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

Python开发的Discord Bot无法加入语音频道,寻求技术帮助

解决Discord Bot !join命令无反应的问题

我太懂这种明明代码没报错但命令就是不生效的憋屈了!看完你的代码,立刻就找到问题所在啦——你自定义了on_message事件,但没有让Bot继续处理命令逻辑。

核心原因

当你手动实现on_message函数后,Discord.py默认的命令处理流程会被覆盖。也就是说,Bot只会执行你在on_message里写的逻辑,完全不会管那些用@client.command装饰的命令(比如你的join)。

修复步骤

只需要在on_message函数的最后一行,加上await client.process_commands(message),让Bot在处理完你的自定义消息逻辑后,继续处理命令即可。

另外还给你加了几个实用优化:

  • 移除了过时的pass_context=True(新版本Discord.py已经自动传递ctx)
  • 给join命令加了用户不在语音频道的判断,避免报错
  • 调整了代码格式,可读性更好

修改后的完整代码:

import discord
from discord.ext import commands
from discord.utils import get
import os
import youtube_dl

token = os.environ.get('DISCORD_TOKEN')
client = commands.Bot(command_prefix='!')

@client.event
async def on_message(message):
    channels = ['bot-commands']
    if str(message.channel) in channels:
        if message.content == '!help':
            embed = discord.Embed(title='How to use the ImposterBot', description='Useful Commands')
            embed.add_field(name='!help', value='Display all the commands')
            embed.add_field(name='!music', value='Play a music playlist')
            embed.add_field(name='!valorant', value='Get the most recent version of Valorant stats')
            embed.add_field(name='!hello', value='Greet a user')
            await message.channel.send(content=None, embed=embed)
        elif message.content == '!hello':
            await message.channel.send(f'Greeting, {message.author}!')
        elif message.content == '!valorant':
            await message.channel.send('This feature is not ready yet')
        elif message.content == '!music':
            await message.channel.send('This feature is not ready yet')
        elif 'sustin' in message.content:
            await message.channel.send(f"""it's sustin... {"<:monkas:392806765789446144>"} """)
    # 关键:让Bot继续处理命令
    await client.process_commands(message)

@client.command()
async def join(ctx):
    # 判断用户是否在语音频道
    if not ctx.author.voice:
        return await ctx.send("你得先加入一个语音频道呀!")
    
    channel = ctx.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
    
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
    
    await ctx.send(f'Joined {channel.name}')

client.run(token)

额外注意事项

  • 确保你的Bot在服务器里拥有连接语音频道和发言的权限
  • 如果使用的是Discord.py v2.x版本,语法都是兼容的,不需要额外调整
  • 测试的时候记得在bot-commands频道里发命令,或者如果想让命令在全频道生效,可以去掉on_message里的频道判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:42:56