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

discord.py中Cogs无法加载及ping命令失效问题求助

问题分析

你的核心问题是异步的Cog加载函数load()从未被执行,导致Cogs根本没被加载,所以.ping命令找不到。直接去掉async/await会导致协程未正确执行,加载不完整,出现警告的同时命令仍无法使用。

解决方案

1. 正确调用异步加载函数

discord.py v2.x版本中,加载扩展必须使用异步方式,且需要确保load()函数被执行。推荐以下两种官方认可的方式:

方法一:使用setup_hook初始化钩子

修改main.py,添加setup_hook事件在Bot启动前加载Cogs:

import discord
from discord.ext import commands
from discord import app_commands
from webserver import keep_alive
import os

intents = discord.Intents.all()

client = commands.Bot(command_prefix = ".",intents=intents)

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('bot online'))
    print ("Bot is currently online!")

@client.event
async def setup_hook():
    # 在Bot启动前执行Cog加载逻辑
    await load()

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
            print(f"Loaded Cog: {filename[:-3]}")
        else:
            # 跳过非py文件(如__pycache__文件夹)
            continue

keep_alive()
token = os.environ.get("discord_bot_secret")
client.run(token)

方法二:用asyncio.run整合加载与启动逻辑

将Cog加载和Bot启动放在同一个异步主函数中:

import discord
from discord.ext import commands
from discord import app_commands
from webserver import keep_alive
import os
import asyncio

intents = discord.Intents.all()

client = commands.Bot(command_prefix = ".",intents=intents)

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('bot online'))
    print ("Bot is currently online!")

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
            print(f"Loaded Cog: {filename[:-3]}")
        else:
            continue

async def main():
    await load()
    await client.start(token)

keep_alive()
token = os.environ.get("discord_bot_secret")
asyncio.run(main())

2. 优化Cog文件(可选但规范)

你的cogs/ping.py功能正常,建议将类名改为大写(符合Python命名规范),不影响功能但代码更易读:

import discord
from discord.ext import commands

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

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

def setup(client):
    client.add_cog(Ping(client))
失败原因复盘
  • 最初代码中仅定义了load()函数但未调用,Cogs完全没被加载,所以找不到.ping命令。
  • 去掉async/await后,client.load_extension作为协程未被正确等待,虽然打印了加载日志,但Cog并未完成注册,命令仍不可用,同时触发协程未执行的警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:05:36