You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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()是阻塞式方法,代码执行到这一行时会直接启动机器人并保持事件循环运行,后续写的事件监听注册、命令注册逻辑永远不会被执行,直接导致两个问题:

  1. on_ready事件监听函数没有被注册到客户端,启动后自然不会触发
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 08:00:58