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

discord.py 2.0更新后Cogs无法正常工作的问题求助

Discord.py 2.0升级后Cogs命令无法使用的解决方案

问题根源

升级到discord.py 2.0后,你的代码存在几个关键兼容性问题:

  • 命令上下文参数错误:discord.py 2.0要求前缀命令的第一个参数必须是commands.Context对象(通常命名为ctx),你的代码里用msg替代,导致命令无法正确接收上下文触发。
  • 未配置命令前缀:discord.py 2.0中commands.Bot初始化必须显式指定command_prefix,否则前缀命令不会生效。
  • 缺少必要Intents配置:2.0强制要求显式启用所需Intents,尤其是message_content Intent,否则机器人无法接收用户消息,自然无法响应命令。

修复步骤

1. 修正Cogs中的命令参数

将命令第一个参数改为ctx,并通过ctx.send()发送消息(ctx包含完整上下文,原消息对象可通过ctx.message获取):

from Utils import *

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

    @commands.command()
    @commands.is_owner()
    async def ping(self, ctx):
        await ctx.send("Only the owner can use this command!")

    @commands.command()
    @commands.is_owner()
    async def remove(self, ctx, userId: int):
        db.find_one_and_delete({"UserID": userId})
        await ctx.send(f"Removed <@{userId}> from the database!")

async def setup(client):
    await client.add_cog(Owner(client))

2. 修正主程序的Bot初始化逻辑

显式配置命令前缀和所需Intents,确保机器人能接收消息并响应前缀命令:

from Utils import *
import discord
from discord.ext import commands
import asyncio

# 配置Intents
intents = discord.Intents.default()
intents.message_content = True  # 必须启用,否则无法读取消息内容
intents.members = True  # 按需启用,处理成员相关操作时需要

# 初始化Bot,指定命令前缀和Intents
client = commands.Bot(command_prefix="!", intents=intents)

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

# 客户端连接
async def main():
    async with client:
        await load()
        await client.start(config.token)

asyncio.run(main())

3. 启用开发者门户的特权Intents

登录Discord开发者门户,进入你的机器人页面,在Privileged Gateway Intents部分开启Message Content Intent,否则机器人无法读取用户发送的消息内容。

额外验证

  • 确认你的机器人使用的是commands.Bot()而非discord.Client(),后者不支持前缀命令系统。
  • 检查Cogs文件所在的BotCommands目录是否包含__init__.py文件(空文件即可),确保Python能识别为合法模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:41:18