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

discord.py v2.1中Cogs与Extensions无法正常工作求助

Discord机器人Cogs命令无法注册的问题解决

尝试将Discord机器人命令拆分到Cogs文件中,但命令无法正常注册。相关代码如下:

bot.py 代码

import json
import os
import discord
from discord.ext import commands


# prefix
def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

intents = discord.Intents.all()

client = commands.Bot(intents=intents, command_prefix=get_prefix, self_bot=True, strip_after_prefix = True)


# cogs
@client.command()
async def load(extension):
    await client.load_extension(f'cogs.{extension}')


@client.command()
async def unload(extension):
    await client.unload_extension(f'cogs.{extension}')


async def load_extension():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')


@client.event
async def on_ready():
    await client.wait_until_ready()
    print('Task 1/6: Logged in as: {0.user.name} Bots user id: {0.user.id}'.format(client))


client.run("my token")

Cogs文件:Onstart.py

import discord
from discord.ext import commands, tasks


class onstart(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        print('Logged in as: {0.user.name}\nBots user id: {0.user.id}'.format(self.client))
        print('Discord.py version:')
        print(discord.__version__)
        print('Ready!')

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f'Ping is {round(self.client.latency * 1000)} ms')

async def setup(client):
    await client.add_cog(onstart(client))
    print("Task 2/6: Onstart.py loaded")

问题原因

核心问题是你定义了load_extension函数用于批量加载Cogs,但从未在代码中调用它。机器人启动后,on_ready事件触发时没有执行这个加载逻辑,导致Cogs文件完全没有被加载,里面的命令自然无法注册。

修复方案

修改on_ready事件处理函数,添加对load_extension的调用:

@client.event
async def on_ready():
    await client.wait_until_ready()
    print('Task 1/6: Logged in as: {0.user.name} Bots user id: {0.user.id}'.format(client))
    # 新增:调用批量加载Cogs的函数
    await load_extension()

额外检查点

  • 确认项目目录下存在cogs文件夹,且Onstart.py确实在该文件夹内
  • 检查prefixes.json文件是否存在且格式正确,避免前缀获取失败导致命令无法触发
  • 确保机器人拥有发送消息等必要权限,即使命令注册成功也需要权限才能响应

内容的提问来源于stack exchange,提问作者Hải Ping Cao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:51:36