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

Python脚本自动化更新Discord数据API参数及历史存储求助

解决方案

1. 自动获取最新数据集ID

实现一个函数调用指定接口提取最新roster参数(返回数据中的id字段),替代手动修改的固定值:

import requests

def get_latest_roster_id():
    try:
        response = requests.get("https://api.mir4.gq/v1/latest")
        response.raise_for_status()  # 捕获HTTP请求错误
        return response.json()["id"]
    except requests.exceptions.RequestException as e:
        print(f"获取最新ID失败: {e}")
        # 请求失败时返回默认 fallback 值
        return "32"

初始化MirAPI时传入动态获取的ID:

latest_roster_id = get_latest_roster_id()
api = MirAPI(roster=latest_roster_id)

2. Guild类序列化与历史数据存储

步骤1:给Guild类添加序列化方法

为Guild类编写to_dict()方法,将实例属性转为可JSON序列化的字典:

class Guild:
    def __init__(self, name, score, members_count):
        self.name = name
        self.score = score
        self.members_count = members_count

    def to_dict(self):
        return {
            "name": self.name,
            "score": self.score,
            "members_count": self.members_count,
            "roster_id": latest_roster_id  # 关联对应数据集ID,方便后续对比
        }

步骤2:实现历史数据存储函数

编写函数负责读取/写入本地JSON文件,存储历史数据:

import json
from pathlib import Path

HISTORY_FILE = "guild_history.json"

def save_guild_history(guild_dict):
    # 确保存储目录存在
    Path(HISTORY_FILE).parent.mkdir(exist_ok=True)
    
    # 读取现有历史数据
    try:
        with open(HISTORY_FILE, "r", encoding="utf-8") as f:
            history = json.load(f)
    except FileNotFoundError:
        history = []  # 文件不存在则初始化空列表
    
    # 避免重复存储相同roster_id的数据
    existing_ids = [entry["roster_id"] for entry in history]
    if guild_dict["roster_id"] not in existing_ids:
        history.append(guild_dict)
    
    # 写入回文件
    with open(HISTORY_FILE, "w", encoding="utf-8") as f:
        json.dump(history, f, indent=2, ensure_ascii=False)

3. 整合到完整流程

将模块整合到每日任务脚本中:

# 1. 获取最新roster ID
latest_roster_id = get_latest_roster_id()

# 2. 初始化API并获取数据
api = MirAPI(roster=latest_roster_id)
guild_data = api.fetch_guild_data()  # 替换为你实际获取Guild数据的方法

# 3. 转换为字典并存储历史数据
guild_dict = guild_data.to_dict()
save_guild_history(guild_dict)

# 4. 处理数据并发送Discord Webhook
# 此处编写你原有的数据处理与Webhook发送逻辑
send_discord_webhook(guild_dict)

额外提示

  • 可引入日志模块替代print,方便排查问题
  • 若API有请求频率限制,可添加重试机制(例如使用tenacity库)
  • 历史数据对比时,直接读取JSON文件,对比不同roster_id下的字段变化即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:25:23