Discord机器人$script命令无响应问题求助
问题排查与修复
你的代码核心问题是同时初始化了discord.Client和commands.Bot两个实例,却只启动了Client实例,而命令是注册在Bot实例上的,自然不会被触发。
修复步骤:
- 移除多余的
discord.Client相关代码,只保留commands.Bot实例——Bot是Client的子类,具备所有Client的功能,同时支持命令系统。 - 调整
on_ready事件的注册对象,改为绑定到bot实例。 - 启动时调用
bot.run()而非client.run()。
修复后的代码:
import discord import os from discord.ext import commands # 初始化所需的intents intents = discord.Intents.all() # 只保留Bot实例,指定命令前缀和intents bot = commands.Bot(command_prefix='$', intents=intents) @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.command(name="script") async def getscript(ctx): await ctx.channel.send("pong") # 启动Bot实例 bot.run(os.getenv('TOKEN'))
额外注意:
- 确保你的机器人在Discord开发者平台的机器人设置中,开启了「消息内容意图(Message Content Intent)」,否则无法读取用户发送的命令内容。
内容的提问来源于stack exchange,提问作者Cience
相关产品推荐
相关产品推荐

