You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Discord Bot在用户加入Voice Channel时向Text Channel发消息?

问题分析与修复方案

你的代码存在几个关键问题,导致无法正常运行:

  • 过早调用bot.get_channel:Bot实例初始化后还未完成登录连接,此时调用get_channel会返回None,无法获取目标文本频道。
  • 条件判断逻辑错误:你直接判断discord.VoiceChannel.id(类的属性)是否在频道列表里,这完全不对,应该判断用户加入的语音频道ID(即after.channel.id)。
  • 异步方法未加await:channel.send()是异步函数,必须用await关键字调用,否则会引发运行时错误。
  • 未正确配置Intents:Discord Bot需要开启voice_states意图才能监听语音状态变化,同时开启members意图才能正确获取成员信息。

修正后的完整代码

import discord
from discord.ext import commands

# 配置Intents,必须开启voice_states和members意图
intents = discord.Intents.default()
intents.voice_states = True
intents.members = True

bot = commands.Bot(command_prefix='&', intents=intents)

# 定义要监听的语音频道ID列表和目标文本频道ID
TARGET_VOICE_CHANNELS = [1234567890, 0987654321]  # 替换成你的语音频道ID
TARGET_TEXT_CHANNEL_ID = 112233445566  # 替换成你的文本频道ID

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')

@bot.event
async def on_voice_state_update(member, before, after):
    # 判断用户是否从无频道状态加入了指定语音频道
    if not before.channel and after.channel:
        if after.channel.id in TARGET_VOICE_CHANNELS:
            # 获取目标文本频道
            text_channel = bot.get_channel(TARGET_TEXT_CHANNEL_ID)
            if text_channel:
                await text_channel.send(f'{member.mention} 加入了语音频道 {after.channel.name}!')

# 替换成你的Bot Token
bot.run('YOUR_BOT_TOKEN_HERE')

关键修复说明

  1. Intents配置:明确开启voice_states和members意图,这是监听语音状态变化的前提,需要在Discord开发者后台的Bot页面也开启相应的Privileged Gateway Intents。
  2. 延迟获取频道:在on_voice_state_update事件内调用bot.get_channel,此时Bot已经完成连接,能正确获取频道对象。
  3. 修正条件判断:用after.channel.id判断是否在目标语音频道列表中,确保逻辑正确。
  4. 添加await关键字:调用text_channel.send()时加上await,符合异步函数的调用要求。
  5. 增加空值判断:获取文本频道后先判断是否存在,避免因ID错误导致的报错。

内容的提问来源于stack exchange,提问作者naziwin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:13:28