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

加载Discord Bot Cog时显示0命令同步,斜杠命令无法使用求助

Discord Bot Cog斜杠命令无法同步问题解决

问题情况

我在给大型Python Discord Bot添加cog时,遇到斜杠命令无法同步的问题:cog能被正常识别并加载,但命令同步时显示0条成功同步,服务器内也无法使用对应的斜杠命令。我编写了一个测试命令,怀疑问题出在cog代码中,而非main.py。

相关代码

main.py

imports

activities = [
    discord.Game(name="help"),
    discord.Game(name="me")
]

intents = discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix='.', intents=discord.Intents.all())
client.remove_command('help')

rcolor = [
    discord.Colour.blurple()
]

@client.event
async def on_ready():
    for file in os.listdir("cogs"):
        if file.endswith(".py"):
            await client.load_extension(f"cogs.{file[:-3]}")
    print("NOAAHBOT is ready, you can now leave the tab")
    embed = discord.Embed(colour=discord.Colour.blurple())
    channel = client.get_channel(channelidhere)
    embed.add_field(name=f'back online',
                    value='noaahbot has been updated.',
                    inline=False)
    await channel.send(embed=embed)
    try:
        synced = await client.tree.sync()
        print(f"synced {len(synced)} commands")
    except Exception as e:
        print(e)
    while True:
        for activity in activities:
            await client.change_presence(activity=activity)
            await asyncio.sleep(2)

client.run("Token")

原cog代码

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

class SayCog(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @commands.command(name="say", description="What should the bot say")
    @app_commands.describe(thing_to_say = "text")
    async def say(interaction: discord.Interaction, thing_to_say: str | None):
        if not interaction.user.guild_permissions.administrator:
            return await interaction.response.send_message("You require administator permisions to use this command")
        if thing_to_say is None:
            await interaction.response.send_message(f'nothing to be said')
        else:
            await interaction.response.send_message(f'{thing_to_say}')


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

错误分析

  1. 装饰器混用:用了@commands.command()(前缀命令装饰器)定义斜杠命令,导致命令被注册为前缀命令而非斜杠命令,无法通过client.tree.sync()同步。斜杠命令需要用@app_commands.command()装饰器。
  2. 类方法参数错误:作为Cog类中的方法,say的第一个参数必须是self(代表类实例),否则方法无法正确绑定到Cog实例,Discord.py无法识别该命令。
  3. 拼写错误:代码中"administator"少了一个字母,正确拼写是"administrator",会影响权限判断的提示信息准确性。

修正后的cog代码

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

class SayCog(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @app_commands.command(name="say", description="What should the bot say")
    @app_commands.describe(thing_to_say = "text")
    async def say(self, interaction: discord.Interaction, thing_to_say: str | None):
        if not interaction.user.guild_permissions.administrator:
            return await interaction.response.send_message("You require administrator permissions to use this command")
        if thing_to_say is None:
            await interaction.response.send_message(f'nothing to be said')
        else:
            await interaction.response.send_message(f'{thing_to_say}')


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

额外注意事项

  • 确保Bot账号在服务器中拥有应用程序命令权限(邀请Bot时勾选applications.commands权限)。
  • 测试服务器可指定服务器ID加快同步:await client.tree.sync(guild=discord.Object(id=你的服务器ID)),全局命令同步可能需要1小时左右生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:12:13