如何修复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.
相关产品推荐
相关产品推荐

