Discord Bot前缀命令!dog无响应求助(无控制台错误)
问题原因与解决办法
核心问题
你同时初始化了两个独立的Discord客户端实例:
- 自定义的
client类(继承自discord.Client),最后通过aclient.run()启动了它 commands.Bot实例bot,但这个实例从未被启动,导致@bot.command装饰的!dog命令完全没被加载运行
Slash命令能正常工作,是因为它绑定到了aclient对应的CommandTree上;而前缀命令属于commands.Bot的功能,你的bot实例根本没在运行,自然无法响应。
修复方案
commands.Bot本身就是discord.Client的子类,已经包含所有客户端功能,同时支持前缀命令和Slash命令,不需要同时使用两者。修改后的代码如下:
import discord import random from discord import app_commands from discord.ext import commands id_do_servidor = my_server_id # 直接使用commands.Bot作为主客户端 bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.event async def on_ready(): await bot.wait_until_ready() # 同步Slash命令到指定服务器 await bot.tree.sync(guild=discord.Object(id=id_do_servidor)) print(f"{bot.user.name} is online.") # 前缀命令绑定到bot实例 @bot.command(name='dog') async def sapo(ctx): await ctx.send('dog') # Slash命令绑定到bot的tree属性 @bot.tree.command(guild=discord.Object(id=id_do_servidor), name='test', description='test') async def slash2(interaction: discord.Interaction): await interaction.response.send_message(f"Working!", ephemeral=True) # 运行唯一的bot实例 bot.run('my_bot_token')
关键修改点
- 移除自定义
client类,统一使用commands.Bot作为主客户端 - 将Slash命令绑定到
bot.tree,不再单独创建CommandTree实例 - 只启动
bot实例,确保所有命令(前缀、Slash)都绑定到同一个运行的客户端上
内容的提问来源于stack exchange,提问作者Francis
相关产品推荐
相关产品推荐

