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

discord.py中Cog内用户安装的Hybrid命令无法注册求助

问题解决:Discord.py Cog中带@app_commands.user_install()的Hybrid命令无法全局生效

问题根源

@app_commands.user_install()装饰器与Cog内Hybrid命令的全局注册逻辑存在冲突,导致命令仅被绑定到初始服务器,无法在DM或其他服务器完成注册。

解决方案

1. 替换装饰器为install_params参数

直接在hybrid_command定义中通过install_params指定用户安装权限,避免装饰器干扰Cog的命令注册流程:

from discord import app_commands
from discord.ext import commands

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

    @commands.hybrid_command(
        name="your_command",
        description="你的命令描述",
        install_params=app_commands.InstallParams(user_install=True)
    )
    async def your_command(self, ctx: commands.Context):
        await ctx.send("命令执行成功!")

async def setup(bot):
    await bot.add_cog(YourCog(bot))

2. 确保全局命令同步

在Bot就绪事件中执行全局命令同步,不要限制仅特定服务器:

@bot.event
async def on_ready():
    await bot.tree.sync()  # 同步全局应用命令
    print(f"Logged in as {bot.user}")

3. 检查Cog加载逻辑

确保Cog是全局加载,不要在add_cog时指定特定Guild:

# 正确加载方式
async def setup(bot):
    await bot.add_cog(YourCog(bot))

# 错误示例(会限制Cog仅在指定Guild生效)
# async def setup(bot):
#     await bot.add_cog(YourCog(bot), guild=discord.Object(id=123456789))

4. 验证权限配置

  • 确保Bot在目标服务器拥有应用命令相关权限
  • 确认用户在DM中能正常与Bot交互(未被Bot或用户屏蔽)

补充说明

拆分函数、组合装饰器等操作无效,是因为核心冲突来自装饰器与Cog命令注册机制的不兼容,改用install_params参数可以在保留用户安装配置的同时,让Hybrid命令正常完成全局注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:43:14