使用discord.py Cogs重构机器人遇‘ping命令未找到’错误求助
问题分析与解决
核心问题
Cog未在启动阶段加载
你把bot.add_cog(General(bot))放在了ping命令的内部,但此时ping命令属于未被加载的GeneralCog,Bot根本无法识别这个命令,自然会提示"Command 'ping' is not found"。bot.run位置错误bot.run(os.environ['token'])没有放在if __name__ == '__main__':代码块内,可能导致模块被导入时意外执行启动逻辑。重复添加Cog风险
就算能触发ping命令,每次执行都会重复添加同一个Cog,引发不必要的资源占用和潜在冲突。
修正后的代码
import discord import os import keep_alive from discord.ext import commands from discord.ext.commands import BucketType, BadArgument, cooldown intents = discord.Intents().all() bot = commands.Bot(command_prefix=',', intents=intents) p = ',' class General(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def test(self, ctx): await ctx.channel.send("I'm **alive**.") @commands.command() async def ping(self, ctx): # 用self.bot代替全局bot,符合Cog封装原则 await ctx.send(f'⏱|** {round(self.bot.latency * 1000)} ms** Latency!') # Bot就绪后自动加载Cog @bot.event async def on_ready(): await bot.add_cog(General(bot)) print(f"已登录为 {bot.user}") if __name__ == '__main__': keep_alive.keep_alive() bot.run(os.environ['token'])
修改说明
- 将Cog加载逻辑移到
on_ready事件中,Bot启动就绪后自动注册所有Cog内的命令。 - 把
bot.run放入if __name__ == '__main__':代码块,保证只有直接运行脚本时才启动Bot。 - 在
ping命令中使用self.bot代替全局变量bot,遵循Cog的封装规范,降低耦合度。
内容的提问来源于stack exchange,提问作者issac
相关产品推荐
相关产品推荐

