Files
myrzx_bot/ranch_assistant/daily.py
T

112 lines
5.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Read-only daily status and explicitly selected, free reward claims."""
from dataclasses import dataclass, field
from datetime import datetime
import json
from pathlib import Path
from .maps import reward_summary
from .model import Action, seconds
from .quests import CN
def day(now):
return datetime.fromtimestamp(now, CN).date().isoformat()
class DailyLedger:
def __init__(self, path=None):
self.path = Path(path) if path else None
self.state = json.loads(self.path.read_text(encoding="utf-8")) if self.path and self.path.exists() else {}
def seen(self, snapshot, key):
return key in self.state.get(f"{snapshot.raw['master']['id']}:{day(snapshot.now)}", [])
def record(self, snapshot, key):
role_day = f"{snapshot.raw['master']['id']}:{day(snapshot.now)}"
self.state = {role_day: list(dict.fromkeys(self.state.get(role_day, []) + [key]))}
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
temp = self.path.with_suffix(".tmp")
temp.write_text(json.dumps(self.state), encoding="utf-8")
temp.replace(self.path)
@dataclass
class DailyPolicy:
enabled: bool = False
selected: list[str] = field(default_factory=lambda: ["gift", "check", "loop", "vip", "mail"])
@dataclass
class DailyEntry:
key: str
name: str
status: str
reward: str
action: Action | None = None
def entries(catalog, snapshot, ledger=None):
activity = snapshot.raw.get("activityHistory") or {}
table = catalog.data.get("activity_info", {})
result = []
today = day(snapshot.now)
def add(key, name, ready, status, reward, path, payload=None):
if ready and ledger and ledger.seen(snapshot, key):
ready, status = False, "本日已提交,请核对服务器状态"
result.append(DailyEntry(key, name, "可领取" if ready else status, reward_summary(catalog, reward),
Action(kind="daily", path=path, payload=payload or {}, description="领取" + name) if ready else None))
gift = activity.get("dailyGift")
if isinstance(gift, dict):
stamp = seconds(gift.get("dailyGiftCheckTime"))
ready = not stamp or day(stamp) < today
level = max(1, int(gift.get("dailyGiftLevel") or 1))
shown_level = level if ready else 5 if int(gift.get("dailyGiftCount") or 0) > 5 else max(1, level - 1)
add("gift", "每日签到礼包", ready, "今日已领取", table.get("dailyGift", {}).get(str(shown_level)), "dailyGiftService/dailyGiftSign")
else:
add("gift", "每日签到礼包", False, "状态未返回", None, "")
check = activity.get("dailyCheck")
if isinstance(check, dict):
count = int(check.get("checkDay") or 0)
stamp = seconds(check.get("checkTime"))
add("check", f"七日签到(已领{count}/7)", count < 7 and (not stamp or day(stamp) < today),
"已全部领取" if count >= 7 else "今日已领取", table.get("dailyCheck", {}).get(str(min(count, 6))), "dailyCheckService/dailyCheck")
else:
add("check", "七日签到", False, "状态未返回", None, "")
loop = table.get("loopCheckReward") or {}
target = int(loop.get("dayNum") or 0)
count = min(int((gift or {}).get("dailyGiftCount") or 0), target)
if gift:
stamp, previous = seconds(gift.get("dailyGiftCheckTime")), seconds(gift.get("dailyRewardGetTime"))
count = max(0, min(count, (datetime.fromtimestamp(stamp, CN).date() - datetime.fromtimestamp(previous, CN).date()).days))
add("loop", "累计签到奖励", bool(gift and loop.get("open") and target and count >= target),
f"累计 {count}/{target} 天" if loop.get("open") else "活动未开放", loop.get("reward"), "dailyGiftService/dailyLoopReward")
vip = activity.get("vipInfo") or {}
expiry = seconds(vip.get("vipTime"))
stamp = seconds(vip.get("getTime"))
active = expiry > snapshot.now and day(expiry) > today
add("vip", "VIP每日奖励", active and (not stamp or day(stamp) < today), "今日已领取" if active else "无有效VIP资格",
catalog.data["game_setting"].get("vipReward"), "vipService/getReward")
for mail in snapshot.raw.get("mails") or []:
mid = int(mail["id"])
reward = reward_summary(catalog, mail.get("reward"))
# MailVo.overday: normal mail lasts seven calendar days.
stamp = seconds(mail.get("createTime"))
expired = bool(stamp and (datetime.fromtimestamp(snapshot.now, CN).date() - datetime.fromtimestamp(stamp, CN).date()).days >= 7)
claimed = mail.get("isGetReward") in (1, True, "1")
key = f"mail:{mid}"
add(key, "邮件:" + str(mail.get("title") or mid), bool(reward and reward != "附件格式未知" and not claimed and not expired),
"已过期" if expired else "已领取" if claimed else "无附件" if not reward else "附件格式未知", mail.get("reward"), "mailService/mailGetReward", {"mailId": mid})
return result
def selected_entries(catalog, snapshot, policy, ledger):
return [row for row in entries(catalog, snapshot, ledger) if row.action and
(row.key in policy.selected or row.key.startswith("mail:") and "mail" in policy.selected)]