Files
douyin_guaji-main/douyin_fudai.py
T
Your Name f92933641f feat: Enhance documentation and clean up code structure
- Added comprehensive documentation for the unified screenshot and score recording process in the new markdown file.
- Improved existing markdown files by adding spacing for better readability.
- Cleaned up code by removing unnecessary blank lines across various scripts, enhancing overall code clarity.
- Updated configuration settings to reflect recent changes and ensure consistency across the project.
- Enhanced logging mechanisms to support better debugging and monitoring.
2025-12-25 16:11:25 +08:00

3354 lines
146 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
"""
本地完整版 douyin_fudai(模块化调度器)
======================================
目标:
- 不再依赖外部 axf 目录;
- 保持 `from douyin_fudai import fudai_analyse` 导入方式不变;
- 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。
"""
from typing import Any, List, Tuple, Optional
import os
import time
import sys
import logging
from Underlying_Operations import underlying_operations
import douyin_stage
import douyin_detection
import douyin_fudai_detail
import douyin_fudai_core
import douyin_flow_control
import douyin_live_room
import douyin_lottery
import douyin_popups
import douyin_robot
import douyin_swipe_ops
import douyin_text_utils
import douyin_utils
import douyin_yanghao
import douyin_pixel
import douyin_reservation_logic
import douyin_reservation_verify
import douyin_high_value_room
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.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 = self._enhanced_log_kv
# 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告
self._std_logger = None # type: ignore[assignment]
# 初始化统一日志系统和traceId
# 确保日志系统已配置(在实例化之前)
try:
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:
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 = 2.0
# 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.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]] = []
# 当前“直播间位置”计数:上划 +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"
)
# 初次加载配置
self.load_config()
# ===== 兼容原始脚本的一些简单封装方法 =====
def click(self, x: int, y: int) -> None:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
try:
self.operation.click(self.device_id, int(x), int(y))
except Exception:
pass
def load_config(self) -> None:
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
import json
import os
path = getattr(self, "config_path", "config.json")
try:
if not os.path.exists(path):
return
with open(path, "r", encoding="utf-8") as f:
config = json.load(f)
except Exception:
return
try:
self.contains_not_want = list(config.get("contains_not_want", []) or [])
except Exception:
self.contains_not_want = []
try:
self.contains_want = list(config.get("contains_want", []) or [])
except Exception:
self.contains_want = []
def _float(name: str, default: float) -> float:
try:
return float(config.get(name, default) or default)
except Exception:
return default
def _int(name: str, default: int) -> int:
try:
return int(config.get(name, default) or default)
except Exception:
return default
self.min_prize_value_yuan = _float(
"min_prize_value_yuan", self.min_prize_value_yuan
)
self.min_participants = _int("min_participants", self.min_participants)
self.max_participants = _int("max_participants", self.max_participants)
self.skip_if_countdown_gt_seconds = _int(
"skip_if_countdown_gt_seconds", self.skip_if_countdown_gt_seconds
)
self.skip_if_countdown_lt_seconds = _int(
"skip_if_countdown_lt_seconds", self.skip_if_countdown_lt_seconds
)
try:
self.no_fudai_watchdog_enabled = bool(
config.get("no_fudai_watchdog_enabled", self.no_fudai_watchdog_enabled)
)
except Exception:
pass
self.fudai_icon_retry_delay_seconds = _float(
"fudai_icon_retry_delay_seconds",
self.fudai_icon_retry_delay_seconds,
)
self.fudai_icon_max_wait_seconds = _float(
"fudai_icon_max_wait_seconds",
self.fudai_icon_max_wait_seconds,
)
self.fudai_click_wait_seconds = _float(
"fudai_click_wait_seconds",
self.fudai_click_wait_seconds,
)
self.fudai_find_max_attempts = _int(
"fudai_find_max_attempts",
self.fudai_find_max_attempts,
)
self.screenshot_diagnose_min_interval_seconds = _float(
"screenshot_diagnose_min_interval_seconds",
self.screenshot_diagnose_min_interval_seconds,
)
self.lucky_draw_red_ratio_threshold = _float(
"lucky_draw_red_ratio_threshold",
self.lucky_draw_red_ratio_threshold,
)
if self.lucky_draw_red_ratio_threshold < 0.0:
self.lucky_draw_red_ratio_threshold = 0.0
if self.lucky_draw_red_ratio_threshold > 1.0:
self.lucky_draw_red_ratio_threshold = 1.0
self.live_room_match_threshold = _float(
"live_room_match_threshold",
self.live_room_match_threshold,
)
# 确保阈值在合理范围内
if self.live_room_match_threshold < 0.0:
self.live_room_match_threshold = 0.0
if self.live_room_match_threshold > 1.0:
self.live_room_match_threshold = 1.0
try:
self.fudai_template_match_enabled = bool(
config.get(
"fudai_template_match_enabled", self.fudai_template_match_enabled
)
)
except Exception:
pass
self.fudai_template_match_threshold = _float(
"fudai_template_match_threshold",
self.fudai_template_match_threshold,
)
# 确保阈值在合理范围内
if self.fudai_template_match_threshold < 0.0:
self.fudai_template_match_threshold = 0.0
if self.fudai_template_match_threshold > 1.0:
self.fudai_template_match_threshold = 1.0
# 福袋详情页模板匹配阈值(独立配置)
self.fudai_detail_template_threshold = _float(
"fudai_detail_template_threshold",
0.7, # 默认值
)
# 确保阈值在合理范围内
if self.fudai_detail_template_threshold < 0.0:
self.fudai_detail_template_threshold = 0.0
if self.fudai_detail_template_threshold > 1.0:
self.fudai_detail_template_threshold = 1.0
# 粉丝团相关配置
try:
self.auto_join_fansclub = bool(
config.get("auto_join_fansclub", self.auto_join_fansclub)
)
except Exception:
pass
try:
self.fansclub_fail_action = str(
config.get("fansclub_fail_action", self.fansclub_fail_action) or "stay"
).lower()
except Exception:
pass
# —— 高价值福袋 / 预约配置加载 ——
try:
self.high_value_fudai_enabled = bool(
config.get("high_value_fudai_enabled", self.high_value_fudai_enabled)
)
except Exception:
pass
self.high_value_fudai_threshold_yuan = _float(
"high_value_fudai_threshold_yuan",
self.high_value_fudai_threshold_yuan,
)
self.high_value_fudai_join_ahead_seconds = _int(
"high_value_fudai_join_ahead_seconds",
self.high_value_fudai_join_ahead_seconds,
)
self.high_value_fudai_max_swipe_back = _int(
"high_value_fudai_max_swipe_back",
self.high_value_fudai_max_swipe_back,
)
self.high_value_fudai_max_reservations = _int(
"high_value_fudai_max_reservations",
self.high_value_fudai_max_reservations,
)
# 合理范围约束
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",
self.high_value_fudai_after_action,
)
or self.high_value_fudai_after_action
)
.strip()
.lower()
)
except Exception:
pass
if self.high_value_fudai_after_action not in ("stay", "continue"):
self.high_value_fudai_after_action = "continue"
self.high_value_fudai_after_stay_seconds = _int(
"high_value_fudai_after_stay_seconds",
self.high_value_fudai_after_stay_seconds,
)
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.high_value_room_revisit_only_current_run = bool(
config.get(
"high_value_room_revisit_only_current_run",
self.high_value_room_revisit_only_current_run,
)
)
except Exception:
pass
# 滑动次数重置配置
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 Exception:
self.reset_after_swipes = 10
if self.reset_after_swipes < 1:
self.reset_after_swipes = 1
# 意外返回桌面自救配置
try:
self.desktop_icon_x = int(config.get("desktop_icon_x", self.desktop_icon_x))
self.desktop_icon_y = int(config.get("desktop_icon_y", self.desktop_icon_y))
self.yanghao_fallback_live_x = int(
config.get("yanghao_fallback_live_x", self.yanghao_fallback_live_x)
)
self.yanghao_fallback_live_y = int(
config.get("yanghao_fallback_live_y", self.yanghao_fallback_live_y)
)
self.yanghao_fallback_enter_live_x = int(
config.get(
"yanghao_fallback_enter_live_x", self.yanghao_fallback_enter_live_x
)
)
self.yanghao_fallback_enter_live_y = int(
config.get(
"yanghao_fallback_enter_live_y", self.yanghao_fallback_enter_live_y
)
)
except Exception:
pass
# 预约回退与抢占策略
try:
self.reservation_back_verify_enabled = bool(
config.get(
"reservation_back_verify_enabled",
self.reservation_back_verify_enabled,
)
)
except Exception:
self.reservation_back_verify_enabled = True # 默认启用
self.reservation_back_swipe_delay = _float(
"reservation_back_swipe_delay",
self.reservation_back_swipe_delay,
)
if self.reservation_back_swipe_delay < 0.0:
self.reservation_back_swipe_delay = 0.0
self.reservation_preempt_min_value_yuan = _float(
"reservation_preempt_min_value",
self.reservation_preempt_min_value_yuan,
)
if self.reservation_preempt_min_value_yuan < 0.0:
self.reservation_preempt_min_value_yuan = 0.0
self.poll_before_open_seconds = _int(
"poll_before_open_seconds",
self.poll_before_open_seconds,
)
if self.poll_before_open_seconds < 0:
self.poll_before_open_seconds = 0
# 30分钟超时保护配置
self._no_attend_timeout_minutes = _float(
"no_attend_timeout_minutes",
self._no_attend_timeout_minutes,
)
# 合理范围约束:0表示禁用,最大24小时(1440分钟)
if self._no_attend_timeout_minutes < 0:
self._no_attend_timeout_minutes = 0
if self._no_attend_timeout_minutes > 1440:
self._no_attend_timeout_minutes = 1440
# ========== 兼容旧入口:主循环 ==========
def fudai_choujiang(
self,
device_id: str = "",
y_pianyi: int = 0,
needswitch: bool = False,
wait_minutes: int = 15,
) -> None:
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
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
try:
rx, ry = self.operation.get_device_resolution(self.device_id)
self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int(
ry or 2400
)
except Exception:
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:
import os
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
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 e:
# 捕获异常,记录日志,但继续循环
try:
self._log_kv(
"循环",
"run_once_basic 异常",
error=str(e),
error_type=type(e).__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:
from datetime import datetime
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
import os
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:
from datetime import datetime
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
import os
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 e:
# 捕获异常,记录日志,但继续循环
try:
self._log_kv(
"循环",
"run_once_basic 异常",
error=str(e),
error_type=type(e).__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) -> Tuple[str, str]:
"""封装到子模块的阶段诊断入口。"""
result = douyin_stage.diagnose_stage_from_current_screen(self)
if result is None:
return ("UNKNOWN", "阶段诊断返回 None")
return result
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
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 基准)。"""
try:
x1 = x_top * self.resolution_ratio_x // 1080
y1 = y_top * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
x2 = x_bottom * self.resolution_ratio_x // 1080
y2 = y_bottom * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
self.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name)
except Exception as e:
try:
self._log_kv(
"截图",
"cut_pic 失败",
error=str(e),
x_top=x_top,
y_top=y_top,
x_bottom=x_bottom,
y_bottom=y_bottom,
y_pianyi=y_pianyi,
)
except Exception:
pass
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时)
"""
import os
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
# 获取分辨率比例和y偏移参数
resolution_ratio_x = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
resolution_ratio_y = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
lucky_threshold = float(
getattr(self, "lucky_draw_red_ratio_threshold", 0.9) or 0.9
)
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
fudai_template_threshold = float(
getattr(self, "fudai_detail_template_threshold", None)
or getattr(self, "fudai_template_match_threshold", 0.7)
or 0.7
)
if fudai_template_threshold < 0.0:
fudai_template_threshold = 0.0
if fudai_template_threshold > 1.0:
fudai_template_threshold = 1.0
return douyin_pixel.read_pixel_stage_state_from_screenshot(
pic_path,
resolution_ratio_x,
resolution_ratio_y,
y_pianyi,
lucky_threshold,
fudai_template_threshold,
return_details=return_details,
analyser=self,
)
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
返回 (scaled_x, scaled_y)
"""
try:
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
y_off = int(getattr(self, "y_pianyi", 0) or 0)
sx = int(base_x * rx // 1080)
sy = int(base_y * ry // 2400) + y_off
return sx, sy
except Exception:
try:
return int(base_x), int(base_y)
except Exception:
return 0, 0
def _save_step_screenshot(self, label: str) -> None:
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
try:
import os
import shutil
base_dir = os.path.dirname(__file__)
pic_dir = os.path.join(base_dir, "pic")
# 确保有最新截图
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
src = os.path.join(pic_dir, "screenshot.png")
if not os.path.exists(src):
return
steps_dir = os.path.join(pic_dir, "steps")
os.makedirs(steps_dir, exist_ok=True)
fname = f"{getattr(self,'_run_id','run')}_{getattr(self,'_log_seq',0):04d}_{label}.png"
dst = os.path.join(steps_dir, fname)
try:
shutil.copy(src, dst)
except Exception:
# 最后降级为重命名保存
try:
shutil.copy(src, dst)
except Exception:
pass
except Exception:
pass
def _check_in_live_room_by_icon(self) -> Tuple[bool, float]:
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
返回:
(detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。
"""
# 为了兼容没有 cv2/numpy 的环境,这里做降级处理
try:
import cv2 # type: ignore
import numpy as np # type: ignore
import os
# 抑制OpenCV的文件读取警告(多种方法组合)
# 方法1:设置环境变量
os.environ["OPENCV_LOG_LEVEL"] = "ERROR"
# 方法2:使用cv2.setLogLevel(OpenCV 4.x+)
try:
cv2.setLogLevel(0) # 0 = SILENT
except (AttributeError, Exception):
# 如果setLogLevel不存在(旧版本OpenCV),尝试其他方法
try:
# OpenCV 3.x 使用 cv2.utils.logging.setLogLevel
if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"):
cv2.utils.logging.setLogLevel( # type: ignore[attr-defined]
cv2.utils.logging.LOG_LEVEL_SILENT # type: ignore[attr-defined]
)
except Exception:
pass
# 方法3:通过logging抑制Python层的警告
try:
import logging
logging.getLogger("cv2").setLevel(logging.ERROR)
except Exception:
pass
except Exception:
try:
self._log_kv(
"阶段诊断",
"_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别",
)
except Exception:
pass
return False, 0.0
base_dir = os.path.dirname(__file__)
pic_dir = os.path.join(base_dir, "pic")
assets_dir = os.path.join(base_dir, "assets")
screenshot_path = os.path.join(pic_dir, "screenshot.png")
# 确保有最新截图
try:
self.operation.get_screenshot(self.device_id)
except Exception:
# 若截图失败则尝试继续使用旧图
pass
if not os.path.exists(screenshot_path):
try:
self._log_kv(
"阶段诊断",
"_check_in_live_room_by_icon 截图不存在",
path=screenshot_path,
)
except Exception:
pass
return False, 0.0
try:
img = cv2.imread(
screenshot_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
if img is None:
raise RuntimeError("cv2.imread 返回 None")
except Exception as e:
try:
self._log_kv(
"阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e)
)
except Exception:
pass
return False, 0.0
# 获取可配置的匹配阈值(用于模板匹配,像素检测使用不同的阈值)
# 注意:live_room_match_threshold 主要用于像素检测,模板匹配可以使用稍低的阈值
threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
# 模板匹配可以使用稍低的阈值(像素检测优先,模板匹配作为补充)
template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90%
# 确保阈值在合理范围内
if threshold < 0.0:
threshold = 0.0
if threshold > 1.0:
threshold = 1.0
if template_threshold < 0.0:
template_threshold = 0.0
if template_threshold > 1.0:
template_threshold = 1.0
# 第一步:裁剪右上角图标区域,保存到 pic/ocr/ 目录
ih, iw = img.shape[:2]
roi_x1 = max(0, int(iw * 0.60)) # 60%宽度开始
roi_y1 = 0
roi_x2 = iw # 100%宽度
roi_y2 = min(ih, int(ih * 0.40)) # 40%高度
roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index]
if roi.size == 0:
try:
self._log_kv("阶段诊断", "_check_in_live_room_by_icon ROI区域为空")
except Exception:
pass
return False, 0.0
# 保存裁剪的ROI区域到 pic/ocr/ 目录
ocr_dir = os.path.join(pic_dir, "ocr")
os.makedirs(ocr_dir, exist_ok=True)
x_roi_path = os.path.join(ocr_dir, "xx.png")
xin_roi_path = os.path.join(ocr_dir, "xxin.png")
try:
# 保存ROI区域(两个文件保存相同的内容,因为x和xin图标在同一区域)
cv2.imwrite(x_roi_path, roi) # pyright: ignore[reportAttributeAccessIssue]
cv2.imwrite(
xin_roi_path, roi
) # pyright: ignore[reportAttributeAccessIssue]
except Exception as e:
try:
self._log_kv(
"阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e)
)
except Exception:
pass
# 第二步:使用 assets/ 目录下的模板去匹配 pic/ocr/ 目录下的裁剪图片
# assets/x.png 和 assets/xin.png 是模板
# pic/ocr/xx.png 和 pic/ocr/xxin.png 是要匹配的图片
template_roi_pairs = [
(os.path.join(assets_dir, "x.png"), x_roi_path, "x"),
(os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"),
]
best_score = 0.0
best_name = ""
detected = False
for template_path, roi_path, icon_name in template_roi_pairs:
try:
# 检查模板文件是否存在
if not os.path.exists(template_path) or not os.path.isfile(
template_path
):
continue
try:
if os.path.getsize(template_path) == 0:
continue
except (OSError, IOError):
continue
# 检查ROI文件是否存在(应该刚保存的)
if not os.path.exists(roi_path) or not os.path.isfile(roi_path):
continue
# 读取模板和ROI图片
try:
tpl = cv2.imread(
template_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
roi_img = cv2.imread(
roi_path, cv2.IMREAD_GRAYSCALE
) # pyright: ignore[reportAttributeAccessIssue]
except Exception:
continue
if tpl is None or roi_img is None:
continue
th, tw = tpl.shape[:2]
rh, rw = roi_img.shape[:2]
# 模板必须小于或等于ROI
if th > rh or tw > rw:
# 如果模板比ROI大,缩小模板
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale <= 0:
continue
tpl = cv2.resize( # pyright: ignore[reportAttributeAccessIssue]
tpl, (max(1, int(tw * scale)), max(1, int(th * scale)))
)
th, tw = tpl.shape[:2]
# 在ROI中匹配模板
res = cv2.matchTemplate(
roi_img, tpl, cv2.TM_CCOEFF_NORMED
) # pyright: ignore[reportAttributeAccessIssue]
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(
res
) # pyright: ignore[reportAttributeAccessIssue]
# 记录最佳匹配分数和模板名称
if max_val > best_score:
best_score = float(max_val or 0.0)
best_name = f"assets/{icon_name}.png -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png"
# 如果匹配分数达到阈值,标记为检测成功
# 使用 template_threshold(模板匹配阈值),而不是 threshold(像素检测阈值)
if max_val >= template_threshold:
detected = True
except Exception:
continue
if not detected and best_score == 0.0:
try:
self._log_kv(
"阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件"
)
except Exception:
pass
try:
self._log_kv(
"阶段诊断",
"_check_in_live_room_by_icon 结果",
detected=int(bool(detected)),
score=round(best_score, 3),
template=best_name or "-",
)
except Exception:
pass
return bool(detected), float(best_score or 0.0)
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 e:
try:
self._log_kv("检测", "check_in_fudai_detail 异常", error=str(e))
except Exception:
pass
return False
def _enhanced_log_kv(self, *args, **fields):
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging"""
# 解析参数:优先使用位置参数,避免与关键字参数冲突
if len(args) >= 1:
tag = args[0]
# 如果位置参数提供了 tag,从 fields 中移除 tag 避免冲突
fields.pop("tag", None)
else:
tag = fields.get("tag", "日志")
if len(args) >= 2:
msg = args[1]
# 如果位置参数提供了 msg,从 fields 中移除 msg 避免冲突
fields.pop("msg", None)
else:
msg = fields.get("msg", "")
# 获取日志级别
log_level = fields.get("level", "INFO").upper()
if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
log_level = "INFO"
# 递增日志序号
try:
self._log_seq += 1
except Exception:
self._log_seq = 1
# 获取时间戳
try:
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
except Exception:
# 如果无法导入 datetime(极少见),回退为 time.strftime,避免引用未定义的名字
try:
import time
timestamp = time.strftime("%H:%M:%S")
except Exception:
timestamp = ""
# 获取调用者信息(模块名:函数名:行号)
caller_info = ""
try:
import inspect
# 获取调用栈:跳过 _enhanced_log_kv 本身,找到真正的调用者
frame = inspect.currentframe()
if frame:
# frame.f_back 是调用 _enhanced_log_kv 的帧(可能是 _log_kv 或其他)
# 需要再往上找一层,找到实际调用 _log_kv 的代码
caller_frame = frame.f_back
if caller_frame:
# 检查是否是 _log_kv 的调用(属性赋值的情况)
if (
caller_frame.f_code.co_name == "_log_kv"
or "log_kv" in caller_frame.f_code.co_name
):
caller_frame = caller_frame.f_back
# 如果找到了调用者,提取信息
if caller_frame:
filename = caller_frame.f_code.co_filename
funcname = caller_frame.f_code.co_name
lineno = caller_frame.f_lineno
# 只取文件名,不包含路径
import os
filename = os.path.basename(filename)
# 如果文件名是 <string> 或类似,说明是测试代码,跳过
if filename and filename not in ("<string>", "<stdin>"):
caller_info = f"{filename}:{funcname}:{lineno}"
except Exception:
pass
# 字段映射(中文 key)
key_map = {
"rid": "运行",
"seq": "序号",
"msg": "说明",
"stage": "阶段",
"seen": "识别",
"ok": "成功",
"text": "文本",
"action": "动作",
"result": "结果",
"mode": "模式",
"reason": "原因",
"wait_seconds": "等待秒",
"value_yuan": "价值元",
"future": "开奖时间",
"pos_seen": "发现位置",
"qsize": "队列数量",
"room_pos": "当前位置",
"content": "内容",
"countdown": "倒计时",
"participants": "参与人数",
"copies": "份数",
"seconds": "耗时秒",
"error": "错误",
"error_type": "错误类型",
"fudai_x": "福袋X坐标",
"attempt": "尝试次数",
"room_title": "直播间名",
"back_times": "需回退次数",
}
# 构建日志行(增强格式:时间 级别 标签 [调用者] 消息 字段...)
log_parts = []
if timestamp:
log_parts.append(f"[{timestamp}]")
log_parts.append(f"[{log_level}]")
log_parts.append(f"[{tag}]")
# 添加调用者信息(如果获取成功)
if caller_info:
log_parts.append(f"[{caller_info}]")
if msg:
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
if len(m) > 200:
m = m[:200] + "..."
log_parts.append(m)
# 添加字段信息
for k, v in fields.items():
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
continue
if v is None:
continue
key_cn = key_map.get(str(k), f"字段_{k}")
# 格式化值
if isinstance(v, float):
if abs(v) < 1:
v_str = f"{v:.3f}"
elif abs(v) < 100:
v_str = f"{v:.2f}"
else:
v_str = f"{int(v)}"
elif isinstance(v, (int, bool)):
v_str = str(v)
else:
s = str(v).replace("\r", " ").replace("\n", " ").strip()
if len(s) > 100:
s = s[:100] + "..."
v_str = s
log_parts.append(f"{key_cn}={v_str}")
# 构建完整日志行
log_line = " ".join(log_parts)
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
try:
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
except Exception:
pass
# 写入行为日志(actions.log)- 使用运行日志格式,但只保留关键信息
# 记录所有操作到行为日志
try:
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
should_log = True
# 过滤一些不需要记录的日志(避免噪音)
if tag:
# 跳过一些调试或详细日志
skip_tags = ["[调试图像]", "[步骤耗时]"]
for skip_tag in skip_tags:
if tag.startswith(skip_tag):
should_log = False
break
if should_log:
# 获取时间戳
if not timestamp:
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
# 提取关键信息:做了什么、耗时、分数
# 如果msg为空,从tag中提取操作描述
if msg:
action_desc = str(msg)
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
import re
# 移除函数名(匹配函数名后跟冒号、空格的情况)
# 匹配模式:函数名(可能包含下划线)后跟冒号或空格
# 例如:read_fudai_detail_once: 或 read_fudai_detail_with_retries 或 _handle_in_fudai_detail:
# 先移除带冒号的函数名
action_desc = re.sub(
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
)
# 再移除带空格的函数名(但后面不是字母/下划线开头的单词)
# 例如:read_fudai_detail_with_retries 最终结果 -> 最终结果
action_desc = re.sub(
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
)
# 如果移除后为空,保留原描述
if not action_desc.strip():
action_desc = str(msg)
# 简化描述:移除字段前缀,只保留关键信息
if "字段_" in action_desc:
# 提取阶段信息(如果有)
if "字段_阶段=" in action_desc:
stage_match = re.search(r"字段_阶段=(\w+)", action_desc)
if stage_match:
action_desc = f"阶段={stage_match.group(1)}"
else:
# 简化其他字段描述,只保留消息部分
action_desc = action_desc.split("字段_")[0].strip()
else:
# 从tag中提取操作类型(移除标签的方括号)
if tag:
tag_clean = tag.strip("[]").strip()
if tag_clean:
action_desc = tag_clean
else:
action_desc = "操作"
else:
action_desc = "操作"
# 提取耗时(从字段中查找,优先使用毫秒字段)
elapsed_str = ""
if "elapsed_ms" in fields:
elapsed_seconds = float(fields.get("elapsed_ms", 0)) / 1000.0
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "total_elapsed_ms" in fields:
elapsed_seconds = float(fields.get("total_elapsed_ms", 0)) / 1000.0
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "总耗时毫秒" in fields:
elapsed_seconds = float(fields.get("总耗时毫秒", 0)) / 1000.0
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "seconds" in fields:
elapsed_seconds = float(fields.get("seconds", 0))
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
elif "elapsed_seconds" in fields:
elapsed_seconds = float(fields.get("elapsed_seconds", 0))
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
# 提取分数(如果有)
score_str = ""
if "score" in fields and fields.get("score") is not None:
try:
score_val = float(fields.get("score", 0))
score_str = f"分数:{score_val:.3f}"
except (ValueError, TypeError):
pass
elif "max_val" in fields and fields.get("max_val") is not None:
try:
score_val = float(fields.get("max_val", 0))
score_str = f"分数:{score_val:.3f}"
except (ValueError, TypeError):
pass
elif "分数" in fields:
score_field = fields.get("分数")
# 允许显示0.0分数,只要不是None
if score_field is not None:
try:
score_val = float(score_field)
score_str = f"分数:{score_val:.3f}"
except (ValueError, TypeError):
pass
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
action_parts = [timestamp, "-", "[GUI]", "-"]
if tag:
action_parts.append(tag)
else:
action_parts.append("[日志]")
action_parts.append(action_desc)
if elapsed_str:
action_parts.append(elapsed_str)
if score_str:
action_parts.append(score_str)
action_log_line = " ".join(action_parts)
# 写入 actions.log 文件
import os
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)
# 检测标签变化,用====分隔不同步骤
# 使用实例变量记录上一个标签
if not hasattr(self, "_last_action_tag"):
self._last_action_tag = None
# 如果标签变化,添加分隔符
current_tag = tag or "[日志]"
if (
self._last_action_tag is not None
and self._last_action_tag != current_tag
):
# 标签变化,添加分隔符(增加到80个等号)
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write("=" * 80 + "\n")
f.flush()
# 更新上一个标签
self._last_action_tag = current_tag
# 写入日志行
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write(action_log_line + "\n")
f.flush()
except Exception:
pass
# 同时输出到标准 logging(如果已配置,可选)
try:
# 确保日志系统已配置
import logging
root_logger = logging.getLogger()
if not root_logger.handlers:
# 如果根 logger 没有 handlers,尝试配置日志系统
try:
import douyin_logging
douyin_logging.configure_logging()
except Exception:
pass
if not hasattr(self, "_std_logger") or self._std_logger is None:
try:
from unified_logger import get_unified_logger
self._std_logger = get_unified_logger("douyin.fudai")
except ImportError:
try:
import douyin_logger
self._std_logger = douyin_logger.get_logger("douyin")
except Exception:
# 如果都失败了,使用根 logger
self._std_logger = logging.getLogger("douyin.fudai")
# 使用根 logger 确保日志能写入文件(子 logger 会传播到根 logger)
root_logger = logging.getLogger()
if root_logger.handlers:
# 如果根 logger 有 handlers,使用根 logger 写入(确保能写入文件)
# 构建标准 logging 消息(包含调用者信息)
std_msg_parts = [f"[{tag}]"]
if caller_info:
std_msg_parts.append(f"[调用:{caller_info}]")
if msg:
# 对消息进行敏感信息脱敏
try:
from unified_logger import SensitiveDataMasker
masked_msg = SensitiveDataMasker.mask_all(str(msg))
std_msg_parts.append(masked_msg)
except ImportError:
std_msg_parts.append(str(msg))
# 对字段进行敏感信息脱敏
masked_fields = {}
try:
from unified_logger import SensitiveDataMasker
masked_fields = SensitiveDataMasker.mask_dict(fields)
except ImportError:
masked_fields = fields
for k, v in masked_fields.items():
if k in (
"tag",
"msg",
"level",
"exc_info",
"_show_caller",
"_caller",
):
continue
if v is not None:
std_msg_parts.append(f"{k}={v}")
log_message = " ".join(std_msg_parts)
# 检查是否有异常信息
exc_info = fields.get("exc_info")
if exc_info is None:
if sys.exc_info()[0] is not None:
exc_info = sys.exc_info()
# 记录到根 logger(确保能写入文件)
level = getattr(logging, log_level, logging.INFO)
if exc_info:
root_logger.log(
level,
log_message,
exc_info=exc_info,
extra={"caller": caller_info},
)
else:
root_logger.log(level, log_message, extra={"caller": caller_info})
elif hasattr(self, "_std_logger") and self._std_logger:
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
# 构建标准 logging 消息(包含调用者信息)
std_msg_parts = [f"[{tag}]"]
if caller_info:
std_msg_parts.append(f"[调用:{caller_info}]")
if msg:
# 对消息进行敏感信息脱敏
try:
from unified_logger import SensitiveDataMasker
masked_msg = SensitiveDataMasker.mask_all(str(msg))
std_msg_parts.append(masked_msg)
except ImportError:
std_msg_parts.append(str(msg))
# 对字段进行敏感信息脱敏
masked_fields = {}
try:
from unified_logger import SensitiveDataMasker
masked_fields = SensitiveDataMasker.mask_dict(fields)
except ImportError:
masked_fields = fields
for k, v in masked_fields.items():
if k in (
"tag",
"msg",
"level",
"exc_info",
"_show_caller",
"_caller",
):
continue
if v is not None:
std_msg_parts.append(f"{k}={v}")
log_message = " ".join(std_msg_parts)
# 检查是否有异常信息
exc_info = fields.get("exc_info")
if exc_info is None:
if sys.exc_info()[0] is not None:
exc_info = sys.exc_info()
# 记录到标准 logger(使用 extra 参数传递调用者信息,让 formatter 使用)
level = getattr(logging, log_level, logging.INFO)
if exc_info:
self._std_logger.log(
level,
log_message,
exc_info=exc_info,
extra={"caller": caller_info},
)
else:
self._std_logger.log(
level, log_message, extra={"caller": caller_info}
)
except Exception as e:
# 如果标准 logging 写入失败,尝试使用根 logger 写入(作为备用)
try:
import logging
root_logger = logging.getLogger()
level = getattr(logging, log_level, logging.INFO)
# 构建简单的日志消息
simple_msg = f"[{tag}] {msg}" if msg else f"[{tag}]"
# 直接使用根 logger,它会自动处理子 logger 的传播
root_logger.log(level, simple_msg)
except Exception:
# 如果所有日志写入都失败,至少确保 stdout 输出(已在上面完成)
pass
# 如果有异常堆栈,也输出到 stdout
exc_info = fields.get("exc_info")
if exc_info is None:
if sys.exc_info()[0] is not None:
exc_info = sys.exc_info()
if exc_info:
try:
import traceback
# exc_info 应该是 (type, value, traceback) 元组
if isinstance(exc_info, tuple) and len(exc_info) == 3:
exc_type, exc_value, exc_traceback = exc_info
# 确保 exc_value 是 BaseException 实例
if isinstance(exc_value, BaseException):
tb_str = traceback.format_exception(
exc_type, exc_value, exc_traceback
)
else:
# 如果不是异常实例,创建一个包装异常
try:
# 尝试使用原始值
tb_str = traceback.format_exception(
exc_type,
(
BaseException(str(exc_value))
if exc_value
else BaseException("Unknown error")
),
exc_traceback,
)
except Exception:
# 如果还是失败,只输出异常信息
print(
f" 异常类型: {exc_type}, 异常值: {exc_value}",
flush=True,
)
tb_str = []
for line in tb_str:
print(f" {line.rstrip()}", flush=True)
else:
# 如果不是标准格式,尝试直接格式化
try:
tb_str = traceback.format_exception(*exc_info)
for line in tb_str:
print(f" {line.rstrip()}", flush=True)
except Exception:
# 如果格式化失败,只输出异常信息
print(f" 异常信息: {exc_info}", flush=True)
except Exception:
pass
# 供像素/检测模块记录子步骤耗时使用
def _log_step_time(
self, step_name: str, start_time: float, extra_info: dict | None = None
) -> None:
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。"""
try:
elapsed = time.time() - float(start_time or 0.0)
except Exception:
elapsed = 0.0
fields: dict[str, Any] = {"seconds": elapsed}
if extra_info:
for k, v in extra_info.items():
fields[str(k)] = v
try:
self._log_kv("步骤耗时", step_name, **fields)
except Exception:
pass
# ========== 弹窗 / 人机校验 ==========
def _check_coupon_popup(self) -> bool:
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的“看门狗”中使用)。"""
return douyin_popups.check_coupon_popup(self)
def _check_shopping_redpacket_popup(self) -> bool:
"""购物红包中央弹窗。"""
return douyin_popups.check_shopping_redpacket_popup(self)
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
def run_once_basic(self) -> None:
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。"""
# 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:
# 检查是否有预约需要立即处理
import douyin_reservation_logic
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 e:
self._log_kv("参与", "检查高价值预约时出错", error=str(e))
if should_preempt:
# 被高价值预约抢占,继续执行后续逻辑处理预约
pass
else:
# 没有预约抢占,继续等待开奖
# 直接用预计开奖时间减去当前时间计算剩余秒数
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)
# 开奖时间 + 5秒缓冲后开始检测开奖结果
check_start_ts = future_ts + 5.0
# 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭)
timeout_ts = future_ts + 10.0
if current_ts >= timeout_ts:
# 超过超时时间,清除等待标志,避免卡死
self._waiting_for_lottery_result = False
self._log_kv(
"参与",
"等待开奖超时(超过开奖时间10秒),清除等待标志,继续执行其他操作",
超时秒数=int(current_ts - future_ts),
)
# 继续执行后续逻辑,不返回
elif current_ts >= check_start_ts:
# 已经超过开奖时间+缓冲时间,开始检测开奖结果
# 直接OCR识别开奖结果按钮区域,不需要阶段诊断
self.operation.get_screenshot(self.device_id)
result = self._check_lottery_result_by_ocr()
if result:
# 检测到开奖结果,清除等待标志,处理结果
self._waiting_for_lottery_result = False
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
# 处理开奖结果(根据OCR结果执行不同操作)
self._handle_lottery_result_by_ocr(result)
return
else:
# 还未开奖,继续等待(每2秒检测一次)
self._log_kv(
"参与",
"等待开奖中,OCR未识别到结果",
剩余秒数=int(remain_seconds),
)
self.operation.delay(2.0)
return # 返回,不执行其他操作
else:
# 还未到开奖时间,短暂等待后继续检测
wait_s = min(2.0, remain_seconds)
self._log_kv("参与", "等待开奖中", 剩余秒数=int(remain_seconds))
self.operation.delay(wait_s)
return # 返回,不执行其他操作
except Exception as e:
self._log_kv("参与", "等待开奖检测时出错", error=str(e))
# 出错时清除等待标志,避免卡死
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(
"超时",
f"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
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() 方法中
return
except Exception as e:
try:
self._log_kv("超时", "检查30分钟超时时出错", error=str(e))
except Exception:
pass
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
try:
if getattr(self, "high_value_fudai_enabled", False) and self.reservations:
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
from datetime import datetime
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 e:
try:
self._log_kv(
"预约",
"写入预约队列状态文件失败",
error=str(e),
error_type=type(e).__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)
# 已回退到最早开奖的预约直播间,本轮结束
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
if needswitch_cfg:
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,
)
)
# 同步回写 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:
# 已触发预约回退,本轮直接结束,等待下一轮在目标直播间执行详情逻辑
return
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()
return
# 1. 截图 + 阶段诊断
ok = self.operation.get_screenshot(self.device_id)
if not ok:
self._log_kv("截图", "获取截图失败", ok=0)
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()
# 简洁输出阶段诊断结果(不额外添加分隔符,避免日志噪音)
self._log_kv("截图", "截图+阶段诊断", stage=stage, seen=seen)
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
try:
top_pkg = ""
try:
top_pkg = self.operation.get_top_package(self.device_id) or ""
except Exception:
top_pkg = ""
if top_pkg and (
"aweme" not in top_pkg
and "douyin" not in top_pkg
and "com.ss.android.ugc" not in top_pkg
):
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
# 重新开始下一轮判断
return
except Exception as e:
try:
self._log_kv("自救", "恢复失败", error=str(e))
except Exception:
pass
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))
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))
return
elif stage == "FANSCLUB_JOIN":
# 粉丝团加入阶段:点击加入粉丝团按钮
self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理")
try:
# 点击加入粉丝团按钮(基于截图优化坐标)
# OCR区域:(200, 1940, 880, 2140),尺寸680x200,按钮上部66%是红色区域(文字所在)
# 红色区域高度约132像素,中心Y = 1940 + 132/2 = 2006
# 点击位置:X=540(区域中心),Y=2006(红色区域中心,基于截图分析)
fansclub_x = int(540 * self.resolution_ratio_x // 1080)
fansclub_y = int(2006 * self.resolution_ratio_y // 2400)
# 第一次点击
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv(
"粉丝团处理",
"第一次点击加入粉丝团按钮(基于截图优化坐标)",
x=fansclub_x,
y=fansclub_y,
base_x=540,
base_y=2006,
region="(200,1940)-(880,2140)",
red_area_center_y=2006,
)
self.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击(连续点击两次确保成功)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv(
"粉丝团处理",
"第二次点击加入粉丝团按钮(基于截图优化坐标)",
x=fansclub_x,
y=fansclub_y,
base_x=540,
base_y=2006,
)
self.operation.delay(2.0)
# 如果启用了自动加入,等待页面加载后再次点击(如果需要)
if getattr(self, "auto_join_fansclub", False):
self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载")
self.operation.delay(1.0)
# 再次诊断阶段,看是否还在粉丝团加入页
try:
stage_after, seen_after = (
self._diagnose_stage_from_current_screen()
)
if stage_after == "FANSCLUB_JOIN":
# 仍在粉丝团加入页,再次点击(连续点击两次)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv("粉丝团处理", "仍在粉丝团加入页,再次第一次点击")
self.operation.delay(0.5)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self._log_kv("粉丝团处理", "仍在粉丝团加入页,再次第二次点击")
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 e:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
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 e:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
# 延迟后返回,让主循环继续处理
self.operation.delay(0.5)
except Exception as e:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(e))
# 如果失败,根据配置决定是否切换直播间
fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay")
if fansclub_fail_action == "switch":
self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间")
self.swipe_up_to_next_live()
return
elif stage == "FUDai_DETAIL":
# 已经在详情页:直接读详情并决定是否参与
self._handle_in_fudai_detail()
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
# 在直播间:寻找福袋图标并尝试点开
self._handle_live_room_has_or_not_fudai()
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
# 处理推荐/关注/直播列表页:回到直播间或切换
if stage == "RECOMMEND_PAGE":
# 识别到推荐页面:点击关注标签,然后点击进入直播间
self._log_kv(
"流程",
"检测到推荐页面,点击关注标签并进入直播间",
stage=stage,
seen=seen,
)
try:
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
self._log_kv("流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
# 点击进入直播间的位置 (103, 385),连点两次
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
enter_live_y = int(385 * 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
return
elif stage in ("LIVE_CLOSED",):
# 直播结束:下滑/切下一个
self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
self.swipe_up_to_next_live()
else:
# 未识别出特殊阶段:尽量保持原地,交给上层循环
self._log_kv("阶段", "未匹配到特定阶段", stage=stage)
def _check_lottery_result_by_ocr(self) -> Optional[str]:
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。
返回:
"我知道了" - 识别到"我知道了"按钮
"立即领取奖品" - 识别到"立即领取奖品"按钮
None - 未识别到相关文本
"""
try:
# OCR区域:(175, 1267) 到 (890, 1377)
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
self.cut_pic(175, 1267, 890, 1377, "", "开奖结果按钮", 0)
# OCR识别
ocr_text = str(self.operation.analyse_pic_word("开奖结果按钮", 0) or "")
self._log_kv("开奖结果", "OCR识别结果", text=ocr_text)
# 检查识别到的文本
if "我知道了" in ocr_text:
return "我知道了"
elif (
"立即领取奖品" in ocr_text
or "领取奖品" in ocr_text
or "立即领取" in ocr_text
):
return "立即领取奖品"
else:
# 尝试模式1识别
ocr_text_1 = str(
self.operation.analyse_pic_word("开奖结果按钮", 1) or ""
)
if "我知道了" in ocr_text_1:
return "我知道了"
elif (
"立即领取奖品" in ocr_text_1
or "领取奖品" in ocr_text_1
or "立即领取" in ocr_text_1
):
return "立即领取奖品"
return None
except Exception as e:
self._log_kv("开奖结果", "OCR识别异常", error=str(e))
return None
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
"""根据OCR识别结果处理开奖结果。
参数:
result_type: "我知道了" 或 "立即领取奖品"
"""
try:
if result_type == "我知道了":
# 识别到"我知道了",点击按钮,切换下一个直播间
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1267+1377)/2=1322
btn_x = int(532 * rx // 1080)
btn_y = int(1322 * ry // 2400)
self.operation.click(self.device_id, btn_x, btn_y)
self._log_kv("开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y)
self.operation.delay(0.5)
# 切换下一个直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋")
self.swipe_up_to_next_live()
else:
self._log_kv(
"开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间"
)
elif result_type == "立即领取奖品":
# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间
try:
import os
import shutil
from datetime import datetime
# 确保有最新截图
self.operation.get_screenshot(self.device_id)
base_dir = os.path.dirname(__file__)
pic_dir = os.path.join(base_dir, "pic")
src = os.path.join(pic_dir, "screenshot.png")
if os.path.exists(src):
# 创建单独的文件夹保存"立即领取奖品"的截图
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
os.makedirs(prize_dir, exist_ok=True)
# 保存截图,文件名包含时间戳
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
shutil.copy(src, dst)
self._log_kv("开奖结果", "已保存立即领取奖品截图", path=dst)
except Exception as e:
self._log_kv("开奖结果", "保存截图失败", error=str(e))
# 点击返回键
self.operation.click_back(self.device_id)
self._log_kv("开奖结果", "点击返回键关闭开奖结果")
self.operation.delay(0.5)
# 切换下一个直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋")
self.swipe_up_to_next_live()
else:
self._log_kv(
"开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间"
)
except Exception as e:
self._log_kv(
"开奖结果", "处理开奖结果失败", error=str(e), result_type=result_type
)
# 失败时尝试按返回键并切换
try:
self.operation.click_back(self.device_id)
self.operation.delay(0.5)
self.swipe_up_to_next_live()
except Exception:
pass
def _shot_and_diagnose(
self, tag: str, msg: str, device_id: str, diagnose: bool = True
) -> None:
"""截图并执行阶段诊断(兼容旧版调用方式)。
Args:
tag: 日志标签
msg: 日志消息
device_id: 设备ID
diagnose: 是否执行阶段诊断(默认True)
"""
try:
# 截图
ok = self.operation.get_screenshot(device_id)
if not ok:
self._log_kv(tag, f"{msg} - 获取截图失败", ok=0)
return
# 如果启用诊断,执行阶段诊断
if diagnose:
stage, seen = self._diagnose_stage_from_current_screen()
self._last_diag_stage = stage
self._last_diag_seen = seen
self._last_diag_ts = time.time()
# 使用位置参数调用,避免与关键字参数冲突
self._log_kv(tag, msg, **{"stage": stage, "seen": seen})
else:
self._log_kv(tag, msg)
except Exception as e:
# 避免异常影响主流程
try:
self._log_kv(tag, f"{msg} - 异常: {type(e).__name__}")
except Exception:
pass
# ========== 基础动作封装 ==========
def swipe_up_to_next_live(self) -> None:
"""上滑切换直播间(简单版封装)。"""
douyin_swipe_ops.swipe_up_switch_live(self)
# 记录直播间位置:上滑 +1
try:
self.room_pos += 1
except Exception:
self.room_pos = 0
# 记录滑动次数(用于滑动次数重置功能)
try:
if not hasattr(self, "_swipe_times"):
self._swipe_times = 0
self._swipe_times += 1
except Exception:
pass
# 检查是否需要重置(滑动次数达到阈值)
try:
self._maybe_reset_after_swipes()
except Exception:
pass
def _return_to_recommend_and_reenter_live(self) -> None:
"""返回推荐页面并重新进入直播间。
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
"""
self._log_kv("超时", "开始返回推荐页面")
# 多次点击返回键,直到到达推荐页面
max_back_clicks = self.MAX_BACK_CLICKS_TO_RECOMMEND
for i in range(max_back_clicks):
try:
# 截图并诊断当前阶段
ok = self.operation.get_screenshot(self.device_id)
if not ok:
self._log_kv("超时", f"获取截图失败 ({i+1}/{max_back_clicks})")
# 即使截图失败,也尝试点击返回键
self.operation.click_back(self.device_id)
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
continue
# 诊断当前阶段
stage, seen = self._diagnose_stage_from_current_screen()
# 如果已经在推荐页面,跳出循环
if stage == "RECOMMEND_PAGE":
self._log_kv("超时", f"已到达推荐页面 ({i+1}次返回键)")
break
# 点击返回键
self.operation.click_back(self.device_id)
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
if i == max_back_clicks - 1:
self._log_kv(
"超时", f"已点击{max_back_clicks}次返回键,可能未到达推荐页面"
)
except Exception as e:
try:
self._log_kv(
"超时",
f"返回推荐页面时出错 ({i+1}/{max_back_clicks})",
error=str(e),
)
except Exception:
pass
# 继续尝试点击返回键
try:
self.operation.click_back(self.device_id)
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
except Exception as e:
# 记录异常但继续执行
try:
self._log_kv(
"超时",
"点击返回键失败但继续",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
# 等待页面稳定
self.operation.delay(self.PAGE_STABLE_DELAY)
# 再次截图确认当前阶段
try:
ok = self.operation.get_screenshot(self.device_id)
if ok:
stage, seen = self._diagnose_stage_from_current_screen()
self._log_kv("超时", "确认当前阶段", stage=stage, seen=seen)
except Exception as e:
# 记录异常但继续执行(阶段诊断失败不影响主流程)
try:
self._log_kv(
"超时",
"确认阶段时出错但继续",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
# 点击关注标签并进入直播间(复用现有逻辑)
try:
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
self._log_kv("超时", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
# 点击进入直播间的位置 (103, 385),连点两次
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
enter_live_y = int(385 * 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)
self._log_kv("超时", "已重新进入直播间")
# 重置超时相关时间戳(在成功重新进入直播间后重置,避免立即再次触发)
try:
self._last_successful_attend_ts = time.time()
self._run_start_ts = time.time()
except Exception as e:
try:
self._log_kv(
"超时",
"重置时间戳时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
except Exception as e:
# 记录异常但继续执行
try:
self._log_kv(
"超时",
"重新进入直播间时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
# 如果出错,尝试回退
try:
self.operation.click_back(self.device_id)
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
except Exception as e2:
try:
self._log_kv(
"超时",
"回退操作失败",
error=str(e2),
error_type=type(e2).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
def swipe_down_back_from_live(self) -> None:
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
try:
douyin_swipe_ops.swipe_down_back_live(self)
except Exception:
# 若子模块未实现,则退化为点击返回键
try:
self.operation.click_back(self.device_id)
except Exception:
pass
# 记录直播间位置:下滑/回退 -1
try:
self.room_pos -= 1
except Exception:
self.room_pos = 0
def _maybe_reset_after_swipes(self) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
返回:
重置后的滑动次数(通常为0)
"""
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if not needswitch:
return getattr(self, "_swipe_times", 0)
if not bool(getattr(self, "reset_after_swipes_enabled", False)):
return getattr(self, "_swipe_times", 0)
try:
swipe_times = int(getattr(self, "_swipe_times", 0) or 0)
except Exception:
swipe_times = 0
threshold = max(1, int(self.reset_after_swipes or 0))
if swipe_times < threshold:
return swipe_times
try:
self._log_kv(
"流程",
"已切换直播间{}次,达到阈值{}:向上回退到第一个直播间".format(
swipe_times, threshold
),
swipe_times=swipe_times,
threshold=threshold,
)
except Exception:
pass
# 回退次数按当前已切换次数来(更符合"回到本轮第一个直播间"的语义)
back_times = int(swipe_times)
# 防止无限循环:最大回退次数限制为100
if back_times > 100:
back_times = 100
if back_times <= 0:
return 0
# 向上回退:从上往下滑动(与上划切换相反方向)
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
for i in range(back_times):
try:
# 向上回退:从上往下滑动(start_y < end_y)
start_x = 760 * rx // 1080
start_y = 800 * ry // 2400 # 上方起始位置
end_x = 760 * rx // 1080
end_y = 1600 * ry // 2400 # 下方结束位置
self.operation.swipe(
self.device_id, start_x, start_y, end_x, end_y, 200
)
try:
self._log_kv("流程", "回退直播间 {}/{}".format(i + 1, back_times))
except Exception:
pass
self.operation.delay(2)
except Exception:
pass
# 回到第一个后,计数归零
self.operation.delay(3)
try:
self._swipe_times = 0
self.room_pos = 0
except Exception:
pass
return 0
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
说明:
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
"""
try:
target_pos = int(item.get("pos_seen") or 0)
except Exception:
target_pos = 0
try:
cur_pos = int(getattr(self, "room_pos", 0) or 0)
except Exception:
cur_pos = 0
# 计算需要切换的次数和方向
# room_pos 越大表示越靠下,越小表示越靠上
# 如果 target_pos < cur_pos,说明目标在上方,需要向上回退(使用 swipe_down_back_from_live)
# 如果 target_pos > cur_pos,说明目标在下方,需要向下切换(使用 swipe_up_to_next_live)
pos_diff = target_pos - cur_pos
try:
max_back = int(getattr(self, "high_value_fudai_max_swipe_back", 60) or 60)
except Exception:
max_back = 60
# 防止无限循环:最大回退次数限制为100
if max_back > 100:
max_back = 100
if max_back < 0:
max_back = 0
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 计算切换方向和次数",
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
)
except Exception:
pass
if pos_diff == 0:
# 已在目标位置,但仍需校验
pass
elif pos_diff < 0:
# 目标在上方,需要向上回退
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 向上回退",
back_times=back_times,
)
except Exception:
pass
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
for _ in range(back_times):
self.swipe_down_back_from_live()
try:
self.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
else:
# 目标在下方,需要向下切换
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 向下切换",
forward_times=forward_times,
)
except Exception:
pass
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
for _ in range(forward_times):
self.swipe_up_to_next_live()
try:
self.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
# 如果启用了回退校验,进行详细校验
try:
if bool(getattr(self, "reservation_back_verify_enabled", True)):
import douyin_reservation_verify
is_valid, detail_tuple = (
douyin_reservation_verify.validate_back_to_reservation(
self, item, quick=False
)
)
if not is_valid:
try:
self._log_kv(
"预约", "[预约] _seek_reservation_room 回退校验失败"
)
except Exception:
pass
return False
# 校验通过,保存详情供后续使用
if detail_tuple:
try:
self._forced_reservation_detail = detail_tuple # type: ignore[attr-defined]
self._forced_reservation_fudai_x = None # type: ignore[attr-defined]
except Exception:
pass
except Exception as e:
try:
self._log_kv(
"预约", "[预约] _seek_reservation_room 回退校验异常", error=str(e)
)
except Exception:
pass
# 校验异常时,如果配置要求必须校验,则返回失败
if bool(getattr(self, "reservation_back_verify_enabled", True)):
return False
return True
# ========== 福袋相关 ==========
def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
# 检查是否是第二次打开福袋详情(已经读取过详情)
# 如果是第二次打开,只需要验证参与按钮,不需要重新识别内容、倒计时、价值
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,
)
else:
# 只检测参与按钮,不重新识别内容
try:
self.operation.get_screenshot(self.device_id)
self.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
# OCR识别参与按钮
attend_button_text = str(self.operation.analyse_pic_word("参与按钮", 0) or "")
if not attend_button_text or not any(
k in attend_button_text
for k in ("参与成功", "还需看播", "评论", "参与抽奖", "开始观看", "参与")
):
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 1) or ""
)
self._log_kv("参与", "第二次打开:只验证参与按钮", text=attend_button_text)
# 如果已参与,设置等待开奖标志并返回,不需要继续处理
if "参与成功" in attend_button_text or "还需看播" in attend_button_text or "等待开奖" in attend_button_text:
self._log_kv("参与", "第二次打开:已参与,无需再次点击", result="已参与")
# 从第一次保存的详情数据中获取倒计时信息,设置等待开奖标志
try:
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail and 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:
current_time = time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
# 提前13秒,修正倒计时误差
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = future_ts - 13.0
self._log_kv(
"参与",
"第二次打开:已参与,设置等待开奖标志",
remain_seconds=remain_seconds,
future_ts=int(future_ts),
)
else:
self._log_kv("参与", "第二次打开:已参与,但倒计时已过期,不设置等待标志")
else:
self._log_kv("参与", "第二次打开:已参与,但无法获取倒计时信息")
else:
self._log_kv("参与", "第二次打开:已参与,但详情数据中无倒计时信息")
else:
self._log_kv("参与", "第二次打开:已参与,但未找到保存的详情数据")
except Exception as e:
self._log_kv("参与", "第二次打开:设置等待开奖标志时出错", error=str(e))
# 关闭详情页
self.click(500, 470)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
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
return
except Exception:
pass
# 执行筛选检查(不执行参与操作,只检查是否符合筛选条件)
try:
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(self, detail)
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
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
return
elif last_status == "watch_task":
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到'观看X分钟'任务,已在OCR阶段跳过,无需后续处理",
)
except Exception:
pass
return
elif last_status == "validation_failed":
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理",
)
except Exception:
pass
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
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
return
else:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
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
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
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
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),
)
# 关闭详情页,返回直播间等待开奖
# 检查 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 决定"继续找/切换/养号"."""
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
# 如果已验证过详情页但任务数为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()
return
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,
)
return
# 成功打开详情:调用同一套详情处理逻辑
self._handle_in_fudai_detail()