Discord Bot报错CommandNotFound:ping命令未找到,求排查方案
问题分析与修正方案
核心错误点
- 命令注册代码缩进错误:你把
client.add_command(ping)和client.add_command(magic8ball)缩进在了对应命令函数的内部,导致只有当命令被执行时才会触发注册逻辑,但此时命令还未添加到Bot中,自然无法被识别,直接引发CommandNotFound报错。 - 冗余的手动注册操作:使用
@client.command()装饰器时,Discord.py会自动完成命令注册,不需要额外调用client.add_command();而用@commands.command()装饰的命令,必须在函数外部调用client.add_command()才能完成注册。
修正后的代码
import discord from discord.ext import commands import random # 替换为你从Discord开发者门户获取的有效Bot令牌 Token = "你的Bot令牌" client = commands.Bot(command_prefix="=", intents=discord.Intents.all()) @client.event async def on_ready(): print("Bot is connected to Discord") # 方式1:@client.command()自动注册命令 @client.command() async def ping(ctx): await ctx.send("pong") # 方式2:@commands.command()手动注册(注册代码放在函数外部) @commands.command() async def magic8ball(ctx, *, question): # 路径用正斜杠或双反斜杠避免转义问题 with open("Discordbot_rank/magicball.txt", "r") as f: random_responses = f.readlines() response = random.choice(random_responses) await ctx.send(response) client.add_command(magic8ball) client.run(Token)
额外注意事项
- 确保
Token变量已正确赋值为你的Bot令牌,字符串需加引号。 - 检查
magicball.txt文件路径是否正确,Windows环境建议用Discordbot_rank\\magicball.txt,避免转义字符问题。 - 确认Bot已被邀请到目标服务器,且拥有发送消息、读取频道消息等必要权限。
内容的提问来源于stack exchange,提问作者Kudo
相关产品推荐
相关产品推荐

