Discord.py无法注册Cog:自定义命令无响应求助
Discord机器人自定义命令无响应问题排查与修复
核心问题分析
- 命令处理逻辑被中断:使用
commands.Bot时,自定义on_message事件会覆盖默认的命令解析流程,必须显式调用client.process_commands()才能让机器人识别并执行命令。 - 调用不存在的函数:bot.py中调用了
responses.handle_commands(message),但responses.py中未定义该函数,运行时会触发异常,阻塞后续逻辑执行。 - Cog加载方式冗余:同时使用手动
add_cog和setup函数,虽不直接报错,但不符合discord.py的规范,可能引发潜在问题。
修复步骤
1. 恢复命令处理逻辑
在on_message事件末尾添加await client.process_commands(message),确保机器人能解析命令。
2. 删除无效函数调用
移除bot.py中response = await responses.handle_commands(message)及相关发送逻辑,因为该函数不存在。
3. 规范Cog加载(可选但推荐)
用load_extension替代手动add_cog,这是discord.py加载扩展的标准方式。
修改后的代码
bot.py
import discord from discord.ext import commands def run_discord_bot(): TOKEN = 'TOKEN' intents = discord.Intents.default() intents.message_content = True intents.members = True client = commands.Bot(command_prefix='-', intents=intents) client.remove_command("help") @client.event async def on_ready(): await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="test")) print(f'{client.user} is now running!') # 标准扩展加载方式 await client.load_extension("responses") @client.event async def on_message(message): if message.author == client.user or str(message.author) == "Console#5220": return username = str(message.author) user_message = str(message.content) channel = str(message.channel) print(f'{username} said: "{user_message}" ({channel})') # 关键:触发命令处理 await client.process_commands(message) client.run(TOKEN)
responses.py
from datetime import datetime import json import discord from discord.ext import commands class CommandsCog(commands.Cog): def __init__(self, client): self.client = client @commands.command() # @commands.cooldown(1, 1800, commands.BucketType.user) async def alarm(self, ctx): await ctx.send("MSG") async def setup(client): await client.add_cog(CommandsCog(client))
内容的提问来源于stack exchange,提问作者Xanderl
相关产品推荐
相关产品推荐

