feat: 增强福袋参与和预约管理功能,添加统计记录和优化配置参数

This commit is contained in:
Your Name committed 2026-01-04 11:31:54 +08:00
1 parent c0df59ac26
commit 6b9b02bd58
8 files changed
+265 -225

No files matched your search

+49
View File
@@ -95,6 +95,18 @@ def find_and_open_fudai_detail(
)
except Exception:
pass
# 结构化统计:检测到福袋(attempt)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_detected",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
break
elapsed = time.time() - start_time
@@ -213,6 +225,20 @@ def find_and_open_fudai_detail(
)
except Exception:
pass
# 结构化统计:点击尝试
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_click_attempt",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image
@@ -342,6 +368,18 @@ def find_and_open_fudai_detail(
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
try:
# 结构化统计:成功打开详情(success)
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return True
else:
try:
@@ -385,6 +423,17 @@ def find_and_open_fudai_detail(
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_open_detail",
metric_type="fail",
run_id=getattr(analyser, "_run_id", ""),
fudai_x=int(x or 0),
)
except Exception:
pass
return False
except Exception as e:
try:
+113 -167
View File
@@ -179,7 +179,7 @@ class fudai_analyse:
# 高价值阈值(元)
self.high_value_fudai_threshold_yuan: float = 500.0
# 提前参与秒数:开奖前 N 秒回到该直播间并参与
self.high_value_fudai_join_ahead_seconds: int = 120
self.high_value_fudai_join_ahead_seconds: int = 300
# 从当前位置最多回滑多少次以回到预约直播间
self.high_value_fudai_max_swipe_back: int = 35
# 同时记录的最大预约数量
@@ -191,8 +191,6 @@ class fudai_analyse:
# 高价值直播间"回访"相关(当前仅保留配置,不在本地版强制启用复杂逻辑)
self.high_value_room_revisit_enabled: bool = False
self.high_value_room_revisit_only_current_run: bool = False
# 高价值直播间回访间隔(秒):重访间隔,GUI 可配置
self.high_value_room_revisit_interval_seconds: int = 3600
# 粉丝团相关配置
self.auto_join_fansclub: bool = False # 是否自动加入粉丝团
@@ -1340,77 +1338,79 @@ class fudai_analyse:
pass
if is_first_run:
# 首次运行:尝试从状态文件加载预约队列(优先恢复上次运行的队列),若失败则使用空队列
try:
state_path = getattr(self, "_reservations_state_path", None)
loaded: list = []
if state_path:
try:
from douyin.reservation import douyin_reservation as dr
self._log_kv(
"预约",
"[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件",
old_reservations_count=old_reservations_count,
)
except Exception:
pass
# 清空预约队列(强制清空,确保每次启动时队列为空)
try:
# 先记录清空前的状态
before_clear = (
len(self.reservations)
if hasattr(self, "reservations") and self.reservations
else 0
)
self.reservations = []
after_clear = (
len(self.reservations)
if hasattr(self, "reservations")
else 0
)
if hasattr(dr, "load_reservations_state"):
loaded = dr.load_reservations_state(state_path)
else:
# 回退:尝试直接读取状态文件的 JSON 格式
try:
import json
if os.path.exists(state_path):
with open(
state_path, "r", encoding="utf-8"
) as f:
data = json.load(f)
if (
isinstance(data, dict)
and "reservations" in data
):
loaded = data.get(
"reservations", []
)
elif isinstance(data, list):
loaded = data
else:
loaded = []
except Exception:
loaded = []
except Exception:
loaded = []
if loaded:
try:
self.reservations = loaded
self._log_kv(
"预约",
"[预约] 第一次运行:已从状态文件恢复预约队列",
restored_count=len(loaded),
)
except Exception:
# 兜底赋值
self.reservations = loaded
else:
# 未读取到数据或状态文件不存在,使用空队列
try:
self.reservations = []
self._log_kv(
"预约",
"[预约] 第一次运行:未找到预约状态文件或文件为空,使用空队列",
)
except Exception:
self.reservations = []
except Exception as exc:
# 同时清空状态文件,确保外部查看时也是空的
try:
state_path = getattr(self, "_reservations_state_path", None)
if state_path:
# 写入空队列到状态文件
from douyin.reservation.douyin_reservation import (
write_reservations_state,
)
write_reservations_state(
state_path=state_path,
reservations=[],
room_pos=0,
current_room_title="",
current_room_title_raw="",
reason="startup_clear",
)
try:
self._log_kv(
"预约",
"[预约] 已清空预约队列并更新状态文件",
before_clear=before_clear,
after_clear=after_clear,
)
except Exception:
pass
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 清空状态文件时出错",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
except Exception as exc:
# 如果清空失败,尝试直接设置
try:
if hasattr(self, "reservations"):
self.reservations = []
self._log_kv(
"预约",
"[预约] 初始化预约队列时出错,已设置为空队列",
"[预约] 清空预约队列时出错,已尝试直接设置",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
self.reservations = []
except Exception:
pass
# 标记已运行过
try:
self._first_run_once_basic = False
@@ -1846,23 +1846,22 @@ class fudai_analyse:
len(self.reservations) if self.reservations else 0
),
)
# use module-level `douyin_reservation_logic`
try:
douyin_reservation_logic.cleanup_expired_reservations(
self, self.reservations, _write_state
)
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 单间模式下清理过期预约时出错",
error=str(exc),
)
except Exception:
pass
except Exception:
pass
# use module-level `douyin_reservation_logic`
douyin_reservation_logic.cleanup_expired_reservations(
self, self.reservations, _write_state
)
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 单间模式下清理过期预约时出错",
error=str(exc),
)
except Exception:
pass
except Exception:
pass
@@ -2129,8 +2128,8 @@ class fudai_analyse:
base_y=470,
)
self.operation.delay(1.0) # 等待关闭完成
except Exception as exc_outer:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc_outer))
except Exception as exc:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc))
# 如果启用了自动加入,等待页面加载后再次点击(如果需要)
if getattr(self, "auto_join_fansclub", False):
@@ -2486,33 +2485,20 @@ class fudai_analyse:
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
# 重新读取后,更新保存的详情数据
safe_detail = (
tuple(detail)
if isinstance(detail, (list, tuple)) and len(detail) >= 6
else None
)
if safe_detail:
# 保持存储为 tuple,避免后续可变性导致问题
try:
self._last_fudai_detail_tuple = tuple(safe_detail)
except Exception:
self._last_fudai_detail_tuple = safe_detail
if detail and isinstance(detail, tuple) and len(detail) >= 6:
self._last_fudai_detail_tuple = detail
else:
# 使用第一次保存的详情数据,设置当前福袋的倒计时信息
try:
# 从保存的 tuple 中安全读取倒计时信息,使用 cast 明确类型以帮助静态分析
detail = getattr(self, "_last_fudai_detail_tuple", None)
safe_detail = (
tuple(detail)
if isinstance(detail, (list, tuple)) and len(detail) >= 6
else None
)
if safe_detail:
# 确认 safe_detail 为序列后再索引,避免静态分析误报
try:
countdown_tuple = safe_detail[5]
except Exception:
countdown_tuple = ()
if (
detail is not None
and isinstance(detail, tuple)
and len(detail) >= 6
):
# 使用索引读取以避免静态分析对解包的误报
countdown_tuple = detail[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
@@ -2584,19 +2570,12 @@ class fudai_analyse:
# 在第一次打开时立即进行筛选检查,如果不符合要求则直接跳过
# 注意:这里只检查筛选条件,不执行参与操作
# 为了避免静态分析将 `detail` 视为不可下标对象,先构造一个
# 明确为序列的本地变量 `safe_detail`(类型为 tuple),后续所有索引/解包均使用它。
safe_detail: Optional[Tuple[Any, ...]] = (
tuple(detail)
if isinstance(detail, (list, tuple)) and len(detail) >= 6
else None
)
if safe_detail:
if detail and isinstance(detail, tuple) and len(detail) >= 6:
# 先进行数据验证
is_valid = True
try:
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(
safe_detail, self
detail, self
)
if not is_valid:
try:
@@ -2633,16 +2612,9 @@ class fudai_analyse:
# 提取价值信息
prize_value_yuan = 0.0
countdown_tuple = None
if safe_detail:
# 使用明确的序列类型以帮助静态分析和避免不可下标告警
try:
prize_value_yuan = float(safe_detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
try:
countdown_tuple = safe_detail[5]
except Exception:
countdown_tuple = None
if isinstance(detail, tuple) and len(detail) >= 6:
# 使用解包避免索引告警
_, _, _, _, prize_value_yuan, countdown_tuple = detail
# 检查是否启用高价值预约
high_value_enabled = bool(
@@ -2686,7 +2658,7 @@ class fudai_analyse:
# 获取"预约参与阈值"配置
join_ahead_seconds = int(
getattr(
self, "high_value_fudai_join_ahead_seconds", 120
self, "high_value_fudai_join_ahead_seconds", 300
)
or 120
)
@@ -2827,9 +2799,7 @@ class fudai_analyse:
)
or "adb"
)
if not adb_cmd.startswith(
'"'
) and not adb_cmd.endswith('"'):
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(
@@ -3005,9 +2975,7 @@ class fudai_analyse:
)
or "adb"
)
if not adb_cmd.startswith(
'"'
) and not adb_cmd.endswith('"'):
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
adb_cmd = f'"{adb_cmd}"'
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
subprocess.run(
@@ -3104,17 +3072,9 @@ class fudai_analyse:
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
try:
safe_detail = (
detail
if isinstance(detail, (list, tuple)) and len(detail) >= 5
else None
)
if safe_detail:
content = str(safe_detail[0] or "")
try:
prize_value_yuan = float(safe_detail[4] or 0.0)
except Exception:
prize_value_yuan = 0.0
if isinstance(detail, tuple) and len(detail) >= 5:
content = str(detail[0] or "")
prize_value_yuan = float(detail[4] or 0.0)
if not content and prize_value_yuan == 0.0:
try:
self._log_kv(
@@ -3140,16 +3100,8 @@ class fudai_analyse:
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
try:
safe_detail = (
detail
if isinstance(detail, (list, tuple)) and len(detail) >= 6
else None
)
if safe_detail:
try:
countdown_tuple = safe_detail[5]
except Exception:
countdown_tuple = None
if isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
@@ -3190,20 +3142,9 @@ class fudai_analyse:
countdown_tuple = None
remain_seconds = 0
future_timestamp = 0.0
safe_detail = (
detail
if isinstance(detail, (list, tuple)) and len(detail) >= 6
else None
)
if safe_detail:
try:
countdown_tuple = safe_detail[5]
except Exception:
countdown_tuple = None
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
):
if isinstance(detail, tuple) and len(detail) >= 6:
countdown_tuple = detail[5]
if isinstance(countdown_tuple, tuple) and len(countdown_tuple) >= 2:
# countdown_tuple[0] 是 countdown_start(开始时间戳)
# countdown_tuple[1] 是 countdown_end(结束时间戳/开奖时间戳)
future_timestamp = float(countdown_tuple[1] or 0.0)
@@ -3244,7 +3185,10 @@ class fudai_analyse:
# 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差)
if hasattr(self, "reservations") and self.reservations:
# use module-level `douyin_reservation_logic`
from douyin.reservation import (
douyin_reservation_logic,
) # pylint: disable=redefined-outer-name
reservations_to_remove = []
for idx, r in enumerate(self.reservations):
try:
@@ -3368,7 +3312,9 @@ class fudai_analyse:
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
try:
now_ts = time.time()
import time as time_module
now_ts = time_module.time()
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
queue_full_waiting = bool(
getattr(self, "queue_full_waiting_at_earliest", False) or False
@@ -3383,7 +3329,7 @@ class fudai_analyse:
if ft > 0:
join_ahead = float(
getattr(
self, "high_value_fudai_join_ahead_seconds", 120
self, "high_value_fudai_join_ahead_seconds", 300
)
or 120
)
+32 -20
View File
@@ -1,29 +1,37 @@
{
"updated_ts": 1767493122.2555935,
"reason": "process_reservation",
"room_pos": 0,
"current_room_title": "作I帮数",
"current_room_title_raw": "作I帮数。。",
"updated_ts": 1767493398.0220582,
"reason": "record_reservation",
"room_pos": 3,
"current_room_title": "带娃的小",
"current_room_title_raw": "带娃的小.",
"reservations": [
{
"prize_value_yuan": 6999.0,
"prize_value_yuan": 699.0,
"content": "",
"future_ts": 1767493214.565064,
"future_str": "2026-01-04 10:20:14",
"pos_seen": 0,
"room_title": "彩虹夫妇",
"room_title_raw": "彩虹夫妇",
"created_ts": 1767492808.7325442
"future_ts": 1767493819.527862,
"future_str": "2026-01-04 10:30:19",
"pos_seen": 3,
"room_title": "带娃的小",
"room_title_raw": "带娃的小.",
"created_ts": 1767493297.59925,
"task_count": 2,
"time_text": "08:47",
"participants": 0,
"copies": 0
},
{
"prize_value_yuan": 5999.0,
"prize_value_yuan": 1999.0,
"content": "",
"future_ts": 1767493379.73886,
"future_str": "2026-01-04 10:22:59",
"pos_seen": 3,
"room_title": "刘媛媛媛",
"room_title_raw": "刘媛媛.媛",
"created_ts": 1767492999.3043623
"future_ts": 1767494002.620423,
"future_str": "2026-01-04 10:33:22",
"pos_seen": 0,
"room_title": "作小帮粼",
"room_title_raw": "作小帮粼。。",
"created_ts": 1767493186.2436588,
"task_count": 2,
"time_text": "13:42",
"participants": 0,
"copies": 0
},
{
"prize_value_yuan": 1999.0,
@@ -33,7 +41,11 @@
"pos_seen": 0,
"room_title": "作川帮数",
"room_title_raw": "作川帮数。。",
"created_ts": 1767493120.9476802
"created_ts": 1767493120.9476802,
"task_count": 2,
"time_text": "14:48",
"participants": 0,
"copies": 0
}
]
}
+68
View File
@@ -81,6 +81,17 @@ def attend_choujiang(analyser) -> bool:
attend_button_text and "参与成功" in attend_button_text
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
future_ts=int(future_ts) if future_ts else None,
)
except Exception:
pass
# 记录最后一次成功参与的时间
try:
analyser._last_successful_attend_ts = time.time()
@@ -180,6 +191,19 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="activity_ended",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.5)
@@ -194,11 +218,33 @@ def attend_choujiang(analyser) -> bool:
): # 如果识别到需要看播
analyser.last_attend_fail_reason = "watch_required"
analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="watch_required",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "无法参与" in attend_button_text:
analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与")
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="cannot_participate",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(500, 470)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
@@ -220,6 +266,17 @@ def attend_choujiang(analyser) -> bool:
base_y=2070,
region="(306,2030)-(780,2110)",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
mode="评论",
)
except Exception:
pass
return True
elif attend_button_text and "参与抽奖" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
@@ -234,6 +291,17 @@ def attend_choujiang(analyser) -> bool:
base_y=2070,
region="(306,2030)-(780,2110)",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
run_id=getattr(analyser, "_run_id", ""),
mode="普通",
)
except Exception:
pass
# 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测
# 注意:点击参与按钮后会自动关闭详情页,返回直播间
+3 -12
View File
@@ -12,7 +12,6 @@ try:
log_reservation_error,
format_reservation_context,
)
_RESERVATION_ERROR_UTILS_AVAILABLE = True
except ImportError:
# 如果导入失败,提供占位符函数
@@ -25,9 +24,7 @@ except ImportError:
_RESERVATION_ERROR_UTILS_AVAILABLE = False
def _write_json_atomic(
path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None
) -> None:
def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None) -> None:
"""原子写入 JSON 文件,带详细的错误处理。
参数:
@@ -144,11 +141,7 @@ def write_reservations_state(
except Exception:
ft = 0.0
try:
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft
else ""
)
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else ""
except Exception:
ft_str = ""
items.append(
@@ -225,9 +218,7 @@ def load_high_value_rooms_map(path: str) -> dict[str, dict]:
return {}
def write_high_value_rooms_state(
path: str, rooms_map: dict, *, reason: str = ""
) -> None:
def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "") -> None:
"""寫入高價值直播間映射(跨運行持久化)。"""
try:
rooms: list[dict] = []
-7
View File
@@ -1288,13 +1288,6 @@ class ProcRunner:
cmd.append("--high-value-room-revisit-disabled")
if high_value_room_revisit_only_current_run:
cmd.append("--high-value-room-revisit-only-current-run")
# 可选:通过 GUI 指定回访间隔(秒)
try:
rv_interval = int(_pick("high_value_room_revisit_interval_seconds", 0) or 0)
except Exception:
rv_interval = 0
if rv_interval > 0:
cmd += ["--high-value-room-revisit-interval-seconds", str(rv_interval)]
# 预约回退校验开关(由 Run 面板控制)
reservation_back_verify_enabled = bool(
-14
View File
@@ -199,12 +199,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
action="store_true",
help="仅回访本次运行记录的高价值直播间",
)
p.add_argument(
"--high-value-room-revisit-interval-seconds",
type=int,
default=None,
help="高价值直播间回访间隔(秒),用于覆盖配置中的回访间隔",
)
p.add_argument(
"--reservation-back-verify-enabled",
action="store_true",
@@ -471,14 +465,6 @@ def main(argv: list[str]) -> int:
analyser.high_value_room_revisit_enabled = False
if getattr(args, "high_value_room_revisit_only_current_run", False):
analyser.high_value_room_revisit_only_current_run = True
# 回访间隔覆盖(秒)
if getattr(args, "high_value_room_revisit_interval_seconds", None) is not None:
try:
analyser.high_value_room_revisit_interval_seconds = max(
0, int(args.high_value_room_revisit_interval_seconds)
)
except Exception:
pass
# 预约回退校验开关(命令行优先)
if getattr(args, "reservation_back_verify_enabled", False):
analyser.reservation_back_verify_enabled = True
-5
View File
@@ -268,11 +268,6 @@
<span>仅本次运�?/span>
</label>
</div>
<div class="row">
<label class="label">回访间隔(秒)</label>
<input id="high_value_room_revisit_interval_seconds" class="input" data-key="high_value_room_revisit_interval_seconds" data-type="int" type="number" min="60" max="86400" step="1" />
<div class="hint">两个回访记录之间的最小间隔,单位秒(默认3600)</div>
</div>
<div class="row">
<label class="label">预约回退后校验(回退校验开关)</label>
<label class="check">