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

Python实现Discord分页Embed:将61条数据按10条分组

解决Discord分页所需的分组数据生成问题

你已经完成了最核心的数据抓取部分,现在只需要调整数据存储的逻辑,把平铺的单条数据改成每10条一组的结构,就能完美适配DiscordUtils的分页功能了。我帮你修改了脚本,尽量保留你原来的代码风格,同时加入分组逻辑,适合刚接触Python的你理解:

import urllib.request, json
from shutil import copyfile
from termcolor import colored
from tinydb import TinyDB, Query

db = TinyDB("/home/nepmia/Myazu/db/db.json")

def api_get():
    print(colored("[Myazu]","cyan"), colored("Fetching WynncraftAPI...", "white"))
    # 新增:创建列表收集所有玩家数据,先不着急存数据库
    all_players = []
    try:
        with urllib.request.urlopen("https://api.wynncraft.com/public_api.php?action=guildStats&command=Spectral%20Cabbage") as u1:
            api_1 = json.loads(u1.read().decode())
            if members := api_1.get("members"):
                print(colored("[Myazu]","cyan"), colored("Got expected answer, starting saving process.", "white"))
                for member in members:
                    nick = member.get("name")
                    ur2 = f"https://api.wynncraft.com/v2/player/{nick}/stats"
                    u2 = urllib.request.urlopen(ur2)
                    api_2 = json.loads(u2.read().decode())
                    data = api_2.get("data")
                    for item in data:
                        meta = item.get("meta")
                        playtime = meta.get("playtime")
                        print(colored("[Myazu]","cyan"), colored("Saving playtime for player", "white"), colored(f"{nick}...","green"))
                        # 修改:把数据添加到临时列表,而不是直接插入数据库
                        all_players.append({"username": nick, "playtime": playtime})
            else:
                print(colored("[Myazu]","cyan"), colored("Unexpected answer from WynncraftAPI [ERROR 1]", "white"))
    except Exception as e:
        # 新增:打印具体异常信息,方便调试
        print(colored("[Myazu]","cyan"), colored(f"Unhandled error in saving process [ERROR 2]: {str(e)}", "white"))
    finally:
        # 新增:将收集到的玩家数据按每10条一组拆分
        grouped_players = [all_players[i:i+10] for i in range(0, len(all_players), 10)]
        # 清空数据库旧数据,插入新的分组结构
        db.truncate()
        db.insert({"groups": grouped_players})
        
        count = len(all_players)
        print(colored("[Myazu]","cyan"), colored(f"Finished saving data for", "white"), colored(f"{count}", "green"), colored("players.", "white"))
        print(colored("[Myazu]","cyan"), colored(f"Data split into", "white"), colored(f"{len(grouped_players)}", "green"), colored("groups for pagination.", "white"))

关键修改点说明:

  1. 临时数据收集:新增all_players列表,先把所有玩家的数据都存到这个列表里,而不是逐条插入数据库,这样方便后续分组。
  2. 分组逻辑:用列表推导式[all_players[i:i+10] for i in range(0, len(all_players), 10)]实现每10条数据一组的拆分,最后一组如果不足10条也会自动保留。
  3. 数据库存储调整:先清空数据库的旧数据(db.truncate()),再把分组后的结构以{"groups": 分组列表}的形式插入,这样后续读取时能直接拿到分页所需的分组数据。
  4. 调试优化:在异常捕获里加入了具体的错误信息打印,方便你排查问题。

后续使用分组数据:

当你需要生成Discord Embed分页时,可以这样从数据库读取分组:

from tinydb import TinyDB
db = TinyDB("/home/nepmia/Myazu/db/db.json")
# 获取分组数据
grouped_data = db.all()[0]["groups"]
# 遍历每个分组生成Embed
for group in grouped_data:
    # 这里写生成单个Embed的逻辑,比如遍历group里的每个玩家添加字段
    pass

这样每个分组正好对应一个Embed,完美避开Discord的消息长度限制,适配分页功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:27:28