""" 本地完整版 douyin_fudai(模块化调度器) ====================================== 目标: - 不再依赖外部 axf 目录; - 保持 `from douyin_fudai import fudai_analyse` 导入方式不变; - 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。 """ from __future__ import annotations from typing import Any, List, Tuple, Optional import os import time import logging from Underlying_Operations import underlying_operations from douyin.stage import douyin_stage from douyin.detection import douyin_detection from douyin.fudai import douyin_fudai_detail from douyin.fudai import douyin_fudai_core from douyin.core import douyin_flow_control # pylint: disable=redefined-outer-name from douyin.other import douyin_live_room from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name from douyin.utils import douyin_config from douyin.logging import douyin_logging_wrapper from douyin.handlers import douyin_screenshot_handler from douyin.utils import douyin_helpers from douyin.handlers import douyin_popup_handler from douyin.handlers import douyin_swipe_handler from douyin.reservation import douyin_reservation_handler from douyin.stage import douyin_stage_handler class fudai_analyse: """福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。""" # 类常量:魔法数字提取 MAX_BACK_CLICKS_TO_RECOMMEND = 10 # 返回推荐页面的最大返回键点击次数 BACK_KEY_CLICK_DELAY = 1.0 # 返回键点击后的延迟(秒) PAGE_STABLE_DELAY = 2.0 # 页面稳定等待时间(秒) FOLLOW_TAB_CLICK_DELAY = 2.0 # 点击关注标签后的延迟(秒) ENTER_LIVE_CLICK_DELAY = 0.6 # 点击进入直播间的延迟(秒) ENTER_LIVE_FINAL_DELAY = 2.0 # 进入直播间后的最终等待时间(秒) def __init__(self) -> None: # 设备与分辨率 self.device_id: str = "" # 设备ID,需要在运行时设置 self.y_pianyi: int = 0 self.resolution_ratio_x: int = 1080 self.resolution_ratio_y: int = 2400 # 滑动次数计数器(用于滑动次数重置功能) self._swipe_times: int = 0 # 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部) self.operation = underlying_operations() self.config_path = "config/config.json" # 日志相关字段:完全独立的日志系统(不依赖原始代码) try: from datetime import datetime 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._log_kv_orig = None # 使用增强版本(通过日志包装器) self._log_kv = lambda *args, **kwargs: douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv( self, *args, **kwargs ) # 用于跟踪上一个日志标签,以便检测阶段变化并添加分隔符 self._last_log_tag = None # 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告 self._std_logger = None # type: ignore[assignment] # 初始化统一日志系统和traceId # 确保日志系统已配置(在实例化之前) try: from douyin.logging import douyin_logging # 检查 _logging_configured 标志是否存在 if not getattr(douyin_logging, "_logging_configured", False): douyin_logging.configure_logging() except Exception: pass try: from unified_logger import MDC, get_unified_logger # 为当前实例设置traceId MDC.set_trace_id(f"run_{self._run_id}") self._std_logger = get_unified_logger("douyin.fudai") except ImportError: # 如果unified_logger不可用,使用标准logging self._std_logger = logging.getLogger("douyin.fudai") # 确保根 logger 有 handlers root_logger = logging.getLogger() if not root_logger.handlers: try: from douyin.logging import douyin_logging douyin_logging.configure_logging() except Exception: pass self._forced_reservation_detail = None self._forced_reservation_fudai_x = None # 进入直播间后诊断与阶段流转所需的一些状态 self._last_diag_stage: str = "INIT" self._last_diag_seen: str = "-" self._last_diag_ts: float = 0.0 # 30分钟超时相关:记录最后一次成功参与福袋的时间 self._last_successful_attend_ts: float = 0.0 self._no_attend_timeout_minutes: float = ( 30.0 # 30分钟没有参与成功则返回推荐页面(可通过config.json配置) ) self._run_start_ts: float = ( time.time() ) # 记录运行开始时间,用于从未成功参与时的超时检查 self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标(用于优化搜索) # 与配置相关的核心字段(只初始化最关键的几项,其余保持默认) self.contains_not_want: list[str] = [] self.contains_want: list[str] = [] self.min_prize_value_yuan: float = 0.0 self.min_participants: int = 0 self.max_participants: int = 0 self.skip_if_countdown_gt_seconds: int = 900 self.skip_if_countdown_lt_seconds: int = 0 # 倒计时小于该秒数则不参与 self.no_fudai_watchdog_enabled: bool = False # 福袋图标检测节流相关默认值 # 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整 # 注意:已改为使用时间限制(fudai_icon_max_wait_seconds),不再使用尝试次数限制 self.fudai_icon_retry_delay_seconds: float = 0.6 self.fudai_icon_max_wait_seconds: float = 5.0 # 点击福袋图标后等待详情页加载的时间(秒) self.fudai_click_wait_seconds: float = 1.0 # 切换直播间后等待阶段诊断的时间(秒) self.switch_room_wait_after_stage_diag_seconds: float = 7.0 # 滑动速度(毫秒),影响滑动持续时间,值越大滑动越慢 self.swipe_duration_ms: int = 600 # fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用 self.fudai_find_max_attempts: int = 10 # 优化查找器相关配置 self.fudai_finder_optimized_enabled: bool = True # 默认启用优化查找器 self.fudai_click_verify_enabled: bool = True # 点击后验证是否成功打开详情页 self.fudai_find_max_retries: int = 3 # 最大重试次数 self.screenshot_diagnose_min_interval_seconds: float = 8.0 # 开奖页面检测红色占比阈值(0.0~1.0) self.lucky_draw_red_ratio_threshold: float = 0.9 # 优惠券模板匹配阈值(0.0~1.0,默认0.75) self.coupon_template_match_threshold: float = 0.75 # 参与按钮红色占比阈值(0.0~1.0,默认0.25) self.attend_button_red_ratio_threshold: float = 0.25 # 粉丝团加入红色占比阈值(0.0~1.0,默认0.25) self.fansclub_join_red_ratio_threshold: float = 0.25 # 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8) self.live_room_match_threshold: float = 0.8 # 福袋模板匹配开关(默认关闭) self.fudai_template_match_enabled: bool = False # 福袋模板匹配阈值(0.0~1.0,默认0.7) self.fudai_template_match_threshold: float = 0.7 # —— 高价值福袋 / 预约相关配置(从原 fudai1 精简迁移) —— # 是否启用“高价值福袋预约参与” self.high_value_fudai_enabled: bool = False # 高价值阈值(元) self.high_value_fudai_threshold_yuan: float = 500.0 # 提前参与秒数:开奖前 N 秒回到该直播间并参与 self.high_value_fudai_join_ahead_seconds: int = 120 # 从当前位置最多回滑多少次以回到预约直播间 self.high_value_fudai_max_swipe_back: int = 35 # 同时记录的最大预约数量 self.high_value_fudai_max_reservations: int = 3 # 完成某个预约福袋后的动作:stay=停留当前直播间;continue=继续执行抢福袋 self.high_value_fudai_after_action: str = "continue" self.high_value_fudai_after_stay_seconds: int = 120 # 高价值直播间"回访"相关(当前仅保留配置,不在本地版强制启用复杂逻辑) self.high_value_room_revisit_enabled: bool = False self.high_value_room_revisit_only_current_run: bool = False # 粉丝团相关配置 self.auto_join_fansclub: bool = False # 是否自动加入粉丝团 self.fansclub_fail_action: str = ( "stay" # 粉丝团失败策略:stay=停留,switch=切换 ) # 预约回退相关 self.reservation_back_verify_enabled: bool = True # 默认启用回退校验 # 未做回退校验时的快速回滑延迟(秒) self.reservation_back_swipe_delay: float = 0.6 # 预约抢占最小价值:低于该价值的预约不会抢占当前任务(元) self.reservation_preempt_min_value_yuan: float = 0.0 # 在预计开奖前多少秒开始积极轮询结果 self.poll_before_open_seconds: int = 10 # 滑动次数重置相关 self.reset_after_swipes_enabled: bool = False # 由 Web/CLI 显式开关 self.reset_after_swipes: int = 10 # 达到阈值次数后回退,需启用开关后生效 # 意外返回桌面自救相关 self.desktop_icon_x: int = 153 # 桌面图标 X 坐标(默认值) self.desktop_icon_y: int = 260 # 桌面图标 Y 坐标(默认值) self.yanghao_fallback_live_x: int = 540 # 养号备用直播按钮 X 坐标 self.yanghao_fallback_live_y: int = 2000 # 养号备用直播按钮 Y 坐标 self.yanghao_fallback_enter_live_x: int = 540 # 养号备用进入直播间 X 坐标 self.yanghao_fallback_enter_live_y: int = 1200 # 养号备用进入直播间 Y 坐标 # —— 预约运行时状态(单次运行内有效) —— # 高价值福袋预约队列 self.reservations: list[dict[str, Any]] = [] # 标记是否是第一次运行 run_once_basic(用于刷新预约队列) self._first_run_once_basic: bool = True # 当前"直播间位置"计数:上划 +1,下滑 -1(仅在本次连续切换过程中有效) self.room_pos: int = 0 # 回退到预约直播间后,在该时间戳前不允许上划离开 self.reservation_focus_until_ts: float = 0.0 # 当前是否还有"完成某个预约后的后续动作"待执行 self.reservation_after_action_pending: bool = False # 达到"无福袋切换阈值"后,是否在处理完预约后回到列表第一个直播间 self.reset_to_list_after_reservations: bool = False # 队列满时是否已回退到最早开奖的预约直播间等待 self.queue_full_waiting_at_earliest: bool = False # 预约队列状态文件(供 WebGUI / 其他进程查看) self._reservations_state_path: str = os.path.join( os.path.dirname(__file__), "state", "reservations.json" ) # 运行时直播间标题和位置映射表(用于回退校验) # 格式:{room_pos: (room_title, room_title_raw)} self._room_pos_to_title_map: dict[int, tuple[str, str]] = {} # 运行时状态标志(避免在外部定义属性的警告) self.needswitch: bool | None = ( None # 是否允许切换直播间,将从配置文件加载,默认 True ) self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果 self._reservation_back_direct_attend: bool = False # 预约回退后直接参与标志 self._force_attend_after_reservation_back: bool = False # 强制参与标志 self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志 self._just_switched_room: bool = False # 是否刚刚切换了直播间 self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = ( None # 上次读取的福袋详情 ) self._current_fudai_future_ts: float = 0.0 # 当前福袋的开奖时间戳 self._fudai_detail_first_read: bool = False # 是否第一次读取福袋详情 self._fudai_detail_consecutive_failures: int = 0 # 连续失败次数 self._detail_closed_by_attend: bool = False # 详情页是否由参与操作关闭 self._lottery_result_expected_ts: float = 0.0 # 开奖结果预期时间戳 # 初次加载配置 self.load_config() # ===== 兼容原始脚本的一些简单封装方法 ===== def _find_room_pos_by_title( self, target_title: str, target_title_raw: str = "" ) -> int | None: """根据直播间标题在运行时映射表中查找对应的位置。 返回: 如果找到匹配的位置,返回位置值;否则返回 None """ return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title( self, target_title, target_title_raw ) def _record_room_title_and_pos(self) -> None: """记录当前直播间的标题和位置到运行时映射表。 用于预约回退校验时验证位置信息。 """ douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self) def click(self, x: int, y: int) -> None: """兼容原版 fudai_analyse.click:转发到底层 operation.click。""" douyin_helpers.HelperFunctions.click(self, x, y) def load_config(self) -> None: """从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。""" douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined] # ========== 兼容旧入口:主循环 ========== def fudai_choujiang( self, device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15, ) -> None: """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" # DEBUG: 记录函数入口 try: self._log_kv( "DEBUG", "entered fudai_choujiang", device_id=device_id, wait_minutes=wait_minutes, ) except Exception: print( f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}" ) self.device_id = device_id or self.device_id self.y_pianyi = int(y_pianyi or 0) # 保存是否允许切换直播间的配置,供后续所有逻辑统一使用 try: self.needswitch = bool(needswitch) except Exception: # 兜底:若赋值失败,则保持原有行为(默认允许切换) self.needswitch = True # 尝试获取设备分辨率;若设备未连接则重试数次再回退到默认分辨率 resolved = False if self.device_id: for attempt in range(5): try: rx, ry = self.operation.get_device_resolution(self.device_id) self.resolution_ratio_x = int(rx or 1080) self.resolution_ratio_y = int(ry or 2400) resolved = True break except Exception as e: try: self._log_kv( "截图", "获取分辨率失败,重试中", attempt=attempt + 1, error=str(e), ) except Exception: print( f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}" ) time.sleep(1.0) if not resolved: # 回退到默认分辨率 try: self._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400) except Exception: pass self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400 # 记录运行开始 from datetime import datetime start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] try: actions_log_path = os.path.join( os.path.dirname(__file__), "logs", "actions.log" ) log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( actions_log_path, "a", encoding="utf-8-sig", errors="replace" ) as f: f.write("=" * 80 + "\n") f.write(f"{start_time} - [GUI] - [运行] 程序开始运行\n") f.flush() except Exception: pass # 捕获并记录未被捕获的异常以便排查立即退出问题 try: # 原有后续逻辑继续... pass except Exception as top_exc: try: self._log_kv( "ERROR", "fudai_choujiang top-level exception", error=str(top_exc) ) except Exception: import traceback traceback.print_exc() raise # 暂时禁用流式截图,使用直接截图模式 self._log_kv("截图服务", "暂时禁用流式截图,使用直接截图模式") self._log_kv( "启动", "fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)", 分辨率=f"{self.resolution_ratio_x}x{self.resolution_ratio_y}", needswitch=int(bool(self.needswitch)), wait_minutes=int(wait_minutes), ) # 基础循环:在限定时间内反复执行单轮逻辑 # 如果 wait_minutes <= 0,则无限循环运行 if wait_minutes and wait_minutes > 0: end_ts = time.time() + int(wait_minutes) * 60 while time.time() < end_ts: try: self.run_once_basic() except Exception as exc: # 捕获异常,记录日志,但继续循环 try: self._log_kv( "循环", "run_once_basic 异常", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass # 异常后稍作延迟再继续 try: self.operation.delay(2.0) except Exception: time.sleep(2.0) continue # 为避免过于频繁截图,增加少量间隔 try: self.operation.delay(1.0) except Exception: time.sleep(1.0) # 记录运行结束(定时模式) try: end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] actions_log_path = os.path.join( os.path.dirname(__file__), "logs", "actions.log" ) log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( actions_log_path, "a", encoding="utf-8-sig", errors="replace" ) as f: f.write("=" * 80 + "\n") f.write(f"{end_time} - [GUI] - [运行] 程序运行结束(时间到)\n") f.flush() except Exception: pass else: # 无限循环模式(wait_minutes <= 0) self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)") while True: try: self.run_once_basic() except KeyboardInterrupt: # 允许 Ctrl+C 退出 self._log_kv("循环", "收到中断信号,退出循环") # 记录运行结束 try: end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] actions_log_path = os.path.join( os.path.dirname(__file__), "logs", "actions.log" ) log_dir = os.path.dirname(actions_log_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( actions_log_path, "a", encoding="utf-8-sig", errors="replace", ) as f: f.write("=" * 80 + "\n") f.write( f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n" ) f.flush() except Exception: pass raise except Exception as exc: # 捕获异常,记录日志,但继续循环 try: self._log_kv( "循环", "run_once_basic 异常", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass # 异常后稍作延迟再继续 try: self.operation.delay(2.0) except Exception: time.sleep(2.0) continue # 为避免过于频繁截图,增加少量间隔 try: self.operation.delay(1.0) except Exception: time.sleep(1.0) # ========== 阶段诊断 ========== def _diagnose_stage_from_current_screen( self, force_screenshot: bool = False ) -> Tuple[str, str]: """封装到子模块的阶段诊断入口。 参数: force_screenshot: 是否强制重新截图(默认False,优先使用缓存) """ return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen( self ) # ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ========== def cut_pic( self, x_top: int = 1, y_top: int = 1, x_bottom: int = 2, y_bottom: int = 2, target: str = "", cut_pic_name: str = "", y_pianyi: int = 0, ) -> None: """裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。""" douyin_screenshot_handler.ScreenshotHandler.cut_pic( self, x_top, y_top, x_bottom, y_bottom, target, cut_pic_name, y_pianyi ) def _read_pixel_stage_state( self, return_details: bool = False ) -> dict | tuple[dict, dict]: """读取像素阶段状态(用于阶段诊断)。 参数: return_details: 是否返回每个检测步骤的详细信息(包括分数) 返回: dict: 检测结果(return_details=False时) tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时) """ return douyin_helpers.HelperFunctions.read_pixel_stage_state( self, return_details ) def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]: """将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。 返回 (scaled_x, scaled_y) """ return douyin_screenshot_handler.ScreenshotHandler.scale_from_base( self, base_x, base_y ) def _save_step_screenshot(self, label: str) -> None: """保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。""" douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label) def _check_in_live_room_by_icon( self, ) -> Tuple[bool, float]: # pyright: ignore[reportAttributeAccessIssue] """通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。 返回: (detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。 """ return douyin_stage_handler.StageHandler.check_in_live_room_by_icon(self) def check_in_fudai_detail(self) -> bool: """判断当前是否处于福袋详情页:委托给 douyin_detection.check_in_fudai_detail。""" try: return bool(douyin_detection.check_in_fudai_detail(self)) except Exception as exc: try: self._log_kv("检测", "check_in_fudai_detail 异常", error=str(exc)) except Exception: pass return False def _enhanced_log_kv(self, *args, **fields): """增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging""" douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(self, *args, **fields) # 供像素/检测模块记录子步骤耗时使用 def _log_step_time( self, step_name: str, start_time: float, extra_info: dict | None = None ) -> None: """记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。""" douyin_logging_wrapper.LoggingWrapper.log_step_time( self, step_name, start_time, extra_info ) # ========== 弹窗 / 人机校验 ========== def _check_coupon_popup(self) -> bool: """购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。""" return douyin_popup_handler.PopupHandler.check_coupon_popup(self) def _check_shopping_redpacket_popup(self) -> bool: """购物红包中央弹窗。""" return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self) # ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ========== def run_once_basic(self) -> None: # type: ignore[complexity] """单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。 注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。 """ from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name start_time = time.time() # 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果 if getattr(self, "_waiting_for_lottery_result", False): try: # 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖) should_preempt = False try: if getattr(self, "high_value_fudai_enabled", False) and getattr( self, "reservations", None ): reservations = self.reservations if reservations and len(reservations) > 0: # 检查是否有预约需要立即处理 reservation_focus_until_ts_ref = [0.0] reservation_after_action_pending_ref = [False] room_pos_ref = [getattr(self, "room_pos", 0) or 0] # 检查是否有预约需要抢占 preempted = douyin_reservation_logic.process_reservation_attend_window( self, reservations, room_pos_ref[0], reservation_focus_until_ts_ref, reservation_after_action_pending_ref, float( getattr(self, "reservation_back_swipe_delay_s", 0.5) or 0.5 ), lambda: self.swipe_down_back_from_live(), lambda item: self._seek_reservation_room(item), lambda: ( douyin_reservation_logic._sort_reservations_inplace( self.reservations ) if self.reservations else None ), lambda: None, # write_state_callback ) if preempted: # 有高价值预约需要处理,清除等待开奖标志,中断等待 self._waiting_for_lottery_result = False should_preempt = True self._log_kv( "参与", "等待开奖期间检测到高价值预约需要处理,中断等待", ) except Exception as exc: self._log_kv("参与", "检查高价值预约时出错", error=str(exc)) if should_preempt: # 被高价值预约抢占,继续执行后续逻辑处理预约 pass else: # 没有预约抢占,继续等待开奖 # 直接用预计开奖时间减去当前时间计算剩余秒数,加上6秒延迟修正 future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0 current_ts = time.time() remain_seconds = max( 0, future_ts - current_ts + 6.0 ) # 加上6秒延迟,修正倒计时误差 # 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒) check_start_ts = future_ts + 1.0 # 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭) timeout_ts = future_ts + 10.0 if current_ts >= timeout_ts: # 超过超时时间,清除等待标志,避免卡死 self._waiting_for_lottery_result = False timeout_seconds = int(current_ts - future_ts) self._log_kv( "参与", f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作", 超时秒数=timeout_seconds, ) # 继续执行后续逻辑,不返回 elif current_ts >= check_start_ts: # 已经超过开奖时间+缓冲时间,直接点击"我知道了"按钮(多次点击,确保关闭弹窗) # 计算已过开奖时间的秒数 passed_seconds = int(current_ts - future_ts) self._log_kv( "参与", f"等待开奖结果中,OCR未识别到结果(已过开奖时间{passed_seconds}秒),开始直接点击", 已过开奖时间秒数=passed_seconds, ) # 按钮位置基于1080x2400:532, 1322 rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400) btn_x = int(532 * rx // 1080) btn_y = int(1322 * ry // 2400) # 直接点击已被禁用 —— 改为仅使用 OCR 模式识别与处理结果 self._log_kv( "参与", "直接点击已禁用,改为OCR识别处理开奖结果", ) try: self.operation.get_screenshot(self.device_id) except Exception: pass result = self._check_lottery_result_by_ocr() if result: self._waiting_for_lottery_result = False self._log_kv("参与", "等待期间检测到开奖结果,开始处理") self._handle_lottery_result_by_ocr(result) elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2), ) return # 未识别到则清除等待标志并继续(不执行点击) self._waiting_for_lottery_result = False self._log_kv( "参与", "等待开奖期间:未识别到开奖结果(点击已禁用),清除等待标志", ) # 切换下一个直播间 try: needswitch = bool(getattr(self, "needswitch", True)) except Exception: needswitch = True if needswitch: self._log_kv( "开奖结果", "处理完开奖结果,切换直播间找新福袋" ) self.swipe_up_to_next_live() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2), ) return else: # 还未到开奖时间,短暂等待后继续检测 wait_s = min(2.0, remain_seconds) remain_seconds_int = int(remain_seconds) # 在日志消息中显示倒计时 self._log_kv( "参与", f"等待开奖中,剩余{remain_seconds_int}秒", 剩余秒数=remain_seconds_int, ) self.operation.delay(wait_s) elapsed = time.time() - start_time self._log_kv( "流程", f"run_once_basic完成(等待开奖中,剩余{remain_seconds_int}秒)", elapsed_seconds=round(elapsed, 2), ) return # 返回,不执行其他操作 except Exception as exc: self._log_kv("参与", "等待开奖检测时出错", error=str(exc)) # 出错时清除等待标志,避免卡死 self._waiting_for_lottery_result = False # 0. 检查30分钟超时:如果30分钟没有成功参与福袋,则返回推荐页面并重新进入直播间 try: last_attend_ts = float( getattr(self, "_last_successful_attend_ts", 0.0) or 0.0 ) timeout_minutes = float( getattr(self, "_no_attend_timeout_minutes", 30.0) or 30.0 ) current_ts = time.time() run_start_ts = float( getattr(self, "_run_start_ts", current_ts) or current_ts ) # 如果从未成功参与过,且运行时间超过30分钟,则触发超时 # 如果成功参与过,检查距离最后一次成功参与是否超过30分钟 if last_attend_ts > 0: elapsed_minutes = (current_ts - last_attend_ts) / 60.0 if elapsed_minutes >= timeout_minutes: try: self._log_kv( "超时", "30分钟未参与成功福袋,返回推荐页面重新进入直播间", last_attend_minutes_ago=round(elapsed_minutes, 1), ) except Exception: pass # 返回推荐页面并重新进入直播间 self._return_to_recommend_and_reenter_live() # 重置最后成功参与时间,避免立即再次触发 try: self._last_successful_attend_ts = current_ts except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2), ) return else: # 从未成功参与过,检查运行时间 elapsed_minutes = (current_ts - run_start_ts) / 60.0 if elapsed_minutes >= timeout_minutes: try: self._log_kv( "超时", f"运行{round(elapsed_minutes, 1)}分钟仍未参与成功福袋,返回推荐页面重新进入直播间", run_minutes=round(elapsed_minutes, 1), ) except Exception: pass # 返回推荐页面并重新进入直播间 self._return_to_recommend_and_reenter_live() # 重置运行开始时间(在成功重新进入直播间后重置,避免立即再次触发) # 注意:重置逻辑已移至 _return_to_recommend_and_reenter_live() 方法中 elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2), ) return except Exception as exc: try: self._log_kv("超时", "检查30分钟超时时出错", error=str(exc)) except Exception: pass # 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间" try: # 每次开始运行时丢弃旧的预约队列,不加载状态文件 try: # 如果是第一次运行,清空预约队列,不加载状态文件 is_first_run = getattr(self, "_first_run_once_basic", True) # 记录清空前的队列状态(用于调试) old_reservations_count = 0 try: old_reservations_count = ( len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0 ) except Exception: pass if is_first_run: try: 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 ) # 同时清空状态文件,确保外部查看时也是空的 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._first_run_once_basic = False except Exception: pass else: # 如果不是第一次运行,也记录日志(用于调试) try: current_count = ( len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0 ) self._log_kv( "预约", "[预约] 非第一次运行,保持当前预约队列", reservations_count=current_count, is_first_run=False, ) except Exception: pass # 不再从状态文件加载预约数据,每次启动时都从空队列开始 # 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空 except Exception as exc: try: self._log_kv( "预约", "[预约] 初始化预约队列时出错", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass high_value_enabled = getattr(self, "high_value_fudai_enabled", False) reservations_list = getattr(self, "reservations", None) reservations_count = len(reservations_list) if reservations_list else 0 # 添加详细的调试日志,确认预约回退逻辑的触发条件 try: # 输出预约队列的详细信息 reservations_detail = [] if reservations_list: for idx, r in enumerate(reservations_list[:3]): # 只显示前3个 try: ft = float(r.get("future_ts") or 0) from datetime import datetime ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" ) reservations_detail.append( { "index": idx, "future_ts": int(ft) if ft > 0 else 0, "future_str": ft_str, "value": float(r.get("prize_value_yuan", 0)), "pos_seen": int(r.get("pos_seen", 0)), } ) except Exception: pass self._log_kv( "预约", "[预约] run_once_basic:检查预约回退触发条件", high_value_enabled=high_value_enabled, reservations_count=reservations_count, reservations_is_none=(reservations_list is None), will_check_reservations=bool( high_value_enabled and reservations_list ), reservations_detail=reservations_detail, ) except Exception: pass # 如果预约功能未启用,输出日志 if not high_value_enabled: try: self._log_kv( "预约", "[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查", ) except Exception: pass # 如果预约队列为空,输出日志 elif not reservations_list or reservations_count == 0: try: self._log_kv( "预约", "[预约] 预约队列为空,跳过预约回退检查", reservations_is_none=(reservations_list is None), reservations_count=reservations_count, ) except Exception: pass if high_value_enabled and reservations_list: def _swipe_down_once() -> None: self.swipe_down_back_from_live() def _sort_reservations() -> None: douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] def _write_state() -> None: # 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致) try: import json os.makedirs( os.path.dirname(self._reservations_state_path), exist_ok=True, ) # 格式化预约队列数据(与 douyin_reservation.py 格式一致) items = [] for r in self.reservations or []: try: ft = float(r.get("future_ts") or 0) except Exception: ft = 0.0 try: ft_str = ( datetime.fromtimestamp(ft).strftime( "%Y-%m-%d %H:%M:%S" ) if ft else "" ) except Exception: ft_str = str(r.get("future_str", "")) items.append( { "prize_value_yuan": float( r.get("prize_value_yuan") or 0 ), "content": str(r.get("content") or ""), "future_ts": ft, "future_str": ft_str, "pos_seen": int(r.get("pos_seen") or 0), "room_title": str(r.get("room_title", "") or ""), "room_title_raw": str( r.get("room_title_raw", "") or "" ), "created_ts": float(r.get("created_ts") or 0), } ) # 获取当前直播间标题(用于状态文件) current_title = str( getattr(self, "current_room_title", "") or "" ) current_title_raw = str( getattr(self, "current_room_title_raw", "") or "" ) # 写入完整的状态数据 data = { "updated_ts": time.time(), "reason": "process_reservation", "room_pos": int(getattr(self, "room_pos", 0) or 0), "current_room_title": current_title, "current_room_title_raw": current_title_raw, "reservations": items, } with open( self._reservations_state_path, "w", encoding="utf-8" ) as f: json.dump(data, f, ensure_ascii=False, indent=2) except Exception as exc: try: self._log_kv( "预约", "写入预约队列状态文件失败", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass focus_ref = [float(self.reservation_focus_until_ts or 0.0)] after_action_ref = [ bool(self.reservation_after_action_pending or False) ] def _seek_reservation_room(item: dict) -> bool: try: return bool(self._seek_reservation_room(item)) except Exception: return False # 检查队列是否已满且需要等待 max_reservations = int( getattr(self, "high_value_fudai_max_reservations", 3) or 3 ) if ( len(self.reservations) >= max_reservations and not self.queue_full_waiting_at_earliest ): # 队列已满,回退到最早开奖的预约直播间等待 waiting = ( douyin_reservation_logic.handle_queue_full_wait_at_earliest( analyser=self, reservations=self.reservations, room_pos=int(getattr(self, "room_pos", 0) or 0), reservation_focus_until_ts_ref=focus_ref, reservation_back_swipe_delay_s=float( self.reservation_back_swipe_delay or 0.6 ), swipe_down_back_callback=_swipe_down_once, seek_reservation_room_callback=_seek_reservation_room, sort_reservations_callback=_sort_reservations, write_state_callback=_write_state, ) ) if waiting: self.queue_full_waiting_at_earliest = True if focus_ref: self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) # 已回退到最早开奖的预约直播间,本轮结束 # 注意:_reservation_back_direct_attend 标志已在 handle_queue_full_wait_at_earliest 中设置 elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(预约队列满等待)", elapsed_seconds=round(elapsed, 2), ) return # 如果正在等待开奖,跳过预约回退检查 if getattr(self, "_waiting_for_lottery_result", False): try: self._log_kv( "预约", "[预约] 正在等待开奖,跳过预约回退检查", waiting_for_lottery=True, ) except Exception: pass # 跳过预约回退检查,让流程继续执行到阶段诊断后检查开奖结果 # 不在这里 return,让流程继续 # 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查 elif self.queue_full_waiting_at_earliest: reservation_direct_attend = getattr( self, "_reservation_back_direct_attend", False ) if reservation_direct_attend: try: self._log_kv( "预约", "[预约] 队列满等待状态,已设置直接参与标志,立即执行参与(不再循环检查)", reservation_direct_attend=reservation_direct_attend, ) except Exception: pass # 立即执行参与,不再循环检查预约回退 # 先进行阶段诊断,然后根据阶段执行参与 try: self.operation.get_screenshot(self.device_id) except Exception: pass from douyin.stage import ( douyin_stage, ) # pylint: disable=redefined-outer-name result = douyin_stage.diagnose_stage_from_current_screen(self) if result is None: stage, _ = ( "IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间", ) else: stage, _ = result if stage == "FUDai_DETAIL": # 在福袋详情页,直接参与 try: self._log_kv( "预约", "[预约] 检测到福袋详情页,立即执行直接参与", stage=stage, ) except Exception: pass self._reservation_back_direct_attend = False # 清除标志 self._force_attend_after_reservation_back = ( True # 设置强制参与标志 ) self._handle_reservation_direct_attend() elif stage == "IN_LIVE_ROOM": # 在直播间,查找福袋并打开详情页 try: self._log_kv( "预约", "[预约] 检测到直播间,查找福袋并打开详情页后执行直接参与", stage=stage, ) except Exception: pass # 查找福袋并打开详情页 from douyin.core import ( douyin_flow_control, ) # pylint: disable=redefined-outer-name room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] original_max_wait = getattr( self, "fudai_icon_max_wait_seconds", None ) try: wait_seconds_for_find = float( getattr( self, "switch_room_wait_after_stage_diag_seconds", 7.0, ) or 7.0 ) self.fudai_icon_max_wait_seconds = wait_seconds_for_find self._log_kv( "预约", "[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)", room_pos=room_pos_ref[0], max_wait_seconds=wait_seconds_for_find, ) except Exception: pass found = douyin_flow_control.find_and_open_fudai_detail( self, room_pos_ref ) # 恢复原始配置 try: if original_max_wait is not None: self.fudai_icon_max_wait_seconds = original_max_wait elif hasattr(self, "fudai_icon_max_wait_seconds"): delattr(self, "fudai_icon_max_wait_seconds") except Exception: pass if found: # 成功打开详情页,直接参与 try: self._log_kv( "预约", "[预约] 成功打开详情页,立即执行直接参与", ) except Exception: pass self._reservation_back_direct_attend = False # 清除标志 self._force_attend_after_reservation_back = ( True # 设置强制参与标志 ) self._handle_reservation_direct_attend() else: # 查找福袋失败,保留标志,下一轮继续尝试 try: self._reservation_back_direct_attend = ( True # 恢复标志 ) self._log_kv( "预约", "[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试", flag_restored=True, ) except Exception: pass else: # 其他阶段,保留标志,下一轮继续尝试 try: self._reservation_back_direct_attend = True # 恢复标志 self._log_kv( "预约", "[预约] 检测到其他阶段,保留直接参与标志,下一轮继续尝试", stage=stage, flag_restored=True, ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(预约回退直接参与)", elapsed_seconds=round(elapsed, 2), ) return # 检查是否所有预约已完成,需要重置到第一个直播间 if self.queue_full_waiting_at_earliest and not self.reservations: try: self._log_kv( "预约", "[预约] 所有预约已完成,重置到第一个直播间", ) except Exception: pass self.queue_full_waiting_at_earliest = False self.reservation_focus_until_ts = 0.0 # 回退到第一个直播间:需要回退 room_pos 次 try: current_pos = int(getattr(self, "room_pos", 0) or 0) back_times = abs(current_pos) # 防止无限循环:最大回退次数限制为100 if back_times > 100: back_times = 100 if back_times > 0: for i in range(back_times): _swipe_down_once() self.operation.delay(0.6) self.room_pos = 0 if hasattr(self, "_swipe_times"): self._swipe_times = 0 try: self._log_kv( "预约", "[预约] 已回退到第一个直播间", back_times=back_times, ) except Exception: pass except Exception: pass return # 单间模式(needswitch=False)下不启用预约回退逻辑 # 因为单间模式不会切换直播间,不需要回退,预约会在当前直播间自动识别和参与 try: needswitch_cfg = bool(getattr(self, "needswitch", True)) except Exception: needswitch_cfg = True # 添加详细的调试日志,确认 needswitch 的值和预约信息 try: # 输出第一个预约的详细信息 first_reservation_info = {} if self.reservations and len(self.reservations) > 0: first_r = self.reservations[0] try: ft = float(first_r.get("future_ts") or 0) from datetime import datetime import time as time_module now_ts = time_module.time() ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" ) remain_seconds = int(ft - now_ts) if ft > 0 else 0 first_reservation_info = { "future_ts": int(ft) if ft > 0 else 0, "future_str": ft_str, "value": float(first_r.get("prize_value_yuan", 0)), "pos_seen": int(first_r.get("pos_seen", 0)), "remain_seconds": remain_seconds, "current_room_pos": int( getattr(self, "room_pos", 0) or 0 ), } except Exception: pass self._log_kv( "预约", "[预约] run_once_basic:检查预约回退条件", needswitch_cfg=needswitch_cfg, reservations_count=( len(self.reservations) if self.reservations else 0 ), first_reservation=first_reservation_info, ) except Exception: pass if needswitch_cfg: # 多间模式:需要回退到预约直播间 try: self._log_kv( "预约", "[预约] 多间模式:开始调用 process_reservation_attend_window", reservations_count=( len(self.reservations) if self.reservations else 0 ), room_pos=int(getattr(self, "room_pos", 0) or 0), ) except Exception: pass preempted = ( douyin_reservation_logic.process_reservation_attend_window( analyser=self, reservations=self.reservations, room_pos=int(getattr(self, "room_pos", 0) or 0), reservation_focus_until_ts_ref=focus_ref, reservation_after_action_pending_ref=after_action_ref, reservation_back_swipe_delay_s=float( self.reservation_back_swipe_delay or 0.6 ), swipe_down_back_callback=_swipe_down_once, seek_reservation_room_callback=_seek_reservation_room, sort_reservations_callback=_sort_reservations, write_state_callback=_write_state, ) ) try: self._log_kv( "预约", "[预约] process_reservation_attend_window 返回结果", preempted=preempted, focus_until=( int(focus_ref[0]) if focus_ref and focus_ref[0] > 0 else 0 ), ) except Exception: pass # 同步回写 ref 值 if focus_ref: self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) if after_action_ref: self.reservation_after_action_pending = bool( after_action_ref[0] ) if preempted: # 已触发预约回退,设置标志:下一轮直接参与,跳过详情识别 try: self._reservation_back_direct_attend = True self._log_kv( "预约", "[预约] 预约回退成功,设置直接参与标志(跳过详情识别)", flag_set=True, next_round_will_check="下一轮将检查此标志并直接参与", ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(预约回退)", elapsed_seconds=round(elapsed, 2), ) return else: # 单间模式:不需要回退,预约会在当前直播间自动识别和参与 # 只需要清理过期的预约 try: self._log_kv( "预约", "[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与", reservations_count=( len(self.reservations) if self.reservations else 0 ), ) except Exception: pass try: from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name 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 # 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后) skip_stage_diagnosis = getattr( self, "_skip_stage_diagnosis_and_find_fudai", False ) if skip_stage_diagnosis: try: self._skip_stage_diagnosis_and_find_fudai = False # 清除标志 self._log_kv("流程", "点击参与抽奖后,跳过阶段检测,直接查找福袋") except Exception: pass # 直接查找福袋,跳过阶段检测 self._handle_live_room_has_or_not_fudai() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(跳过阶段检测)", elapsed_seconds=round(elapsed, 2), ) return # 1. 截图 + 阶段诊断 screenshot_start = time.time() max_screenshot_retries = 3 ok = False for retry in range(max_screenshot_retries): ok = self.operation.get_screenshot(self.device_id, use_service=False) if ok: break if retry < max_screenshot_retries - 1: self._log_kv( "截图", f"截图失败,重试中 ({retry + 1}/{max_screenshot_retries})", retry=retry + 1, max_retries=max_screenshot_retries, ) try: self.operation.delay(1.0) # 等待1秒后重试 except Exception: time.sleep(1.0) screenshot_elapsed = time.time() - screenshot_start if not ok: elapsed = time.time() - start_time self._log_kv( "截图", "获取截图失败(多次重试后仍失败)", ok=0, retries=max_screenshot_retries, elapsed_seconds=round(elapsed, 2), screenshot_elapsed_seconds=round(screenshot_elapsed, 2), suggestion="检查设备连接状态和ADB服务", ) return stage, seen = self._diagnose_stage_from_current_screen() self._last_diag_stage = stage self._last_diag_seen = seen self._last_diag_ts = time.time() # 简洁输出阶段诊断结果(不额外添加分隔符,避免日志噪音) elapsed = time.time() - start_time self._log_kv( "截图", "截图+阶段诊断", stage=stage, seen=seen, elapsed_seconds=round(elapsed, 2), screenshot_elapsed_seconds=round(screenshot_elapsed, 2), ) # 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复 try: top_pkg = "" try: top_pkg = self.operation.get_top_package(self.device_id) or "" self._log_kv("自救", "桌面检测:获取前台包名", top_pkg=top_pkg) except Exception as exc: top_pkg = "" self._log_kv("自救", "桌面检测:获取前台包名失败", error=str(exc)) # 如果获取到包名且不是抖音相关包,说明可能在桌面或其他应用 is_douyin_pkg = top_pkg and ( "aweme" in top_pkg or "douyin" in top_pkg or "com.ss.android.ugc" in top_pkg ) if top_pkg and not is_douyin_pkg: self._log_kv( "自救", "桌面检测:检测到不在抖音前台", top_pkg=top_pkg, is_douyin=False, ) try: self._log_kv( "自救", "发现前台包不在抖音,尝试恢复进入直播间", top_pkg=top_pkg, ) # 直接点击桌面图标的预设坐标 try: self.click(int(self.desktop_icon_x), int(self.desktop_icon_y)) except Exception: # 退化为默认硬编码位置 self.click(153, 260) self.operation.delay(2) # 点击直播与进入直播间的备用坐标 try: lx = int(self.yanghao_fallback_live_x) ly = int(self.yanghao_fallback_live_y) self._log_kv("自救", "点击直播按钮", x=lx, y=ly) self.click(lx, ly) self.operation.delay(1.5) except Exception: pass try: ex = int(self.yanghao_fallback_enter_live_x) ey = int(self.yanghao_fallback_enter_live_y) self._log_kv("自救", "点击进入直播间", x=ex, y=ey, 次数=2) self.click(ex, ey) self.operation.delay(0.6) self.click(ex, ey) self.operation.delay(2.0) except Exception: pass # 自救完成后,不在这里结束本轮流程,而是立即重新执行一次主流程: # 重新截图 + 阶段诊断 + 查找福袋,使流程与正常进入直播间路径保持一致 try: self._log_kv( "流程", "run_once_basic:自救完成,立即重新执行一次主流程", ) except Exception: pass # 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次; # 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。 try: self.operation.delay(0.5) except Exception: time.sleep(0.5) self.run_once_basic() return except Exception as e: try: self._log_kv( "自救", "恢复失败", error=str(e), error_type=type(e).__name__, ) except Exception: pass except Exception as exc: # 桌面检测本身出错,记录日志 try: self._log_kv( "自救", "桌面检测异常", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass # 2. 诊断后分支(弹窗检测已合并到阶段诊断中) # 处理弹窗阶段 if stage == "COUPON_POPUP": # 优惠券弹窗:按返回键关闭 self._log_kv("弹窗处理", "检测到优惠券弹窗,按返回键关闭") try: self.operation.click_back(self.device_id) self.operation.delay(0.5) self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗") except Exception as e: self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e)) elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理优惠券弹窗)", elapsed_seconds=round(elapsed, 2), ) return elif stage == "SHOPPING_REDPACKET_POPUP": # 购物红包弹窗:点击关闭按钮 self._log_kv("弹窗处理", "检测到购物红包弹窗,点击关闭按钮") try: close_x = int(530 * self.resolution_ratio_x // 1080) close_y = int(1647 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, close_x, close_y) self.operation.delay(0.5) self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y) except Exception as e: self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e)) elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理购物红包弹窗)", elapsed_seconds=round(elapsed, 2), ) return elif stage == "FANSCLUB_JOIN": # 粉丝团加入阶段:先点击参与按钮,再点击两次预设位置,最后关闭详情页 self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理") try: # 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070)) attend_x = int(543 * self.resolution_ratio_x // 1080) attend_y = int(2070 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, attend_x, attend_y) self._log_kv( "粉丝团处理", "先点击参与按钮", x=attend_x, y=attend_y, base_x=543, base_y=2070, region="(306,2030)-(780,2110)", ) self.operation.delay(0.5) # 等待参与按钮响应 # 第二步:点击两次预设位置(527, 567) preset_x = int(527 * self.resolution_ratio_x // 1080) preset_y = int(567 * self.resolution_ratio_y // 2400) # 第一次点击预设位置 self.operation.click(self.device_id, preset_x, preset_y) self._log_kv( "粉丝团处理", "第一次点击预设位置", x=preset_x, y=preset_y, base_x=527, base_y=567, ) self.operation.delay(0.5) # 短暂等待后立即第二次点击 # 第二次点击预设位置 self.operation.click(self.device_id, preset_x, preset_y) self._log_kv( "粉丝团处理", "第二次点击预设位置", x=preset_x, y=preset_y, base_x=527, base_y=567, ) self.operation.delay(1.0) # 等待点击完成 # 第三步:关闭详情页(点击详情页旁边位置) close_x = int(500 * self.resolution_ratio_x // 1080) close_y = int(470 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, close_x, close_y) self._log_kv( "粉丝团处理", "关闭详情页", x=close_x, y=close_y, base_x=500, base_y=470, ) self.operation.delay(1.0) # 等待关闭完成 except Exception as exc: self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc)) # 如果启用了自动加入,等待页面加载后再次点击(如果需要) if getattr(self, "auto_join_fansclub", False): self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载") self.operation.delay(1.0) # 再次诊断阶段,看是否还在粉丝团加入页 try: stage_after, _ = self._diagnose_stage_from_current_screen() if stage_after == "FANSCLUB_JOIN": # 仍在粉丝团加入页,再次点击(连续点击两次) # 使用预设位置坐标(527, 567) preset_x = int(527 * self.resolution_ratio_x // 1080) preset_y = int(567 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, preset_x, preset_y) self._log_kv( "粉丝团处理", "仍在粉丝团加入页,再次第一次点击", x=preset_x, y=preset_y, base_x=527, base_y=567, ) self.operation.delay(0.5) self.operation.click(self.device_id, preset_x, preset_y) self._log_kv( "粉丝团处理", "仍在粉丝团加入页,再次第二次点击", x=preset_x, y=preset_y, base_x=527, base_y=567, ) self.operation.delay(2.0) # 加入粉丝团成功后,点击 (527, 567) 返回直播间 try: return_x = int(527 * self.resolution_ratio_x // 1080) return_y = int(567 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, return_x, return_y) self._log_kv( "粉丝团处理", "加入粉丝团成功后,点击返回直播间", x=return_x, y=return_y, base_x=527, base_y=567, ) self.operation.delay(1.0) # 等待返回完成 except Exception as exc: self._log_kv( "粉丝团处理", "点击返回直播间失败", error=str(exc) ) except Exception: pass else: self._log_kv( "粉丝团处理", "未启用自动加入粉丝团,等待手动确认", wait_seconds=15, ) self.operation.delay(15.0) # 未启用自动加入时,也需要在等待后点击返回 # 加入粉丝团成功后,点击 (527, 567) 返回直播间 try: return_x = int(527 * self.resolution_ratio_x // 1080) return_y = int(567 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, return_x, return_y) self._log_kv( "粉丝团处理", "加入粉丝团成功后,点击返回直播间", x=return_x, y=return_y, base_x=527, base_y=567, ) self.operation.delay(1.0) # 等待返回完成 except Exception as exc: self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc)) # 延迟后返回,让主循环继续处理 self.operation.delay(0.5) # 如果失败,根据配置决定是否切换直播间 fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay") if fansclub_fail_action == "switch": self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间") try: self.swipe_up_to_next_live() except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理粉丝团)", elapsed_seconds=round(elapsed, 2), ) return elif stage == "FUDai_DETAIL": # 已经在详情页:检查是否是预约回退后的直接参与 reservation_direct_attend = getattr( self, "_reservation_back_direct_attend", False ) try: self._log_kv( "预约", "[预约] 检测到福袋详情页,检查预约回退直接参与标志", stage=stage, reservation_direct_attend=reservation_direct_attend, ) except Exception: pass if reservation_direct_attend: # 先检查预约是否过期 expired = False try: if self.reservations and len(self.reservations) > 0: first_reservation = self.reservations[0] future_ts = float( first_reservation.get("future_ts", 0.0) or 0.0 ) if future_ts > 0: now_ts = time.time() poll_before = float( getattr( self, "high_value_fudai_poll_before_seconds", 10.0 ) or 10.0 ) expired_threshold = future_ts + max(0.0, poll_before) if now_ts > expired_threshold: expired = True from datetime import datetime future_str = ( datetime.fromtimestamp(future_ts).strftime( "%Y-%m-%d %H:%M:%S" ) if future_ts > 0 else "无效" ) expired_seconds = int(now_ts - expired_threshold) self._log_kv( "预约", "[预约] 预约回退后直接参与:福袋已过期,清除标志", future_ts=int(future_ts), future_str=future_str, expired_seconds=expired_seconds, ) # 清除相关标志 self._reservation_back_direct_attend = False self._force_attend_after_reservation_back = False self.queue_full_waiting_at_earliest = False # 清理过期预约 from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name douyin_reservation_logic.cleanup_expired_reservations( analyser=self, reservations=self.reservations, write_state_callback=lambda: None, ) except Exception: pass if not expired: # 预约回退后直接参与:使用正常流程,但设置强制参与标志 try: self._reservation_back_direct_attend = False # 清除标志 # 设置强制参与标志,让 basic_join_decision 跳过倒计时检查 self._force_attend_after_reservation_back = True self._log_kv( "预约", "[预约] 预约回退后直接参与:使用正常流程,设置强制参与标志", flag_cleared=True, force_attend=True, ) except Exception: pass # 使用正常流程处理 self._handle_reservation_direct_attend() else: # 已过期,执行正常流程 self._handle_in_fudai_detail() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(预约回退直接参与)", elapsed_seconds=round(elapsed, 2), ) else: # 正常流程:读详情并决定是否参与 try: self._log_kv( "预约", "[预约] 预约回退直接参与标志为False,执行正常流程", reservation_direct_attend=reservation_direct_attend, ) except Exception: pass self._handle_in_fudai_detail() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理福袋详情)", elapsed_seconds=round(elapsed, 2), ) elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"): # 在直播间:检查是否是预约回退后的直接参与 reservation_direct_attend = getattr( self, "_reservation_back_direct_attend", False ) try: self._log_kv( "预约", "[预约] 检测到直播间,检查预约回退直接参与标志", stage=stage, reservation_direct_attend=reservation_direct_attend, ) except Exception: pass if reservation_direct_attend: # 先检查预约是否过期 expired = False try: if self.reservations and len(self.reservations) > 0: first_reservation = self.reservations[0] future_ts = float( first_reservation.get("future_ts", 0.0) or 0.0 ) if future_ts > 0: now_ts = time.time() poll_before = float( getattr( self, "high_value_fudai_poll_before_seconds", 10.0 ) or 10.0 ) expired_threshold = future_ts + max(0.0, poll_before) if now_ts > expired_threshold: expired = True from datetime import datetime future_str = ( datetime.fromtimestamp(future_ts).strftime( "%Y-%m-%d %H:%M:%S" ) if future_ts > 0 else "无效" ) expired_seconds = int(now_ts - expired_threshold) self._log_kv( "预约", "[预约] 预约回退后直接参与:福袋已过期,清除标志", future_ts=int(future_ts), future_str=future_str, expired_seconds=expired_seconds, ) # 清除相关标志 self._reservation_back_direct_attend = False self._force_attend_after_reservation_back = False self.queue_full_waiting_at_earliest = False # 清理过期预约 from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name douyin_reservation_logic.cleanup_expired_reservations( analyser=self, reservations=self.reservations, write_state_callback=lambda: None, ) except Exception: pass if not expired: # 预约回退后直接参与:查找福袋并打开详情页,然后直接参与 try: self._reservation_back_direct_attend = False # 清除标志 # 设置强制参与标志,让 basic_join_decision 跳过倒计时检查 self._force_attend_after_reservation_back = True self._log_kv( "预约", "[预约] 预约回退后直接参与:查找福袋并打开详情页,设置强制参与标志", flag_cleared=True, force_attend=True, stage=stage, ) except Exception: pass # 回退后等待页面加载和查找福袋都使用 switch_room_wait_after_stage_diag_seconds 参数 try: wait_seconds = float( getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0 ) self._log_kv( "预约", "[预约] 预约回退后等待页面加载(使用 switch_room_wait_after_stage_diag_seconds)", wait_seconds=wait_seconds, ) self.operation.delay(wait_seconds) except Exception: try: time.sleep(7.0) except Exception: pass # 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间) from douyin.core import ( douyin_flow_control, ) # pylint: disable=redefined-outer-name room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)] # 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds original_max_wait = None try: original_max_wait = getattr( self, "fudai_icon_max_wait_seconds", None ) wait_seconds_for_find = float( getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0 ) self.fudai_icon_max_wait_seconds = wait_seconds_for_find self._log_kv( "预约", "[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)", room_pos=room_pos_ref[0], max_wait_seconds=wait_seconds_for_find, ) except Exception: pass found = douyin_flow_control.find_and_open_fudai_detail( self, room_pos_ref ) # 恢复原始配置 try: if original_max_wait is not None: self.fudai_icon_max_wait_seconds = original_max_wait elif hasattr(self, "fudai_icon_max_wait_seconds"): delattr(self, "fudai_icon_max_wait_seconds") except Exception: pass try: self._log_kv( "预约", "[预约] 查找福袋结果", found=found, room_pos=room_pos_ref[0], ) except Exception: pass if found: # 成功打开详情页,直接参与 try: self._log_kv( "预约", "[预约] 成功打开详情页,开始直接参与", ) except Exception: pass self._handle_reservation_direct_attend() else: # 查找福袋失败,保留标志,下一轮继续尝试 try: self._reservation_back_direct_attend = True # 恢复标志 self._log_kv( "预约", "[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试", flag_restored=True, ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(预约回退直接参与)", elapsed_seconds=round(elapsed, 2), ) return # 在直播间:如果刚刚切换了直播间,等待福袋加载 just_switched = getattr(self, "_just_switched_room", False) if just_switched: try: self._just_switched_room = False # 清除标志 wait_seconds = float( getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0 ) if wait_seconds > 0: self._log_kv( "流程", "切换直播间后,阶段检测完成,等待福袋加载", wait_seconds=wait_seconds, ) self.operation.delay(wait_seconds) except Exception as e: try: self._just_switched_room = False # 确保清除标志 self._log_kv("流程", "等待福袋加载时出错", error=str(e)) except Exception: pass # 在直播间:寻找福袋图标并尝试点开 self._handle_live_room_has_or_not_fudai() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理直播间)", elapsed_seconds=round(elapsed, 2), ) elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"): # 处理推荐/关注/直播列表页:回到直播间或切换 if stage == "RECOMMEND_PAGE": # 识别到推荐页面:直接点击进入直播页,然后点击进入直播间 self._log_kv( "流程", "检测到推荐页面,点击进入直播页并进入直播间", stage=stage, seen=seen, ) try: # 直接点击 (718, 169) 进入直播页 - 基于1080x2400分辨率 live_tab_x = int(718 * self.resolution_ratio_x // 1080) live_tab_y = int(169 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, live_tab_x, live_tab_y) self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y) self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY) # 点击进入直播间的位置 (103, 382),连点两次 enter_live_x = int(103 * self.resolution_ratio_x // 1080) enter_live_y = int(382 * self.resolution_ratio_y // 2400) self.operation.click(self.device_id, enter_live_x, enter_live_y) self.operation.delay(self.ENTER_LIVE_CLICK_DELAY) self.operation.click(self.device_id, enter_live_x, enter_live_y) self._log_kv( "流程", "点击进入直播间位置", x=enter_live_x, y=enter_live_y, 次数=2, ) self.operation.delay(self.ENTER_LIVE_FINAL_DELAY) except Exception as e: self._log_kv("流程", "处理推荐页面时出错", error=str(e)) # 如果出错,尝试回退 try: self.operation.click_back(self.device_id) self.operation.delay(1.0) except Exception: pass else: # 其他列表页:使用原有逻辑 douyin_live_room.reflash_zhibo(self) elif stage == "FUDai_RESULT": # 抽奖结果弹窗:处理开奖结果(使用OCR识别,不使用阶段诊断) # 清除等待开奖标志 self._waiting_for_lottery_result = False self._log_kv("开奖结果", "检测到抽奖结果弹窗,使用OCR识别处理") # 直接OCR识别并处理 result = self._check_lottery_result_by_ocr() if result: self._handle_lottery_result_by_ocr(result) else: # OCR识别失败,使用返回键关闭 try: self.operation.click_back(self.device_id) self.operation.delay(0.5) self.swipe_up_to_next_live() except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(处理开奖结果)", elapsed_seconds=round(elapsed, 2), ) return elif stage in ("LIVE_CLOSED",): # 直播结束:下滑/切下一个 self._log_kv("阶段", "当前直播已结束,尝试切换下一个") self.swipe_up_to_next_live() elapsed = time.time() - start_time self._log_kv( "流程", "run_once_basic完成(直播结束)", elapsed_seconds=round(elapsed, 2), ) else: # 未识别出特殊阶段:尽量保持原地,交给上层循环 elapsed = time.time() - start_time self._log_kv( "阶段", "未匹配到特定阶段", stage=stage, elapsed_seconds=round(elapsed, 2), ) def _check_lottery_result_by_ocr(self) -> Optional[str]: """通过OCR识别开奖结果按钮区域,返回识别到的文本类型。""" return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self) def _handle_lottery_result_by_ocr(self, result_type: str) -> None: """根据OCR识别结果处理开奖结果。 参数: result_type: "我知道了" 或 "立即领取奖品" """ douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type) def _shot_and_diagnose( self, tag: str, msg: str, device_id: str, diagnose: bool = True ) -> None: """截图并执行阶段诊断(兼容旧版调用方式)。 Args: tag: 日志标签 msg: 日志消息 device_id: 设备ID diagnose: 是否执行阶段诊断(默认True) """ douyin_helpers.HelperFunctions.shot_and_diagnose( self, tag, msg, device_id, diagnose ) # ========== 基础动作封装 ========== def swipe_up_to_next_live(self) -> None: """上滑切换直播间(简单版封装)。 注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间), 则不允许上划离开预约直播间,直接返回。 """ douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self) def _return_to_recommend_and_reenter_live(self) -> None: """返回推荐页面并重新进入直播间。 通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。 """ douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self) def swipe_down_back_from_live(self) -> None: """上划回退到上一个直播间(供预约/无福袋逻辑使用)。""" douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self) def _maybe_reset_after_swipes(self) -> int: """达到切换阈值后,在当前直播间页面回退到第一个直播间。 返回: 重置后的滑动次数(通常为0) """ return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self) def _seek_reservation_room(self, item: dict[str, Any]) -> bool: """根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。 说明: - 使用 high_value_fudai_max_swipe_back 约束最大回退次数; - 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。 """ return douyin_reservation_handler.ReservationHandler.seek_reservation_room( self, item ) # ========== 福袋相关 ========== def _handle_reservation_direct_attend(self) -> None: """预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。""" douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend( self ) def _handle_in_fudai_detail(self) -> None: """已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。""" start_time = time.time() # 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋 # 检查是否是第二次打开福袋详情(已经读取过详情) # 如果是第二次打开,直接点击参与,不需要验证,使用第一次的倒计时 is_second_open = getattr(self, "_fudai_detail_first_read", False) if is_second_open: # 第二次打开:直接点击参与,不进行验证,使用第一次的倒计时 try: self._log_kv( "流程", "_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别", ) except Exception: pass # 获取第一次读取的详情数据 detail = getattr(self, "_last_fudai_detail_tuple", None) if detail is None or not isinstance(detail, tuple) or len(detail) < 6: # 如果没有保存的详情数据,需要重新读取(兜底逻辑) try: self._log_kv( "流程", "_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取", ) except Exception: pass detail = douyin_fudai_detail.read_fudai_detail_with_retries( self, fudai_x=0, read_once_callback=douyin_fudai_detail.read_fudai_detail_once, close_detail_callback=douyin_fudai_detail.close_fudai_detail, ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, ) # 重新读取后,更新保存的详情数据 if detail and isinstance(detail, tuple) and len(detail) >= 6: self._last_fudai_detail_tuple = detail else: # 使用第一次保存的详情数据,设置当前福袋的倒计时信息 try: detail: Optional[Tuple[Any, ...]] = getattr( self, "_last_fudai_detail_tuple", None ) if ( detail is not None and isinstance(detail, tuple) and len(detail) >= 6 ): # 类型检查:detail 已经通过 isinstance 检查,可以安全地索引 countdown_tuple: Any = detail[5] if ( isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 ): future_ts = float(countdown_tuple[1] or 0.0) if future_ts > 0: # 设置当前福袋的 future_ts,供 attend_choujiang 使用 self._current_fudai_future_ts = future_ts self._log_kv( "参与", "第二次打开:使用第一次的倒计时信息", future_ts=int(future_ts), remain_seconds=int(future_ts - time.time()), ) except Exception as e: self._log_kv( "参与", "第二次打开:设置倒计时信息时出错", error=str(e), ) # 直接调用参与函数,不进行验证 try: attend_result = douyin_fudai_core.attend_choujiang(self) if attend_result: self._log_kv( "参与", "第二次打开:直接点击参与成功", result="参与成功", ) else: self._log_kv( "参与", "第二次打开:直接点击参与失败", result="参与失败", ) # 清除第一次读取标志,下次打开新福袋时重新识别 try: self._fudai_detail_first_read = False self._last_fudai_detail_tuple = None except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(第二次打开直接参与)", elapsed_seconds=round(elapsed, 2), attend_result=attend_result, ) return except Exception as e: self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e)) # 异常时继续正常流程 else: # 第一次打开:完整读取详情(包括内容、倒计时、价值) detail = douyin_fudai_detail.read_fudai_detail_with_retries( self, fudai_x=0, read_once_callback=douyin_fudai_detail.read_fudai_detail_once, close_detail_callback=douyin_fudai_detail.close_fudai_detail, ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open, ) # 在第一次打开时立即进行筛选检查,如果不符合要求则直接跳过 # 注意:这里只检查筛选条件,不执行参与操作 if detail and isinstance(detail, tuple) and len(detail) >= 6: # 先进行数据验证 is_valid = True try: is_valid, reason = douyin_fudai_detail.validate_fudai_detail( detail, self ) if not is_valid: try: self._log_kv( "流程", "_handle_in_fudai_detail:第一次打开时数据验证失败,跳过", validation_reason=reason, ) except Exception: pass # 关闭详情页并返回 try: douyin_fudai_detail.close_fudai_detail(self) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(数据验证失败)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass # 执行筛选检查(不执行参与操作,只检查是否符合筛选条件) try: skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config( self, detail ) if skip: # 检查是否是高价值福袋,如果是则记录预约或立即参与 try: # 提取价值信息 prize_value_yuan = 0.0 countdown_tuple = None if isinstance(detail, tuple) and len(detail) >= 6: detail_values = detail prize_value_yuan = float(detail_values[4] or 0.0) countdown_tuple = detail_values[5] # 检查是否启用高价值预约 high_value_enabled = bool( getattr(self, "high_value_fudai_enabled", False) ) high_value_threshold = float( getattr(self, "high_value_fudai_threshold_yuan", 500.0) or 500.0 ) # 检查价值是否达到高价值阈值 is_high_value = ( high_value_enabled and prize_value_yuan > 0 and prize_value_yuan >= high_value_threshold and isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 and float(countdown_tuple[1] or 0.0) > 0.0 ) # 如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约 if is_high_value and skip_reason.startswith( "countdown_gt_" ): # 计算剩余秒数 remain_seconds = None if ( isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 ): try: now = time.time() cd_start = float(countdown_tuple[0] or 0.0) cd_end = float(countdown_tuple[1] or 0.0) if cd_start > 0 and cd_end > cd_start: remain_seconds = float(cd_end - now) except Exception: pass # 获取"预约参与阈值"配置 join_ahead_seconds = int( getattr( self, "high_value_fudai_join_ahead_seconds", 120 ) or 120 ) # 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约 if ( remain_seconds is not None and remain_seconds <= join_ahead_seconds ): try: self._log_kv( "流程", "_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与", reason=skip_reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=int(remain_seconds), join_ahead_threshold=join_ahead_seconds, ) except Exception: pass # 不关闭详情,继续走立即参与逻辑(保存详情数据,标记为已读取) skip = False else: # 剩余秒数大于"预约参与阈值",记录预约 try: self._log_kv( "流程", "_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约", reason=skip_reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, remain_seconds=( int(remain_seconds) if remain_seconds is not None else None ), join_ahead_threshold=join_ahead_seconds, ) except Exception: pass # 调用 basic_join_decision 来记录预约 # 注意:basic_join_decision 内部已经关闭详情并切换直播间,不需要再次关闭 try: douyin_fudai_core.basic_join_decision( self, detail ) except Exception as e: try: self._log_kv( "流程", "_handle_in_fudai_detail:记录预约时出错", error=str(e), ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(记录预约)", elapsed_seconds=round(elapsed, 2), ) return except Exception as e: # 高价值检查异常,记录日志但继续流程 try: self._log_kv( "流程", "_handle_in_fudai_detail:高价值检查异常", error=str(e), ) except Exception: pass # 如果不是高价值福袋,或者不是倒计时原因,筛选不通过,直接跳过 if skip: try: self._log_kv( "流程", "_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过", skip_reason=skip_reason, ) except Exception: pass # 关闭详情页 try: douyin_fudai_detail.close_fudai_detail(self) except Exception: pass # 如果允许切换直播间,筛选不通过直接切换直播间 try: needswitch = bool(getattr(self, "needswitch", True)) except Exception: needswitch = True if needswitch: try: self._log_kv( "流程", "_handle_in_fudai_detail:筛选不通过后切换直播间", skip_reason=skip_reason, ) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(self, "swipe_up_to_next_live"): self.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int( getattr( self, "resolution_ratio_x", 1080 ) or 1080 ) ry = int( getattr( self, "resolution_ratio_y", 2400 ) or 2400 ) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: import subprocess if hasattr(self.operation, "_adb"): adb_cmd = self.operation._adb() else: import os adb_cmd = ( os.environ.get( "ADB_EXECUTABLE", "adb" ) or "adb" ) 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( cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except Exception: # 回退到 operation.swipe self.operation.swipe( self.device_id, start_x, start_y, end_x, end_y, 300, ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2), ) return except Exception as e: # 筛选检查异常,记录日志但继续流程 try: self._log_kv( "流程", "_handle_in_fudai_detail:筛选检查异常", error=str(e), ) except Exception: pass # 筛选通过,保存详情数据并标记为已读取 try: self._last_fudai_detail_tuple = detail self._fudai_detail_first_read = True except Exception: pass else: # 详情数据无效,不保存,不标记为已读取 try: self._log_kv( "流程", "_handle_in_fudai_detail:第一次打开时详情数据无效,跳过", ) except Exception: pass return # 检查是否是优惠券弹窗、观看任务或识别错误:如果检测到,应该直接跳过,不继续处理 try: last_status = getattr(self, "_last_fudai_detail_status", "") if last_status == "coupon_popup": try: self._log_kv( "流程", "_handle_in_fudai_detail:检测到优惠券弹窗,已关闭,跳过后续处理", ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(优惠券弹窗)", elapsed_seconds=round(elapsed, 2), ) return elif last_status == "watch_task": try: self._log_kv( "流程", "_handle_in_fudai_detail:检测到'观看X分钟'任务,已在OCR阶段跳过,无需后续处理", ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(观看任务)", elapsed_seconds=round(elapsed, 2), ) return elif last_status == "validation_failed": try: self._log_kv( "流程", "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理", ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(验证失败)", elapsed_seconds=round(elapsed, 2), ) return elif last_status == "error": # 检查是否是任务数量为0的错误 try: last_extra = getattr(self, "_last_fudai_detail_extra", {}) if ( isinstance(last_extra, dict) and last_extra.get("reason") == "task_count_zero" ): # 记录连续失败次数 consecutive_failures = ( getattr(self, "_fudai_detail_consecutive_failures", 0) or 0 ) consecutive_failures += 1 try: self._fudai_detail_consecutive_failures = ( consecutive_failures ) except Exception: pass # 如果连续失败3次,强制关闭详情页并切换直播间,避免卡死 if consecutive_failures >= 3: try: self._log_kv( "流程", "_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死", consecutive_failures=consecutive_failures, ) except Exception: pass # 强制关闭详情页 try: douyin_fudai_detail.close_fudai_detail(self) self.operation.delay(0.5) except Exception: pass # 切换直播间 try: needswitch = bool(getattr(self, "needswitch", True)) except Exception: needswitch = True if needswitch: try: if hasattr(self, "swipe_up_to_next_live"): self.swipe_up_to_next_live() else: rx = int( getattr(self, "resolution_ratio_x", 1080) or 1080 ) ry = int( getattr(self, "resolution_ratio_y", 2400) or 2400 ) start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: import subprocess if hasattr(self.operation, "_adb"): adb_cmd = self.operation._adb() else: import os adb_cmd = ( os.environ.get( "ADB_EXECUTABLE", "adb" ) or "adb" ) 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( cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except Exception: # 回退到 operation.swipe self.operation.swipe( self.device_id, start_x, start_y, end_x, end_y, 300, ) self.operation.delay(0.5) except Exception: pass # 重置失败计数 try: self._fudai_detail_consecutive_failures = 0 except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(连续失败)", elapsed_seconds=round(elapsed, 2), ) return else: try: self._log_kv( "流程", "_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理", consecutive_failures=consecutive_failures, ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(任务数量为0)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass except Exception: pass # 如果成功读取,重置失败计数 try: self._fudai_detail_consecutive_failures = 0 except Exception: pass # 额外验证:使用验证函数检查数据合理性 try: # 使用已导入的模块,避免重复导入导致作用域问题 if detail is None: try: self._log_kv("福袋详情", "详情数据为 None,跳过验证") except Exception: pass else: is_valid, reason = douyin_fudai_detail.validate_fudai_detail( detail, self ) if not is_valid: try: self._log_kv( "流程", "_handle_in_fudai_detail:福袋详情数据验证失败,识别出错", validation_reason=reason, ) except Exception: pass douyin_fudai_detail.close_fudai_detail(self) elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(验证失败)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 try: 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( "流程", "_handle_in_fudai_detail:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", content=content, prize_value_yuan=prize_value_yuan, ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(无效详情)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass # 记录参与前的状态 attend_before_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0 # 记录当前福袋的 future_ts,供 attend_choujiang 使用 try: if isinstance(detail, tuple) and len(detail) >= 6: countdown_tuple = detail[5] if ( isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 ): future_ts = float(countdown_tuple[1] or 0.0) if future_ts > 0: self._current_fudai_future_ts = future_ts except Exception: pass # 重置详情关闭标志 try: self._detail_closed_by_attend = False except Exception: pass # 执行参与决策 if detail is None: try: self._log_kv("参与", "详情数据为 None,无法执行参与决策") except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_in_fudai_detail完成(详情为None)", elapsed_seconds=round(elapsed, 2), ) return join_result = douyin_fudai_core.basic_join_decision(self, detail) # 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功 attend_after_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0 if join_result and attend_after_ts > attend_before_ts: # 参与成功,设置等待开奖标志,停止其他行为 try: # 从 detail 中提取倒计时信息 countdown_tuple = None remain_seconds = 0 future_timestamp = 0.0 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) # 计算剩余秒数:结束时间戳 - 当前时间 current_time = time.time() if future_timestamp > current_time: remain_seconds = int(future_timestamp - current_time) if remain_seconds > 0: # 设置等待开奖标志和预期开奖时间 # 直接保存开奖时间戳,等待时直接用 future_timestamp - time.time() 计算剩余秒数 # 提前13秒,修正倒计时误差 self._waiting_for_lottery_result = True self._lottery_result_expected_ts = ( future_timestamp - 13.0 ) # 提前13秒,修正倒计时误差 self._log_kv( "参与", "参与成功,设置等待开奖标志,停止其他行为", remain_seconds=remain_seconds, future_ts=int(future_timestamp), ) # 检查是否是预约福袋,如果是,清除锁定期并从预约队列中移除已完成的预约 try: if getattr(self, "reservation_after_action_pending", False): # 这是预约福袋,参与成功后需要清除锁定期和移除预约 try: self._log_kv( "预约", "[预约] 参与成功,清除锁定期并移除预约", future_ts=int(future_timestamp), ) except Exception: pass # 清除锁定期 self.reservation_focus_until_ts = 0.0 self.reservation_after_action_pending = False # 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差) if hasattr(self, "reservations") and self.reservations: from douyin.reservation import ( douyin_reservation_logic, ) # pylint: disable=redefined-outer-name reservations_to_remove = [] for idx, r in enumerate(self.reservations): try: r_ft = float(r.get("future_ts") or 0.0) if ( r_ft > 0 and abs(r_ft - future_timestamp) < 5.0 ): reservations_to_remove.append(idx) except Exception: continue # 从后往前删除,避免索引变化 for idx in reversed(reservations_to_remove): try: removed = self.reservations.pop(idx) try: self._log_kv( "预约", "[预约] 已从队列中移除已完成的预约", future_ts=int( removed.get("future_ts", 0) ), content=str(removed.get("content", ""))[ :50 ], ) except Exception: pass except Exception: pass # 重新排序预约队列 if self.reservations: try: douyin_reservation_logic._sort_reservations_inplace( self.reservations ) except Exception: pass except Exception as e: try: self._log_kv( "预约", "[预约] 清除锁定期和移除预约时出错", error=str(e), ) except Exception: pass # 关闭详情页,返回直播间等待开奖 # 检查 attend_choujiang 是否已经关闭了详情,如果已关闭就不应该再点击返回键 detail_already_closed = getattr( self, "_detail_closed_by_attend", False ) if not detail_already_closed: try: self.operation.click_back(self.device_id) self.operation.delay(1.0) self._log_kv("参与", "已关闭详情页,返回直播间等待开奖") except Exception: pass else: try: self._log_kv( "参与", "详情页已由 attend_choujiang 关闭,跳过返回键点击", ) except Exception: pass # 清除第一次读取标志,下次打开新福袋时重新识别 try: self._fudai_detail_first_read = False self._last_fudai_detail_tuple = None except Exception: pass # 清除第一次读取标志,下次打开新福袋时重新识别 try: self._fudai_detail_first_read = False self._last_fudai_detail_tuple = None except Exception: pass # 返回,让主循环只检测开奖结果,不执行其他操作 return else: self._log_kv("参与", "参与成功但无法获取倒计时,跳过等待") except Exception as e: self._log_kv("参与", "设置等待开奖标志时出错", error=str(e)) def _handle_live_room_has_or_not_fudai(self) -> None: """在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号".""" start_time = time.time() # 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别) # 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋 try: already_verified = bool( getattr(self, "_fudai_detail_verified", False) or False ) if already_verified: try: self._log_kv( "流程", "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋", ) except Exception: pass # 直接调用详情处理逻辑,不查找福袋 self._handle_in_fudai_detail() elapsed = time.time() - start_time self._log_kv( "流程", "_handle_live_room_has_or_not_fudai完成(已验证详情页)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass # 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情 try: 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 ) if focus_until > 0 and now_ts < focus_until and queue_full_waiting: # 在锁定期内,且队列满等待中,检查时间窗口 if self.reservations and len(self.reservations) > 0: earliest = self.reservations[0] try: ft = float(earliest.get("future_ts") or 0.0) if ft > 0: join_ahead = float( getattr( self, "high_value_fudai_join_ahead_seconds", 120 ) or 120 ) # poll_before = float( # getattr(self, "poll_before_open_seconds", 10.0) or 10.0 # ) # 未使用,注释掉 time_window_start_ts = ft - join_ahead # 如果时间窗口未到,避免重复打开福袋详情 if now_ts < time_window_start_ts: try: self._log_kv( "预约", "[预约] 锁定期内时间窗口未到,避免重复打开福袋详情", focus_until=int(focus_until), now_ts=int(now_ts), time_window_start=int(time_window_start_ts), remain_seconds=int( time_window_start_ts - now_ts ), ) except Exception: pass elapsed = time.time() - start_time self._log_kv( "流程", "_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)", elapsed_seconds=round(elapsed, 2), ) return except Exception: pass except Exception: pass room_pos_ref: List[int] = [0] opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref) if not opened: # 无福袋,交给 flow_control 的“无福袋处理”逻辑 # 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房) try: needswitch_cfg = bool(getattr(self, "needswitch", True)) except Exception: needswitch_cfg = True wait_times_ref = [0] swipe_times_ref = [0] reservation_focus_until_ts_ref = [0.0] reset_to_list_after_reservations_ref = [False] douyin_flow_control.handle_no_fudai_situation( self, x=0, swipe_times=0, wait_times_ref=wait_times_ref, needswitch=needswitch_cfg, reservation_focus_until_ts=0.0, reservations=[], room_pos=room_pos_ref[0], post_switch_delay_s=1.5, swipe_up_switch_callback=self.swipe_up_to_next_live, swipe_down_back_callback=lambda: None, sort_reservations_callback=lambda: None, clear_reservations_callback=lambda: None, write_state_callback=lambda: None, back_to_list_callback=lambda: None, into_list_callback=lambda: None, reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref, swipe_times_ref=swipe_times_ref, ) elapsed = time.time() - start_time self._log_kv( "流程", "_handle_live_room_has_or_not_fudai完成(无福袋)", elapsed_seconds=round(elapsed, 2), ) return # 成功打开详情:调用同一套详情处理逻辑 self._handle_in_fudai_detail() elapsed = time.time() - start_time self._log_kv( "流程", "_handle_live_room_has_or_not_fudai完成(成功打开详情)", elapsed_seconds=round(elapsed, 2), )