如何使用Python和discord.py在Discord bot消息下方添加可点击按钮
使用discord.py实现消息按钮的方法
前提要求
- 确保你使用的是discord.py 2.0及以上版本,旧版本不支持原生消息组件,升级命令:
pip install -U discord.py - 邀请机器人进服时需要勾选
applications.commands权限,否则组件交互可能无法正常触发
基础实现步骤
1. 导入所需模块
import discord from discord.ext import commands from discord.ui import Button, View
2. 创建按钮和绑定回调
按钮需要放在View容器中,你可以自定义View类添加按钮和对应的点击触发逻辑:
# 自定义View类 class SampleView(View): def __init__(self): super().__init__(timeout=None) # timeout设为None代表按钮永久有效 # 定义按钮,参数分别为样式、显示文字、emoji(可选) @discord.ui.button(label="确认", style=discord.ButtonStyle.green, emoji="✅") async def confirm_callback(self, interaction: discord.Interaction, button: Button): # 点击按钮后的触发逻辑 await interaction.response.send_message("你点击了确认按钮", ephemeral=True) # ephemeral=True代表只有点击的用户能看到这条回复 @discord.ui.button(label="取消", style=discord.ButtonStyle.red, emoji="❌") async def cancel_callback(self, interaction: discord.Interaction, button: Button): await interaction.response.send_message("你点击了取消按钮", ephemeral=True)
3. 发送带按钮的消息
在指令或者触发逻辑中,发送消息时传入view参数即可:
@bot.command() async def test_button(ctx): view = SampleView() await ctx.send("请选择操作:", view=view)
额外说明
- 如果你需要做跳转外部链接的按钮,不需要绑定回调,直接在初始化View时添加即可:
class LinkView(View): def __init__(self): super().__init__() self.add_item(Button(label="跳转链接", style=discord.ButtonStyle.link, url="你的链接地址"))
- 按钮样式可选值:
ButtonStyle.primary:蓝紫色(默认)ButtonStyle.secondary:灰色ButtonStyle.success:绿色ButtonStyle.danger:红色ButtonStyle.link:灰色跳转样式,仅用于链接按钮
- 按钮回调中必须给交互一个响应,可使用
await interaction.response.defer()延迟响应,避免界面显示「交互失败」提示。
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

