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

如何在discord.py 2.2.3中实现带按钮的分页嵌入菜单斜杠命令

实现带可点击导航按钮的分页嵌入斜杠命令(discord.py 2.2.3)

核心方案

利用discord.py 2.2.3内置的discord.ui.View和discord.ui.Button组件实现导航按钮,自定义分页逻辑管理页面数据与页码,通过CommandTree绑定斜杠命令触发。

完整代码实现

import discord
from discord import appcommands

# 初始化客户端,开启必要意图
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = appcommands.CommandTree(client)

class PaginationView(discord.ui.View):
    def __init__(self, data_list, items_per_page=10):
        super().__init__(timeout=None)
        self.data_list = data_list
        self.items_per_page = items_per_page
        self.total_pages = max(1, (len(data_list) + items_per_page - 1) // items_per_page)
        self.current_page = 1

    def generate_embed(self):
        # 计算当前页元素范围
        start_idx = (self.current_page - 1) * self.items_per_page
        end_idx = start_idx + self.items_per_page
        current_items = self.data_list[start_idx:end_idx]

        # 构建嵌入内容
        embed = discord.Embed(title="分页列表", color=discord.Color.blue())
        embed.description = "\n".join([f"{i+1}. {item}" for i, item in enumerate(current_items)])
        embed.set_footer(text=f"第 {self.current_page}/{self.total_pages} 页")
        return embed

    @discord.ui.button(label="上一页", style=discord.ButtonStyle.gray, disabled=True)
    async def prev_page(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.current_page -= 1
        # 更新按钮状态
        self.prev_page.disabled = self.current_page == 1
        self.next_page.disabled = self.current_page == self.total_pages
        await interaction.response.edit_message(embed=self.generate_embed(), view=self)

    @discord.ui.button(label="下一页", style=discord.ButtonStyle.gray)
    async def next_page(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.current_page += 1
        # 更新按钮状态
        self.prev_page.disabled = self.current_page == 1
        self.next_page.disabled = self.current_page == self.total_pages
        await interaction.response.edit_message(embed=self.generate_embed(), view=self)

@tree.command(name="分页列表", description="展示带导航按钮的分页嵌入消息")
async def pagination_command(interaction: discord.Interaction):
    # 替换为你的实际数据列表
    sample_data = [f"元素{i}" for i in range(1, 35)]
    view = PaginationView(sample_data, items_per_page=10)
    await interaction.response.send_message(embed=view.generate_embed(), view=view)

# 同步斜杠命令(首次运行需执行)
@client.event
async def on_ready():
    # 服务器同步(即时生效),全局同步去掉guild参数(需1小时左右生效)
    await tree.sync(guild=discord.Object(id=你的服务器ID))
    print(f"已登录为 {client.user}")

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

关键细节说明

  • 视图超时设置:将View的timeout设为None,按钮长期有效;如需超时失效,可设置具体秒数(如timeout=300表示5分钟后失效)
  • 按钮状态控制:每次点击后根据当前页码更新按钮禁用状态,避免无效操作
  • 数据切片逻辑:通过(current_page-1)*items_per_page计算起始索引,确保每页展示固定数量元素
  • 命令同步:开发阶段建议用服务器ID同步,命令即时生效;全局同步适合正式发布场景

注意事项

  • 需在Discord开发者门户的Bot设置中开启message_content意图
  • 替换代码中的你的服务器ID和你的Bot令牌为实际值
  • 实际使用时将sample_data替换为你的业务数据源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:07:53