为何Discord中ctx.send(arg)无法发送arg?机器人命令故障排查
Discord机器人命令不生效的问题解决
你代码的核心问题是同时创建了discord.Client和commands.Bot两个独立的客户端实例,但实际运行的是Client实例(所以$hello的消息逻辑能正常工作),而负责命令系统的Bot实例根本没被启动,自然无法响应?test这类命令。
修复步骤:
- 移除冗余的
discord.Client实例以及对应的事件绑定,因为commands.Bot是Client的子类,完全可以替代普通Client的功能,同时自带命令系统。 - 将
on_ready事件绑定到Bot实例上。 - 最后调用
bot.run()启动机器人,而非client.run()。
修正后的完整代码:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 仅保留Bot实例,兼顾消息处理与命令系统 bot = commands.Bot(command_prefix='?', intents=intents) @bot.event async def on_ready(): print(f'We have logged in as {bot.user}') @bot.command() async def test(ctx, arg): await ctx.send(arg) # 替换为你的机器人令牌 bot.run('YOUR_BOT_TOKEN')
额外说明:
如果需要保留message.content.startswith这类自定义消息处理逻辑,直接给Bot绑定on_message事件即可,但必须在事件末尾调用await bot.process_commands(message),否则命令系统会被屏蔽:
@bot.event async def on_message(message): if message.content.startswith('$hello'): await message.channel.send('Hello!') # 必须添加此行,确保命令系统能正常处理消息 await bot.process_commands(message)
内容的提问来源于stack exchange,提问作者DrogaMleczna
相关产品推荐
相关产品推荐

