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

discord.py 2.0如何在Cogs中配置Slash Commands?加载扩展失败

在discord.py 2.0中配置Cogs与Slash Commands的问题

问题说明

在discord.py 2.0中实现Slash Commands时,已写出可正常运行的基础代码,但不清楚如何在Cogs中配置该功能,参考类似机制的方案后仍无法解决,同时load_extensions函数无法正常工作。

现有基础运行代码

import discord
from discord import app_commands
import os, asyncio

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False # 避免机器人重复同步命令
        self.tree = app_commands.CommandTree(self)  # 将CommandTree设为客户端属性

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await self.tree.sync()  # 留空为全局同步(需1-24小时生效),可指定guild参数实现服务器即时同步
            self.synced = True
        print(f"已登录为 {self.user}.")

client = aclient()

@client.tree.command(name = 'hello', description='打招呼!')
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"你好呀!", ephemeral = True) 

client.run("你的令牌")

现有load_extensions函数代码

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

解决方案

1. 修复load_extensions函数的调用问题

原代码未调用load_extensions,且client.run是同步方法,需用asyncio.run包裹加载扩展和启动客户端的逻辑,修改主文件的启动部分:

async def main():
    await load_extensions()
    await client.start("你的令牌")

if __name__ == "__main__":
    asyncio.run(main())

注意:替换原代码中的client.run("你的令牌")为上述代码,避免同步/异步逻辑冲突。

2. 在Cogs中配置Slash Commands的正确方式

创建Cog文件(例如cogs/test.py),使用app_commands装饰器定义命令,并在setup函数中注册到客户端的CommandTree:

import discord
from discord import app_commands
from discord.ext import commands

class TestCog(commands.Cog):
    def __init__(self, client: discord.Client):
        self.client = client

    @app_commands.command(name="cog_hello", description="来自Cog的问候")
    async def cog_hello(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"这是Cog里的命令!你好呀 {interaction.user.name}", ephemeral=True)

    # 可选:添加服务器专属命令
    @app_commands.command(name="guild_only", description="仅当前服务器可用的命令")
    @app_commands.guilds(discord.Object(id="你的服务器ID"))
    async def guild_only_cmd(self, interaction: discord.Interaction):
        await interaction.response.send_message("这是服务器专属命令!")

async def setup(client: discord.Client):
    await client.add_cog(TestCog(client))
    # 同步Cog中的命令(可选,若主文件已全局同步可省略)
    await client.tree.sync(guild=discord.Object(id="你的服务器ID"))

3. 关键注意事项

  • 确保cogs文件夹与主文件同级,且文件夹内存在空的__init__.py文件,否则Python无法识别为合法模块。
  • 全局命令同步需1-24小时生效,测试阶段建议指定服务器ID实现即时同步。
  • Cog中的命令必须通过setup函数添加到客户端,且需将CommandTree设为客户端的属性,方便Cog内部访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:55:26