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

Discord机器人ping命令未找到错误 求排查修复方案

修复Discord.py中Cog命令未找到的问题(CommandNotFound: Command "ping" is not found)

问题诊断

你的代码存在两个核心问题导致ping命令无法被识别:

  1. 批量加载Cog的main()函数未执行:你定义了用于自动加载所有cogs的main()函数,但从未调用它,导致ping.py里的Cog完全没被加载到机器人中。
  2. 同步加载扩展的异步兼容性问题:在异步函数main()中使用了同步的bot.load_extension(),Discord.py v2.0+要求在异步上下文里使用await bot.load_extension()来加载扩展。

另外需要确认你的文件结构是否正确:cog文件必须放在./cogs/目录下,且文件名与加载时的名称对应(比如你的cog文件是ping.py,加载路径就是cogs.ping)。

修复方案

1. 修改main.py,正确调用异步加载逻辑

将原来直接调用bot.run()的方式,改为通过异步main()函数启动机器人,并在其中完成cog加载:

import discord
from discord.ext import commands, tasks
from discord import app_commands 
import json
import os
import asyncio

file = open('config.json', 'r')
config = json.load(file)

intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(config['prefix'], intents=intents, help_command=None)


@bot.command()
async def load(ctx, extension):
    if ctx.author.id == config['myid']:
        await bot.load_extension(f'cogs.{extension}')
        await ctx.send('Cog已加载...')
    else:
        await ctx.send('你不是开发者。')

@bot.command()
async def unload(ctx, extension):
    if ctx.author.id == config['myid']:
        await bot.unload_extension(f'cogs.{extension}')
        await ctx.send('Cog已卸载...')
    else:
        await ctx.send('你不是开发者。')

@bot.command()
async def reload(ctx, extension):
    if ctx.author.id == config['myid']:
        await bot.unload_extension(f'cogs.{extension}')
        await bot.load_extension(f'cogs.{extension}')
        await ctx.send('Cog已重载...')
    else:
        await ctx.send('你不是开发者。')


async def main():
    # 异步加载所有cogs
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')
    # 启动机器人
    await bot.start(config['token'])

# 运行异步main函数
asyncio.run(main())

2. (可选)规范Cog类名

虽然不影响功能,但根据PEP8规范,类名建议使用大驼峰命名,将ping类改为Ping:

# cog.py
import discord
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print('Bot已连接')

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong')


async def setup(bot):
    await bot.add_cog(Ping(bot))

3. 确认文件结构

确保你的项目目录结构如下:

你的项目文件夹/
├── main.py
├── config.json
└── cogs/
    └── ping.py

验证修复

运行修改后的代码,机器人启动后会自动加载cogs/ping.py中的Cog,此时发送[你的前缀]ping就能触发命令回复Pong了。

内容的提问来源于stack exchange,提问作者Effectys

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:25:00