import os import sys import time from PIL import Image from datetime import datetime from Underlying_Operations import underlying_operations import json import re import shutil import random import hashlib import difflib """ V3.3.1 版本 """ def normalize_countdown_text(text: str) -> str: if not text: return '' t = re.sub(r"\s+", "", str(text)) t = t.replace(':', ':') # 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字) t = t.translate(str.maketrans({ 'O': '0', 'o': '0', 'Q': '0', 'D': '0', 'I': '1', 'l': '1', '|': '1', '!': '1', 'S': '5', 's': '5', 'B': '8', 'G': '6', 'Z': '2', })) # 中文:x分y秒 / y秒 m = re.search(r"(\d{1,2})分(\d{1,2})秒", t) if m: mm = int(m.group(1)) ss = int(m.group(2)) if ss >= 60: mm += ss // 60 ss = ss % 60 return f"{mm:02d}:{ss:02d}" m = re.search(r"(\d{1,3})秒", t) if m: ss = int(m.group(1)) mm = ss // 60 ss = ss % 60 return f"{mm:02d}:{ss:02d}" # 标准样式:11:37后开奖 / 11:37后开奖 m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t) if m: mm = int(m.group(1)) ss = int(m.group(2)) # 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释 if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: mm, ss = ss, mm return f"{mm:02d}:{ss:02d}后开奖" # 识别错序:54后开奖04 m = re.search(r"(\d{1,2})后开奖(\d{2})", t) if m: mm = int(m.group(1)) ss = int(m.group(2)) if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: mm, ss = ss, mm return f"{mm:02d}:{ss:02d}后开奖" # 纯数字 1137 / 5404 digits = ''.join(ch for ch in t if ch.isdigit()) if len(digits) == 4: a = int(digits[:2]) b = int(digits[2:]) # 生成两种解释:mm:ss 以及交换后的 mm:ss mm1, ss1 = a, b mm2, ss2 = b, a total1 = mm1 * 60 + ss1 total2 = mm2 * 60 + ss2 # 默认相信“从左到右”的顺序:前两位=分,后两位=秒。 # 只有在明显异常(>15分钟)或秒数不合法时才交换。 if ss1 >= 60 and ss2 < 60: mm, ss = mm2, ss2 elif ss2 >= 60 and ss1 < 60: mm, ss = mm1, ss1 elif total1 > 900 and total2 <= 900: mm, ss = mm2, ss2 elif total2 > 900 and total1 <= 900: mm, ss = mm1, ss1 else: mm, ss = mm1, ss1 return f"{mm:02d}:{ss:02d}" # 3 位数字:934 => 09:34 if len(digits) == 3: mm = int(digits[0]) ss = int(digits[1:]) if ss >= 60: # 尝试 15:09(OCR 丢 0) mm2 = int(digits[:2]) ss2 = int(digits[2]) if ss2 < 60: return f"{mm2:02d}:{ss2:02d}" mm += ss // 60 ss = ss % 60 return f"{mm:02d}:{ss:02d}" # 2 位数字:31 => 00:31(更符合临近开奖) if len(digits) == 2: return f"00:{int(digits):02d}" return t def extract_prize_value_yuan(text: str) -> float: if not text: return 0.0 t = re.sub(r"\s+", "", str(text)) # 先去掉倒计时类数字,避免把 00:31 解析成 31 元 t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t) # 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元 currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t) yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t) tagged = currency_matches + yuan_matches if tagged: vals = [] for n in tagged: try: vals.append(float(n)) except ValueError: pass return max(vals) if vals else 0.0 # 去掉常见干扰:份数/参与人数 t = re.sub(r"共\d+份", "", t) t = re.sub(r"\d+人已参与", "", t) # 退化:抓小数 decimals = re.findall(r"\d+\.\d+", t) if decimals: vals = [] for n in decimals: try: vals.append(float(n)) except ValueError: pass return max(vals) if vals else 0.0 # 再退化:抓整数 ints = re.findall(r"\d+", t) if ints: vals = [] for n in ints: try: v = int(n) except ValueError: continue if 1 <= v <= 99999: vals.append(float(v)) return max(vals) if vals else 0.0 return 0.0 class Tee(object): """重写print的函数""" def __init__(self, *files): self.files = files def write(self, obj): for f in self.files: f.write(obj) f.flush() def flush(self): for f in self.files: f.flush() class fudai_analyse: """福袋抽奖相关操作类""" def __init__(self): self.device_id = 'XXXXXXXXX' self.y_pianyi = 0 # 应用于不同型号手机,图标相对屏幕的高度位置有偏差 self.resolution_ratio_x = 1080 self.resolution_ratio_y = 2400 # 预约队列状态文件(用于 Web GUI 展示;子进程写入,Web GUI 进程读取) self._reservations_state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json") # 让终端输出更“整行、实时”(避免看起来空白/零散) try: sys.stdout.reconfigure(encoding='utf-8', line_buffering=True) except Exception: pass try: sys.stderr.reconfigure(encoding='utf-8', line_buffering=True) except Exception: pass # 可通过环境变量关闭 Tee 重定向(例如 Web GUI 统一收集日志时) if not str(os.environ.get("NO_TEE_STDOUT", "")).strip(): # 统一日志文件(默认 logs/unified.log),便于长期追踪与 grep base_dir = os.path.dirname(__file__) cfg = {} try: cfg_path = os.path.join(base_dir, "config.json") if os.path.exists(cfg_path): with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) if f.readable() else {} except Exception: cfg = {} enabled = True try: enabled = bool(cfg.get("log_unified_enabled", True)) except Exception: enabled = True if enabled: rel = str(cfg.get("log_unified_path") or "logs/unified.log") log_path = rel if os.path.isabs(rel) else os.path.join(base_dir, rel) try: os.makedirs(os.path.dirname(log_path), exist_ok=True) except Exception: pass # 使用 utf-8-sig:文件首次创建时写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码 log_file = open(log_path, 'a', encoding='utf-8-sig', errors='ignore') else: # 兼容:若禁用统一日志,则按旧逻辑写一个时间戳文件 timepic = datetime.now().strftime('%Y-%m-%d-%H-%M') log_file = open(timepic + '.log', 'a', encoding='utf-8-sig', errors='ignore') sys.stdout = Tee(sys.stdout, log_file) sys.stderr = Tee(sys.stderr, log_file) # 结构化日志:本次运行唯一 id + 递增序号(便于 Web GUI 里按 rid/seq 定位) try: self._run_id = datetime.now().strftime('%Y%m%d%H%M%S') except Exception: self._run_id = str(int(time.time())) self._log_seq = 0 self.last_find_fudai_time = 0.0 self.last_refresh_zhibo_list_time = 0.0 # 进入直播间计时:用于统计“进入直播间后找到福袋图标耗时” self._enter_live_ts = 0.0 self._enter_live_reason = "" self._enter_live_fudai_logged = False # 无福袋“看门狗”:超时后回到列表重进直播。用户要求先整体关闭,后续再调整。 self.no_fudai_watchdog_enabled = False self.operation = underlying_operations() self.config_path = "config.json" self.contains_not_want = [] self.contains_want = [] self.min_prize_value_yuan = 0.0 # 小于该价值(元)则不参与,0 表示不启用 self.min_participants = 0 # 参与人数小于该值则不参与,0 表示不启用 self.max_participants = 0 # 参与人数大于该值则不参与,0 表示不启用 self.skip_if_countdown_lt_seconds = 15 # 倒计时小于该秒数则不参与(仅 needswitch=True 时生效) # 切换直播间计数:当上划切换达到阈值后,在当前直播间页面下滑回退到第一个直播间 self.reset_after_swipes_enabled = False # 由 Web/CLI 显式开关 self.reset_after_swipes = 10 # 达到阈值次数后回退,需启用开关后生效 # 高价值福袋:预约参与(避免在倒计时很长时一直卡在直播间等待) self.high_value_fudai_enabled = False self.high_value_fudai_threshold_yuan = 1000.0 self.high_value_fudai_join_ahead_seconds = 120 # 开奖前 N 秒回到该直播间并参与 self.high_value_fudai_max_swipe_back = 60 # 为防止回滑过远导致异常,限制最多回退次数 self.high_value_fudai_max_reservations = 5 # 最多记录多少个高价值福袋预约 # 完成某个预约福袋后动作:stay=停留当前直播间;continue=继续执行抢福袋 self.high_value_fudai_after_action = "continue" self.high_value_fudai_after_stay_seconds = 120 # 高价值直播间“回访”:曾经记录过高价值福袋的直播间,每隔一段时间回去看一眼是否出现新福袋。 # 优先级:预约参与(最高) > 回访(中) > 普通找福袋(低) self.high_value_room_revisit_enabled = True self.high_value_room_revisit_interval_seconds = 300 # 默认 5 分钟 self.high_value_room_revisit_watch_window_seconds = 900 # 默认仅在 15 分钟观察窗内回访 self.high_value_room_revisit_skip_if_reservation_within_seconds = 120 # 若离预约参与窗口过近则跳过回访 self.high_value_room_revisit_only_current_run = False # 若为 True,则仅回访本次运行记录的直播间 # 预约回退校验开关:用于在运行时决定是否做回退后详细校验(可通过 Run 面板控制) self.reservation_back_verify_enabled = True # 轮询策略:在预计开奖前多少秒开始积极轮询结果(默认 10 秒) self.poll_before_open_seconds = 10 # 预约抢占最小价值:低于该价值的预约不抢占当前任务(元,默认0表示任何预约可抢占) self.reservation_preempt_min_value_yuan = 0.0 # 详情页识别兜底(参与按钮 OCR)节流 self.detail_ocr_check_min_interval_seconds = 8.0 # 福袋详情识别异常(时间/价值)时:关闭重开后延迟再截图的秒数 self.fudai_abnormal_reopen_delay_seconds = 1.2 # 定时禁抢:凌晨时段不抢福袋,仅持续养号 self.fudai_quiet_hours_enabled = True self.fudai_quiet_start_hour = 2 self.fudai_quiet_end_hour = 7 # 运行中动态加载配置(网页端保存 config.json 后可生效) self._last_config_reload_ts = 0.0 # 按需求:只保留“推荐页养号流程”(纯坐标点击),不再提供“推荐/直播/进入直播间”文本识别流程。 # 养号总开关:关闭时不执行推荐页养号(只原地等待) self.yanghao_enabled = True # 推荐页养号:可配置的“时长/间隔(冷却)” self.yanghao_recommend_duration_seconds = 60 self.yanghao_recommend_interval_seconds = 0 # 0=不限制(每次触发都可执行) self._yanghao_last_recommend_ts = 0.0 def _log_kv(self, tag: str, msg: str = "", **fields): """统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。""" try: self._log_seq += 1 except Exception: self._log_seq = 1 key_map = { # 通用 "rid": "运行", "seq": "序号", "msg": "说明", "biaoqian": "标签", "bq": "标签", "stage": "阶段", "seen": "识别", "next": "下一步", "ok": "成功", "text": "文本", "action": "动作", "result": "结果", "mode": "模式", "reason": "原因", "wait_seconds": "等待秒", "wait_s": "等待秒", "remain_to_join_window_s": "距参与窗口秒", "remain_wait_s": "剩余等待秒", # 预约 "value_yuan": "价值元", "future": "开奖时间", "pos_seen": "发现位置", "qsize": "队列数量", "max_try": "最大尝试次数", "cap": "队列上限", "dropped": "丢弃数量", "dropped_value_yuan": "丢弃价值元", "dropped_future": "丢弃开奖时间", "back_times": "需回退次数", "room_pos": "当前位置", "target_future": "【目标】开奖时间", "target_value_yuan": "【目标】价值元", "target_content": "【目标】内容", "queue_brief": "【队列】摘要", "attempt": "尝试次数", "room_title": "直播间名(清洗后)", "room_title_raw": "直播间名原文", "room_title_expected": "【预期】直播间名", "room_title_current": "【当前】直播间名", "room_title_ratio": "直播间名相似度", "room_title_raw_expected": "【预期】直播间名原文", "room_title_raw_current": "【当前】直播间名原文", # 预约回退校验:匹配调试字段(来自 _match_reservation debug_dict) "expected_future": "【期望】开奖时间戳", "actual_future": "【识别】开奖时间戳", "future_diff_s": "开奖时间差秒", "expected_value": "【期望】价值元", "actual_value": "【识别】价值元", "expected_content": "【期望】内容", "actual_content": "【识别】内容", } flat = [] flat.append("{}={}".format(key_map.get("rid", "运行"), getattr(self, "_run_id", "-"))) flat.append("{}={}".format(key_map.get("seq", "序号"), getattr(self, "_log_seq", 0))) if msg: m = str(msg).replace("\r", " ").replace("\n", " ").strip() if len(m) > 240: m = m[:240] + "..." flat.append("{}={}".format(key_map.get("msg", "说明"), m)) for k, v in (fields or {}).items(): if v is None: continue s = str(v) if s == "": continue s = s.replace("\r", " ").replace("\n", " ").strip() if len(s) > 240: s = s[:240] + "..." ck = key_map.get(str(k), None) if not ck: # 兜底:避免英文 key 出现在日志里 ck = "字段_{}".format(str(k)) flat.append("{}={}".format(ck, s)) # 日志自动换行:每行最多120字符,超过则换行缩进继续输出 log_line = "[{}] {}".format(tag, " ".join(flat)) if len(log_line) <= 120: print(log_line) else: # 将字段分段输出 header = "[{}] ".format(tag) indent = " " * len(header) parts = [] current_line = header + "{}={} {}={}".format( key_map.get("rid", "运行"), getattr(self, "_run_id", "-"), key_map.get("seq", "序号"), getattr(self, "_log_seq", 0) ) if msg: m = str(msg).replace("\r", " ").replace("\n", " ").strip() if len(m) > 240: m = m[:240] + "..." current_line += " {}={}".format(key_map.get("msg", "说明"), m) parts.append(current_line) for k, v in (fields or {}).items(): if v is None: continue s = str(v) if s == "": continue s = s.replace("\r", " ").replace("\n", " ").strip() if len(s) > 240: s = s[:240] + "..." ck = key_map.get(str(k), None) if not ck: ck = "字段_{}".format(str(k)) field_str = "{}={}".format(ck, s) # 检查是否需要换行 if len(parts[-1]) + len(field_str) + 1 > 120: parts.append(indent + field_str) else: parts[-1] += " " + field_str print("\n".join(parts)) # 纯坐标点击所需的内部默认坐标(1080x2400 基准,会自动按分辨率缩放) self.yanghao_fallback_close_x = 1030 self.yanghao_fallback_close_y = 120 self.yanghao_fallback_live_x = 900 self.yanghao_fallback_live_y = 2280 self.yanghao_fallback_enter_live_x = 540 self.yanghao_fallback_enter_live_y = 1250 # 新养号动作:停留期间可按概率点爱心/收藏,停留结束后自动滑动到下一个 self.yanghao_enable_actions = True self.yanghao_like_prob = 0.15 self.yanghao_fav_prob = 0.05 self.yanghao_after_dwell_swipe_direction = "up" # up=下一个内容, down=上一个内容 self.yanghao_after_dwell_swipe_distance_px = 900 self.yanghao_like_keywords = ["赞", "喜欢", "Like"] self.yanghao_fav_keywords = ["收藏", "加入收藏", "取消收藏", "Favorite"] # 爱心/收藏图标检测(更适合图标,避免文案/层级变化影响) # 坐标以 1080x2400 为基准,会按当前分辨率缩放。 self.yanghao_like_icon_x = 0 self.yanghao_like_icon_y = 0 self.yanghao_fav_icon_x = 0 self.yanghao_fav_icon_y = 0 # 仅用于“截图检测ROI”的偏移(不影响点击坐标)。用于微调截图中心。 self.yanghao_like_roi_offset_x = 0 self.yanghao_like_roi_offset_y = 0 self.yanghao_fav_roi_offset_x = 0 self.yanghao_fav_roi_offset_y = 0 self.yanghao_icon_roi_size = 180 # 截取检测区域边长(px) self.yanghao_icon_match_threshold = 0.72 self.yanghao_like_template_path = os.path.join(os.path.dirname(__file__), "assets", "like.png") self.yanghao_fav_template_path = os.path.join(os.path.dirname(__file__), "assets", "fav.png") # 桌面图标模板(用于检测是否回到桌面) self.desktop_icon_template_path = os.path.join(os.path.dirname(__file__), "assets", "desktop.png") self.desktop_icon_x = 153 self.desktop_icon_y = 260 self.desktop_icon_roi_size = 200 self.desktop_icon_match_threshold = 0.6 # 养号逐步截图(调试用,开启后会比较慢/占空间) self.yanghao_step_screenshot = False # “评论/发弹幕”动作:仅在同时检测到爱心+收藏时,按概率触发 self.yanghao_comment_prob = 0.0 self.yanghao_comment_btn_x = 981 self.yanghao_comment_btn_y = 1399 self.yanghao_comment_input_x = 250 self.yanghao_comment_input_y = 2218 self.yanghao_comment_send_x = 906 self.yanghao_comment_send_y = 1298 self.yanghao_comment_close_x = 586 self.yanghao_comment_close_y = 385 self.yanghao_comment_texts = [] self.auto_join_fansclub = False # 是否自动尝试加入粉丝团(可能触发付费/钻石消耗) self.fansclub_fail_action = "stay" # 粉丝团门槛无法处理时:stay=停留当前直播间,switch=切换下一个 self.last_attend_fail_reason = "" # 最近一次参与失败原因 # 福袋图标检测提速参数(默认更快;可在 config.json 覆盖) self.fudai_icon_retry_delay_seconds = 0.6 self.fudai_icon_max_wait_seconds = 4.0 # 最多尝试寻找福袋图标次数(默认 5,可由 UI 修改) self.fudai_find_max_attempts = 5 # 截图阶段诊断(OCR)节流:避免高频截图时反复 OCR 拖慢 self.screenshot_diagnose_min_interval_seconds = 8.0 self._last_diag_ts = 0.0 self._last_diag_stage = "-" self._last_diag_seen = "-" # 福袋详情异常重试预算:避免 OCR 异常时单次卡太久 self.fudai_detail_retry_budget_seconds = 10.0 self.load_config() def load_config(self): """从配置文件中加载数据""" if os.path.exists(self.config_path): with open(self.config_path, "r", encoding="utf-8") as file: config = json.load(file) self.contains_not_want = config.get("contains_not_want", []) self.contains_want = config.get("contains_want", []) try: self.min_prize_value_yuan = float(config.get("min_prize_value_yuan", 0) or 0) except (TypeError, ValueError): self.min_prize_value_yuan = 0.0 try: self.min_participants = int(config.get("min_participants", 0) or 0) except (TypeError, ValueError): self.min_participants = 0 try: self.max_participants = int(config.get("max_participants", 0) or 0) except (TypeError, ValueError): self.max_participants = 0 try: self.skip_if_countdown_lt_seconds = int(config.get("skip_if_countdown_lt_seconds", 15) or 15) except (TypeError, ValueError): self.skip_if_countdown_lt_seconds = 15 # 无福袋看门狗(30分钟无福袋回列表重进):默认关闭 try: self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", False)) except Exception: self.no_fudai_watchdog_enabled = False # 福袋图标检测提速参数 try: self.fudai_icon_retry_delay_seconds = float(config.get("fudai_icon_retry_delay_seconds", self.fudai_icon_retry_delay_seconds) or self.fudai_icon_retry_delay_seconds) except (TypeError, ValueError): pass if self.fudai_icon_retry_delay_seconds < 0.2: self.fudai_icon_retry_delay_seconds = 0.2 if self.fudai_icon_retry_delay_seconds > 5: self.fudai_icon_retry_delay_seconds = 5.0 try: self.fudai_icon_max_wait_seconds = float(config.get("fudai_icon_max_wait_seconds", self.fudai_icon_max_wait_seconds) or self.fudai_icon_max_wait_seconds) except (TypeError, ValueError): pass if self.fudai_icon_max_wait_seconds < 0: self.fudai_icon_max_wait_seconds = 0.0 if self.fudai_icon_max_wait_seconds > 30: self.fudai_icon_max_wait_seconds = 30.0 try: self.fudai_find_max_attempts = int(config.get("fudai_find_max_attempts", self.fudai_find_max_attempts) or self.fudai_find_max_attempts) except (TypeError, ValueError): pass if self.fudai_find_max_attempts < 1: self.fudai_find_max_attempts = 1 if self.fudai_find_max_attempts > 50: self.fudai_find_max_attempts = 50 # 截图阶段诊断(OCR)节流 try: self.screenshot_diagnose_min_interval_seconds = float( config.get("screenshot_diagnose_min_interval_seconds", self.screenshot_diagnose_min_interval_seconds) or self.screenshot_diagnose_min_interval_seconds ) except (TypeError, ValueError): pass if self.screenshot_diagnose_min_interval_seconds < 0: self.screenshot_diagnose_min_interval_seconds = 0.0 if self.screenshot_diagnose_min_interval_seconds > 60: self.screenshot_diagnose_min_interval_seconds = 60.0 try: self.reset_after_swipes_enabled = bool(config.get("reset_after_swipes_enabled", False)) except Exception: self.reset_after_swipes_enabled = False try: raw_reset_swipes = config.get("reset_after_swipes", 10) self.reset_after_swipes = int(10 if raw_reset_swipes is None else raw_reset_swipes) except (TypeError, ValueError): self.reset_after_swipes = 10 # 兼容旧配置:若未声明开关但阈值大于0,则自动视为开启 if not config.get("reset_after_swipes_enabled", None) and self.reset_after_swipes > 0: self.reset_after_swipes_enabled = True if self.reset_after_swipes < 1: self.reset_after_swipes = 1 # 高价值福袋预约 try: self.high_value_fudai_enabled = bool(config.get("high_value_fudai_enabled", False)) except Exception: self.high_value_fudai_enabled = False try: self.high_value_fudai_threshold_yuan = float(config.get("high_value_fudai_threshold_yuan", 1000.0) or 1000.0) except (TypeError, ValueError): self.high_value_fudai_threshold_yuan = 1000.0 try: self.high_value_fudai_join_ahead_seconds = int(config.get("high_value_fudai_join_ahead_seconds", 120) or 120) except (TypeError, ValueError): self.high_value_fudai_join_ahead_seconds = 120 try: self.high_value_fudai_max_swipe_back = int(config.get("high_value_fudai_max_swipe_back", 60) or 60) except (TypeError, ValueError): self.high_value_fudai_max_swipe_back = 60 try: self.high_value_fudai_max_reservations = int(config.get("high_value_fudai_max_reservations", 5) or 5) except (TypeError, ValueError): self.high_value_fudai_max_reservations = 5 if self.high_value_fudai_max_reservations < 1: self.high_value_fudai_max_reservations = 1 if self.high_value_fudai_max_reservations > 50: self.high_value_fudai_max_reservations = 50 try: self.high_value_fudai_after_action = str(config.get("high_value_fudai_after_action", "continue") or "continue").strip().lower() except Exception: self.high_value_fudai_after_action = "continue" if self.high_value_fudai_after_action not in ("stay", "continue"): self.high_value_fudai_after_action = "continue" try: self.high_value_fudai_after_stay_seconds = int(config.get("high_value_fudai_after_stay_seconds", 120) or 120) except (TypeError, ValueError): self.high_value_fudai_after_stay_seconds = 120 if self.high_value_fudai_after_stay_seconds < 0: self.high_value_fudai_after_stay_seconds = 0 if self.high_value_fudai_after_stay_seconds > 3600: self.high_value_fudai_after_stay_seconds = 3600 # 高价值直播间回访 try: self.high_value_room_revisit_enabled = bool(config.get("high_value_room_revisit_enabled", self.high_value_room_revisit_enabled)) except Exception: pass try: self.reservation_back_verify_enabled = bool(config.get("reservation_back_verify_enabled", True)) except Exception: self.reservation_back_verify_enabled = True try: self.reservation_preempt_min_value_yuan = float(config.get("reservation_preempt_min_value_yuan", self.reservation_preempt_min_value_yuan) or self.reservation_preempt_min_value_yuan) except (TypeError, ValueError): pass if self.reservation_preempt_min_value_yuan < 0: self.reservation_preempt_min_value_yuan = 0.0 try: self.poll_before_open_seconds = int(config.get("poll_before_open_seconds", self.poll_before_open_seconds) or self.poll_before_open_seconds) except (TypeError, ValueError): pass if self.poll_before_open_seconds < 0: self.poll_before_open_seconds = 0 try: self.high_value_room_revisit_interval_seconds = float( config.get("high_value_room_revisit_interval_seconds", self.high_value_room_revisit_interval_seconds) or self.high_value_room_revisit_interval_seconds ) except (TypeError, ValueError): pass if self.high_value_room_revisit_interval_seconds < 60: self.high_value_room_revisit_interval_seconds = 60.0 if self.high_value_room_revisit_interval_seconds > 1800: self.high_value_room_revisit_interval_seconds = 1800.0 try: self.high_value_room_revisit_watch_window_seconds = float( config.get("high_value_room_revisit_watch_window_seconds", self.high_value_room_revisit_watch_window_seconds) or self.high_value_room_revisit_watch_window_seconds ) except (TypeError, ValueError): pass if self.high_value_room_revisit_watch_window_seconds < 60: self.high_value_room_revisit_watch_window_seconds = 60.0 if self.high_value_room_revisit_watch_window_seconds > 7200: self.high_value_room_revisit_watch_window_seconds = 7200.0 try: self.high_value_room_revisit_skip_if_reservation_within_seconds = int( config.get( "high_value_room_revisit_skip_if_reservation_within_seconds", self.high_value_room_revisit_skip_if_reservation_within_seconds, ) or self.high_value_room_revisit_skip_if_reservation_within_seconds ) except (TypeError, ValueError): pass if self.high_value_room_revisit_skip_if_reservation_within_seconds < 0: self.high_value_room_revisit_skip_if_reservation_within_seconds = 0 if self.high_value_room_revisit_skip_if_reservation_within_seconds > 1800: self.high_value_room_revisit_skip_if_reservation_within_seconds = 1800 # 详情页 OCR 兜底节流 try: self.detail_ocr_check_min_interval_seconds = float( config.get("detail_ocr_check_min_interval_seconds", self.detail_ocr_check_min_interval_seconds) or self.detail_ocr_check_min_interval_seconds ) except (TypeError, ValueError): pass if self.detail_ocr_check_min_interval_seconds < 0: self.detail_ocr_check_min_interval_seconds = 0.0 if self.detail_ocr_check_min_interval_seconds > 60: self.detail_ocr_check_min_interval_seconds = 60.0 # 福袋详情异常(时间/价值)重开延迟 try: self.fudai_abnormal_reopen_delay_seconds = float( config.get("fudai_abnormal_reopen_delay_seconds", 1.2) or 1.2 ) except (TypeError, ValueError): self.fudai_abnormal_reopen_delay_seconds = 1.2 if self.fudai_abnormal_reopen_delay_seconds < 0: self.fudai_abnormal_reopen_delay_seconds = 0.0 if self.fudai_abnormal_reopen_delay_seconds > 10: self.fudai_abnormal_reopen_delay_seconds = 10.0 # 福袋详情异常重试预算 try: self.fudai_detail_retry_budget_seconds = float( config.get("fudai_detail_retry_budget_seconds", self.fudai_detail_retry_budget_seconds) or self.fudai_detail_retry_budget_seconds ) except (TypeError, ValueError): pass if self.fudai_detail_retry_budget_seconds < 0: self.fudai_detail_retry_budget_seconds = 0.0 if self.fudai_detail_retry_budget_seconds > 60: self.fudai_detail_retry_budget_seconds = 60.0 # 定时禁抢(默认 2:00-7:00) try: self.fudai_quiet_hours_enabled = bool(config.get("fudai_quiet_hours_enabled", True)) except Exception: self.fudai_quiet_hours_enabled = True try: self.fudai_quiet_start_hour = int(config.get("fudai_quiet_start_hour", 2) or 2) except (TypeError, ValueError): self.fudai_quiet_start_hour = 2 try: self.fudai_quiet_end_hour = int(config.get("fudai_quiet_end_hour", 7) or 7) except (TypeError, ValueError): self.fudai_quiet_end_hour = 7 # 只保留推荐页养号:忽略旧字段与流程开关 try: self.yanghao_enabled = bool(config.get("yanghao_enabled", True)) except Exception: self.yanghao_enabled = True try: self.yanghao_recommend_duration_seconds = int(config.get("yanghao_recommend_duration_seconds", 60) or 60) except (TypeError, ValueError): self.yanghao_recommend_duration_seconds = 60 try: self.yanghao_recommend_interval_seconds = int(config.get("yanghao_recommend_interval_seconds", 0) or 0) except (TypeError, ValueError): self.yanghao_recommend_interval_seconds = 0 # 注意:不再从 config 读取“推荐/直播/进入直播间文本”与“兜底坐标”;统一使用代码内默认坐标。 self.yanghao_enable_actions = bool(config.get("yanghao_enable_actions", True)) try: self.yanghao_like_prob = float(config.get("yanghao_like_prob", 0.15) or 0.15) except (TypeError, ValueError): self.yanghao_like_prob = 0.15 try: self.yanghao_fav_prob = float(config.get("yanghao_fav_prob", 0.05) or 0.05) except (TypeError, ValueError): self.yanghao_fav_prob = 0.05 self.yanghao_after_dwell_swipe_direction = str( config.get("yanghao_after_dwell_swipe_direction", "up") or "up" ).strip().lower() try: self.yanghao_after_dwell_swipe_distance_px = int( config.get("yanghao_after_dwell_swipe_distance_px", 900) or 900 ) except (TypeError, ValueError): self.yanghao_after_dwell_swipe_distance_px = 900 lk = config.get("yanghao_like_keywords", ["赞", "喜欢", "Like"]) or ["赞", "喜欢", "Like"] fk = config.get("yanghao_fav_keywords", ["收藏", "加入收藏", "取消收藏", "Favorite"]) or ["收藏", "加入收藏", "取消收藏", "Favorite"] if isinstance(lk, list): self.yanghao_like_keywords = [str(x) for x in lk if str(x).strip()] if isinstance(fk, list): self.yanghao_fav_keywords = [str(x) for x in fk if str(x).strip()] # 图标检测配置(可选) try: self.yanghao_like_icon_x = int(config.get("yanghao_like_icon_x", 0) or 0) except (TypeError, ValueError): self.yanghao_like_icon_x = 0 try: self.yanghao_like_icon_y = int(config.get("yanghao_like_icon_y", 0) or 0) except (TypeError, ValueError): self.yanghao_like_icon_y = 0 try: self.yanghao_fav_icon_x = int(config.get("yanghao_fav_icon_x", 0) or 0) except (TypeError, ValueError): self.yanghao_fav_icon_x = 0 try: self.yanghao_fav_icon_y = int(config.get("yanghao_fav_icon_y", 0) or 0) except (TypeError, ValueError): self.yanghao_fav_icon_y = 0 # ROI 偏移(可选) for k, attr in ( ("yanghao_like_roi_offset_x", "yanghao_like_roi_offset_x"), ("yanghao_like_roi_offset_y", "yanghao_like_roi_offset_y"), ("yanghao_fav_roi_offset_x", "yanghao_fav_roi_offset_x"), ("yanghao_fav_roi_offset_y", "yanghao_fav_roi_offset_y"), ): try: setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) except (TypeError, ValueError): pass try: self.yanghao_icon_roi_size = int(config.get("yanghao_icon_roi_size", 180) or 180) except (TypeError, ValueError): self.yanghao_icon_roi_size = 180 try: self.yanghao_icon_match_threshold = float(config.get("yanghao_icon_match_threshold", 0.72) or 0.72) except (TypeError, ValueError): self.yanghao_icon_match_threshold = 0.72 tp_like = str(config.get("yanghao_like_template_path", self.yanghao_like_template_path) or self.yanghao_like_template_path) tp_fav = str(config.get("yanghao_fav_template_path", self.yanghao_fav_template_path) or self.yanghao_fav_template_path) base_dir = os.path.dirname(__file__) if tp_like and (not os.path.isabs(tp_like)): tp_like = os.path.normpath(os.path.join(base_dir, tp_like)) if tp_fav and (not os.path.isabs(tp_fav)): tp_fav = os.path.normpath(os.path.join(base_dir, tp_fav)) self.yanghao_like_template_path = tp_like self.yanghao_fav_template_path = tp_fav # 逐步截图开关(可选) try: self.yanghao_step_screenshot = bool(config.get("yanghao_step_screenshot", False)) except Exception: self.yanghao_step_screenshot = False # 评论动作配置 try: self.yanghao_comment_prob = float(config.get("yanghao_comment_prob", 0.0) or 0.0) except (TypeError, ValueError): self.yanghao_comment_prob = 0.0 for k, attr in ( ("yanghao_comment_btn_x", "yanghao_comment_btn_x"), ("yanghao_comment_btn_y", "yanghao_comment_btn_y"), ("yanghao_comment_input_x", "yanghao_comment_input_x"), ("yanghao_comment_input_y", "yanghao_comment_input_y"), ("yanghao_comment_send_x", "yanghao_comment_send_x"), ("yanghao_comment_send_y", "yanghao_comment_send_y"), ("yanghao_comment_close_x", "yanghao_comment_close_x"), ("yanghao_comment_close_y", "yanghao_comment_close_y"), ): try: setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) except (TypeError, ValueError): pass ct = config.get("yanghao_comment_texts", []) or [] if isinstance(ct, list): self.yanghao_comment_texts = [str(x).strip() for x in ct if str(x).strip()] self.auto_join_fansclub = bool(config.get("auto_join_fansclub", False)) self.fansclub_fail_action = str(config.get("fansclub_fail_action", "stay") or "stay").lower() def _maybe_reload_config(self, min_interval_seconds: float = 2.0) -> None: """运行中定期从 config.json 重新加载配置,便于网页端随时修改。""" try: now = time.time() if (now - float(self._last_config_reload_ts or 0.0)) < float(min_interval_seconds or 0.0): return self._last_config_reload_ts = now self.load_config() except Exception: pass def _mark_enter_live(self, reason: str = "") -> None: """标记一次“已进入直播间”,用于统计后续找到福袋图标的耗时。""" try: self._enter_live_ts = float(time.time()) except Exception: self._enter_live_ts = 0.0 try: self._enter_live_reason = str(reason or "") except Exception: self._enter_live_reason = "" self._enter_live_fudai_logged = False def _in_quiet_hours(self, hour: int) -> bool: """判断当前小时是否处于禁抢时段(支持跨天区间)。""" try: h = int(hour) except Exception: return False try: start = int(self.fudai_quiet_start_hour) end = int(self.fudai_quiet_end_hour) except Exception: start, end = 2, 7 # 归一化 start = start % 24 end = end % 24 if start == end: return False if start < end: return start <= h < end # 跨天:例如 22-7 return (h >= start) or (h < end) def _save_step_screenshot(self, label: str) -> str | None: """保存当前屏幕截图为独立文件,便于你逐步核对是否点对了位置。""" try: base_dir = os.path.join(os.path.dirname(__file__), "pic") os.makedirs(base_dir, exist_ok=True) ok = self._shot_and_diagnose("养号截图", "保存逐步截图({})".format(label), self.device_id) if not ok: return None src = os.path.join(base_dir, "screenshot.png") if not os.path.exists(src): return None safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fa5_-]+", "_", str(label or "step")) label_dir = os.path.join(base_dir, safe) os.makedirs(label_dir, exist_ok=True) # 同时保存一份带时间戳的历史截图 + 覆盖 latest.png ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f") dst_hist = os.path.join(label_dir, f"{ts}.png") dst_latest = os.path.join(label_dir, "latest.png") shutil.copyfile(src, dst_hist) shutil.copyfile(src, dst_latest) print(f"[养号] 截图已保存:{dst_hist} (latest已更新)") return dst_hist except Exception as e: print(f"[养号] 截图保存失败:{e}") return None def _scale_from_base(self, x: int, y: int, base_w: int = 1080, base_h: int = 2400) -> tuple[int, int]: try: sx = int(int(x) * int(self.resolution_ratio_x) / int(base_w)) sy = int(int(y) * int(self.resolution_ratio_y) / int(base_h)) except Exception: sx, sy = int(x), int(y) return sx, sy def _capture_roi_screenshot(self, label: str, center_x: int, center_y: int, size_px: int) -> str | None: """截屏并裁剪指定坐标附近 ROI,保存到 pic/