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

使用discord.py Cogs重构机器人遇‘ping命令未找到’错误求助

问题分析与解决

核心问题

  1. Cog未在启动阶段加载
    你把bot.add_cog(General(bot))放在了ping命令的内部,但此时ping命令属于未被加载的General Cog,Bot根本无法识别这个命令,自然会提示"Command 'ping' is not found"。

  2. bot.run位置错误
    bot.run(os.environ['token'])没有放在if __name__ == '__main__':代码块内,可能导致模块被导入时意外执行启动逻辑。

  3. 重复添加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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:27:06