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

使用discord.py创建上下文菜单(Apps)遇到问题求助

解决discord.Client上下文菜单无法显示的问题

以下是针对discord.Client版本代码的问题排查和解决方案:

1. 确认discord.py版本要求

上下文菜单是discord.py 2.0及以上版本新增的功能,先确保你的库是最新版:

pip install -U discord.py

2. 正确实现上下文菜单并注册

使用discord.Client时,需要通过CommandTree来注册上下文菜单,并且必须完成命令同步操作,否则菜单不会显示。

完整示例代码

import discord
from discord import app_commands

class CustomClient(discord.Client):
    def __init__(self, intents: discord.Intents):
        super().__init__(intents=intents)
        # 初始化命令树,用于管理上下文菜单和slash命令
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        # 测试阶段建议同步到指定服务器(立即生效),替换为你的服务器ID
        test_guild = discord.Object(id=123456789012345678)
        # 将全局命令复制到测试服务器
        self.tree.copy_global_to(guild=test_guild)
        # 同步命令到该服务器
        await self.tree.sync(guild=test_guild)

# 定义用户上下文菜单(右键用户触发)
@app_commands.context_menu(name="获取用户ID")
async def get_user_id(interaction: discord.Interaction, user: discord.User):
    await interaction.response.send_message(f"{user.display_name}的ID:{user.id}", ephemeral=True)

# 定义消息上下文菜单(右键消息触发)
@app_commands.context_menu(name="获取消息ID")
async def get_message_id(interaction: discord.Interaction, message: discord.Message):
    await interaction.response.send_message(f"消息ID:{message.id}", ephemeral=True)

# 配置Bot意图,至少开启默认意图,需要处理消息则开启message_content
intents = discord.Intents.default()
intents.message_content = True

# 初始化客户端
client = CustomClient(intents=intents)

# 将上下文菜单添加到命令树
client.tree.add_command(get_user_id)
client.tree.add_command(get_message_id)

# 启动Bot,替换为你的Bot令牌
client.run("YOUR_BOT_TOKEN")

3. 常见问题排查

  • 权限问题:确保Bot在目标服务器拥有applications.commands权限,建议给Bot分配管理员权限测试
  • 同步方式:全局同步(不带guild参数的await self.tree.sync())需要1小时左右生效,测试优先用服务器同步
  • 意图配置:如果是消息上下文菜单,需要开启message_content意图,并且在Discord开发者后台的Bot页面开启对应的意图开关
  • Bot在线状态:只有Bot在线时,上下文菜单才会显示在右键菜单中
  • 频道限制:部分受限频道(如系统频道)可能无法触发,换普通文本频道测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:27:50