discord.py报错CommandNotFound:test命令不存在且未打印登录信息
问题表现
- 执行
yt!test命令时控制台抛出异常:discord.ext.commands.errors.CommandNotFound: Command "test" is not found,提示命令不存在 - 机器人启动后未触发
on_ready事件,控制台未打印登录成功的日志,无法确认运行状态
原问题代码如下:
from discord.ext import commands import os client = commands.Bot(command_prefix=commands.when_mentioned_or("yt!")) TOKEN = os.environ['token'] client.run(TOKEN) @client.event async def on_ready(): print(f"Logged in as {client.user}") @client.command() async def test(ctx): ctx.reply("Test")
故障原因
client.run()是阻塞式方法,代码执行到这一行时会直接启动机器人并保持事件循环运行,后续写的事件监听注册、命令注册逻辑永远不会被执行,直接导致两个问题:
on_ready事件监听函数没有被注册到客户端,启动后自然不会触发test命令没有被注册到命令列表,调用时直接报命令不存在
另外原代码中ctx.reply()是异步协程方法,缺少await关键字,即使命令注册成功也无法正常回复消息。
修复方法
将client.run(TOKEN)移动到所有事件、命令注册代码的最后,同时给ctx.reply()加上await关键字,修复后完整代码:
from discord.ext import commands import os client = commands.Bot(command_prefix=commands.when_mentioned_or("yt!")) TOKEN = os.environ['token'] @client.event async def on_ready(): print(f"Logged in as {client.user}") @client.command() async def test(ctx): await ctx.reply("Test") # run方法必须放在所有注册逻辑的最末尾 client.run(TOKEN)
修改后重启机器人,就能正常看到登录日志,test命令也可以正常响应。
内容的提问来源于stack exchange,提问作者LargeHotDogs13
相关产品推荐
相关产品推荐

