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

Discord.py Bot使用Cog后无法检测命令的问题求助

Discord.py 切换Cog结构后命令无法检测的问题解决

问题情况

原本将所有命令写在main.py中,改用Cog结构后,机器人无法识别welcome命令,终端报错:

[cogs.Vige]
2024-01-08 21:16:01 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "welcome" is not found

现有代码

main.py

#COGS
initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

print(initial_extensions)

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run(token)

cogs/Vige.py

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

    @commands.command()
    async def welcome(self, ctx):
        await ctx.send("Thanks for the warm welcome! I'm Vige, your personalized chat bot, ready to serve!")
        await ctx.send("https://giphy.com/gifs/starwars-star-wars-episode-3-xTiIzJSKB4l7xTouE8")

def setup(client):
    client.add_cog(Vige(client))

修复步骤

1. 确保使用commands.Bot而非discord.Client

Cog依赖commands框架的命令系统,普通discord.Client不支持该功能。修改main.py开头部分:

import os
import discord
from discord.ext import commands

# 替换为你的机器人token
token = "your_bot_token_here"

# 初始化Bot实例,设置命令前缀并启用必要权限
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())

2. 补全Cog文件的依赖导入

Vige.py中缺少discord.ext.commands的导入,导致命令无法被正确注册。修改文件开头:

from discord.ext import commands

class Vige(commands.Cog):
    # 原有代码保持不变

3. 调整client.run的位置

将client.run(token)移到if __name__ == '__main__':代码块内,确保所有扩展加载完成后再启动机器人:

if __name__ == '__main__':
    for extension in initial_extensions:
        try:
            client.load_extension(extension)
            print(f"成功加载扩展: {extension}")
        except Exception as e:
            print(f"加载扩展失败 {extension}: {str(e)}")
    client.run(token)

4. 启用必要的Intents

前往Discord开发者后台,开启机器人的Message Content Intent权限,否则机器人无法接收用户消息,自然无法响应命令。

验证修复

启动机器人后,终端会输出扩展加载成功的日志,发送!welcome即可触发命令响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:23:10