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

如何用discord.py制作可浏览的Discord嵌入分页?

解决Discord嵌入分页的数据库存储问题

问题根源

你遇到的错误本质是:discord.Embed对象无法直接被数据库序列化存储,转成字符串后又丢失了对象的方法和属性,导致后续调用to_dict()失败。

可行解决方案

1. 存储嵌入的字典表示

利用discord.Embed的to_dict()方法将对象转为可序列化的字典,存入数据库;加载时用discord.Embed.from_dict()还原成对象。

示例代码:

# 存储时
pages = (entries // 10) + 1
for i in range(pages):
    embed = discord.Embed(title=f"Page {i+1}")
    # 向嵌入添加条目内容...
    embed_dict = embed.to_dict()
    db[f"pagesembed_{i+1}"] = embed_dict  # 将字典存入数据库

# 加载时
embed_dict = db[f"pagesembed_{current_page}"]
embed = discord.Embed.from_dict(embed_dict)
await message.edit(embed=embed)

2. 动态生成分页嵌入(更推荐)

不需要预存所有嵌入到数据库,而是在用户切换页面时,根据当前页码从数据库提取对应范围的条目,实时生成discord.Embed对象。这种方式更节省存储空间,也避免了数据更新时预存嵌入失效的问题。

示例代码:

# 按钮回调函数示例(基于discord.py的Button组件)
@discord.ui.button(label="下一页", style=discord.ButtonStyle.primary)
async def next_page_button(self, interaction: discord.Interaction, button: discord.ui.Button):
    current_page = self.current_page
    total_pages = (self.total_entries // 10) + 1
    if current_page >= total_pages:
        await interaction.response.send_message("已经是最后一页了", ephemeral=True)
        return
    
    self.current_page += 1
    # 从数据库提取当前页的条目:取第(current_page-1)*10到current_page*10条数据
    start_idx = (self.current_page - 1) * 10
    end_idx = self.current_page * 10
    page_entries = self.db_entries[start_idx:end_idx]
    
    # 实时生成嵌入
    embed = discord.Embed(title=f"Page {self.current_page}/{total_pages}")
    for entry in page_entries:
        embed.add_field(name=entry["name"], value=entry["value"], inline=False)
    
    await interaction.response.edit_message(embed=embed)

为什么之前的方法失效

  • 直接存储discord.Embed对象:数据库无法序列化Python复杂对象,导致JSON解码错误。
  • 转成字符串存储:字符串只是对象的文本表示,丢失了discord.Embed的方法和属性,所以调用to_dict()时触发AttributeError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:45:53