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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:20:27