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

Discord.py开发问询:如何实现示例图所示的交互按钮功能

Discord.py 交互按钮实现教程

你需要的交互按钮效果如下图:
交互按钮示例图

前置要求

  • 你的discord.py版本必须 ≥ 2.0,旧版本不支持原生交互组件
    • 查看版本命令:pip show discord.py
    • 升级到最新版本命令:pip install -U discord.py

实现步骤

1. 导入所需模块

import discord
from discord import ui
from discord.ext import commands

2. 初始化Bot实例

# 开启所需的网关意图
intents = discord.Intents.default()
intents.message_content = True # 如果你使用前缀命令需要开启该项,仅用斜杠命令可以省略
bot = commands.Bot(command_prefix="!", intents=intents)

3. 定义按钮视图类

继承ui.View类,在类中用装饰器定义每个按钮和对应的点击回调逻辑:

class OperationView(ui.View):
    def __init__(self):
        # timeout设为None代表按钮不会自动过期,bot重启后按钮会失效,需要持久化可参考后续说明
        super().__init__(timeout=None)

    # 绿色确认按钮
    @ui.button(label="确认", style=discord.ButtonStyle.green, emoji="✅", custom_id="confirm_btn")
    async def confirm(self, interaction: discord.Interaction, button: ui.Button):
        # 点击按钮后的响应逻辑,ephemeral=True代表仅点击者可见回复
        await interaction.response.send_message("你点击了确认按钮", ephemeral=True)

    # 红色取消按钮
    @ui.button(label="取消", style=discord.ButtonStyle.red, emoji="❌", custom_id="cancel_btn")
    async def cancel(self, interaction: discord.Interaction, button: ui.Button):
        await interaction.response.send_message("你点击了取消按钮", ephemeral=True)

    # 蓝紫色详情按钮
    @ui.button(label="查看详情", style=discord.ButtonStyle.blurple, custom_id="detail_btn")
    async def show_detail(self, interaction: discord.Interaction, button: ui.Button):
        await interaction.response.send_message("这里是详情内容", ephemeral=True)

    # 如果需要跳转链接的按钮,可以在初始化时添加,不需要绑定回调
    def add_link_button(self, label: str, url: str):
        self.add_item(ui.Button(label=label, style=discord.ButtonStyle.url, url=url))

4. 触发带按钮的消息

你可以通过前缀命令或者斜杠命令触发,两种示例如下:

前缀命令触发

@bot.command(name="show_btns")
async def show_buttons(ctx: commands.Context):
    view = OperationView()
    # 可选:添加跳转链接按钮,自行替换为你需要的跳转地址
    # view.add_link_button("访问指定页面", "你的跳转链接")
    await ctx.send("请选择你要执行的操作:", view=view)

斜杠命令触发

@bot.tree.command(name="show_btns", description="显示测试交互按钮")
async def slash_show_buttons(interaction: discord.Interaction):
    view = OperationView()
    await interaction.response.send_message("请选择你要执行的操作:", view=view)

5. 运行Bot

bot.run("你的Bot令牌")

补充说明

  • 按钮样式共5种可选:
    • ButtonStyle.blurple:蓝紫色,默认主操作样式
    • ButtonStyle.green:绿色,用于确认、成功类操作
    • ButtonStyle.red:红色,用于删除、取消等危险操作
    • ButtonStyle.grey:灰色,用于次要操作
    • ButtonStyle.url:带跳转图标的灰色按钮,必须搭配url参数使用
  • 每个按钮的custom_id不能重复,用于区分不同按钮的回调
  • 如果需要按钮在Bot重启后仍然可以正常点击,在Bot启动事件中添加持久化视图即可:
    @bot.event
    async def on_ready():
        bot.add_view(OperationView())
        print(f"已登录为 {bot.user}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:05