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

Pycord中Cog内斜杠命令在Discord中不可见问题求助

问题解决指南

一、Cog内on_ready监听器不生效的修复

Cog中的事件监听器必须用@commands.Cog.listener()装饰器标记,否则不会被Bot识别。正确写法如下:

class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print("Moderation Cog已就绪")

二、Cog内斜杠命令不显示的修复步骤

1. 修正guild_ids的类型问题

你的代码里servers是字符串列表,但Discord要求服务器ID必须是整数类型。把服务器ID改成整数格式:

# 替换成你的服务器整数ID
servers = [123456789012345678]

2. 同步命令到目标服务器

斜杠命令需要主动同步到对应服务器才会显示。在主文件的on_ready事件中添加同步逻辑:

# main.py中的on_ready示例
@bot.event
async def on_ready():
    print(f"Bot已登录为 {bot.user}")
    # 同步Moderation Cog中的服务器专属命令
    for guild_id in Moderation.servers:
        await bot.tree.sync(guild=discord.Object(id=guild_id))
    print("命令同步完成")

3. 确认Cog的正确加载方式

确保主文件中异步加载了Moderation Cog,示例代码:

# main.py示例
import discord
from discord.ext import commands
from moderation_cog import Moderation

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def main():
    async with bot:
        await bot.add_cog(Moderation(bot))
        await bot.start("你的Bot Token")

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

4. 检查权限装饰器的导入

确保default_permissions的导入路径正确,需要添加:

from discord import default_permissions

修正后的完整Moderation Cog代码

import discord
from discord.ext import commands
from discord import default_permissions

class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # 服务器ID必须为整数
    servers = [123456789012345678]

    @commands.Cog.listener()
    async def on_ready(self):
        print("Moderation Cog已加载完成")

    @commands.slash_command(name="clear", guild_ids=servers)
    @default_permissions(manage_messages=True)
    async def clear_cmd(self, ctx, number: discord.Option(discord.SlashCommandOptionType.integer, required=True)):
        await ctx.channel.purge(limit=number)
        # 添加执行反馈,让用户确认操作成功
        await ctx.respond(f"已清除{number}条消息", ephemeral=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:05:04