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

如何修复Discord机器人的discord.ext.commands.errors.CommandNotFound错误?

问题解决:Discord Bot 命令未找到错误

错误原因

你当前的代码仅注册了test这一个命令,只有输入?test 内容时才会触发AI回复。当输入?hallo这类未注册的命令时,Discord.py找不到对应的命令处理函数,就会抛出CommandNotFound错误。

解决方案

如果你的需求是所有以?开头的消息都触发AI回复,不需要指定固定命令名,应该改用on_message事件来处理,而非@bot.command()装饰的命令。修改后的代码如下:

import discord
import openai
from discord.ext import commands

bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
# 注意:不要将Token和API Key硬编码在代码中,建议使用环境变量管理
token = "你的Discord Bot Token"
openai.api_key = "你的OpenAI API Key"

@bot.event
async def on_ready():
    print("\033[32m\033[1m" + "Success: Bot is connected to Discord!")

@bot.event
async def on_message(message):
    # 忽略Bot自身发送的消息,避免触发无限循环
    if message.author == bot.user:
        return
    
    # 判断消息是否以命令前缀?开头
    if message.content.startswith(bot.command_prefix):
        # 提取前缀后的内容作为查询(也可直接传入完整消息内容给OpenAI)
        query = message.content[len(bot.command_prefix):].strip()
        # 处理仅输入?无内容的情况
        if not query:
            await message.channel.send("请输入要查询的内容")
            return
        
        try:
            response = openai.Completion.create(
                model="text-davinci-003",
                prompt=query,
                temperature=0.5,
                max_tokens=60,
                top_p=0.3,
                frequency_penalty=0.5,
                presence_penalty=0.0
            )
            # 提取并发送AI回复内容
            reply_content = response['choices'][0]['text'].strip()
            await message.channel.send(reply_content)
        except Exception as e:
            await message.channel.send(f"处理请求时出错:{str(e)}")
    
    # 必须保留此行,否则后续添加的其他命令会失效
    await bot.process_commands(message)

bot.run(token)

关键说明

  • 用on_message事件监听所有消息,筛选出以?开头的消息进行处理,覆盖所有自定义前缀内容的场景。
  • 添加Bot自身消息过滤,防止循环回复。
  • 增加异常处理,避免API调用失败导致Bot崩溃。
  • 保留await bot.process_commands(message),确保后续若添加其他命令仍能正常运行。

内容的提问来源于stack exchange,提问作者Max P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:15:27