Discord.py技术问询:能否在右键上下文菜单(Apps)添加命令?
在Discord右键「Apps」板块添加上下文菜单命令(discord.py实现)
要在Discord右键菜单的「Apps」板块添加命令,需要使用discord.py 2.0+版本提供的应用级上下文菜单(app_commands.ContextMenu),这类命令属于Discord官方的应用命令体系,会自动出现在「Apps」板块下。以下是具体实现步骤和示例:
核心实现步骤
- 版本要求:确保你的discord.py版本≥2.0,旧版本不支持应用级上下文菜单。
- 创建上下文菜单:分为「用户上下文菜单」和「消息上下文菜单」两种类型,分别对应右键用户/右键消息时显示的命令。
- 注册并同步命令:将创建好的命令注册到Bot,并同步到Discord服务器(测试时建议指定服务器快速生效)。
完整代码示例
import discord from discord import app_commands from discord.ext import commands # 初始化Bot,按需配置前缀和intents bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # -------------------------- # 示例1:用户上下文菜单(右键用户时显示) # -------------------------- @app_commands.context_menu(name="查看用户详情") async def check_user_detail(interaction: discord.Interaction, user: discord.User): # 构造回复内容 embed = discord.Embed(title=f"{user.display_name} 的信息", color=discord.Color.green()) embed.add_field(name="用户ID", value=user.id, inline=False) embed.add_field(name="账号创建时间", value=user.created_at.strftime("%Y-%m-%d %H:%M"), inline=False) embed.set_thumbnail(url=user.display_avatar.url) # 发送回复,ephemeral=True表示仅当前用户可见 await interaction.response.send_message(embed=embed, ephemeral=True) # -------------------------- # 示例2:消息上下文菜单(右键消息时显示) # -------------------------- @app_commands.context_menu(name="引用这条消息") async def quote_message(interaction: discord.Interaction, message: discord.Message): reply_content = f"> {message.content}\n\n来自用户:{message.author.mention}" await interaction.response.send_message(reply_content) # -------------------------- # 启动Bot并同步命令 # -------------------------- @bot.event async def on_ready(): print(f"已登录:{bot.user.name}") # 同步命令(二选一) # 1. 全局同步:所有服务器生效,但Discord可能需要1小时左右同步完成 # await bot.tree.sync() # 2. 指定服务器同步:仅目标服务器生效,立即生效(推荐测试用) test_guild = discord.Object(id=1234567890) # 替换成你的服务器ID await bot.tree.sync(guild=test_guild) # 运行Bot bot.run("你的Bot令牌")
关键注意事项
- Intents配置:确保开启了
members和messages相关intents,否则可能无法获取用户/消息数据。 - 命令名称:
context_menu装饰器的name参数就是右键菜单中显示的命令名称,支持中文。 - 权限要求:Bot需要在目标服务器拥有「发送消息」等基础权限,否则无法执行命令回复。
内容的提问来源于stack exchange,提问作者Juno
相关产品推荐
相关产品推荐

