Files
douyin_guaji-main/douyin_fudai.py
T
Your Name 1a63852bde feat: Add dependency management tools and enhance logging features
- Introduced `check_dependencies.py` to automate dependency checks and provide installation guidance.
- Created `install_dependencies.py` for automatic installation of missing dependencies.
- Updated `config.json` to include new logging settings for log retention and date-based log file management.
- Added `DEPENDENCY_GUIDE.md` and `DEPENDENCY_FIXES_REPORT.md` for comprehensive documentation on dependency management and fixes.
- Enhanced logging functionality in `douyin_logging.py` to support date-based log files and automatic cleanup of old logs.
2025-12-21 22:40:56 +08:00

1797 lines
73 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
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:
"""福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。"""
def __init__(self) -> None:
# 设备与分辨率
self.device_id: str = "XXXXXXXXX"
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]
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
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
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.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
# fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用
self.fudai_find_max_attempts: int = 10
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
# 福袋模板匹配阈值(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.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
)
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_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
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
# —— 高价值福袋 / 预约配置加载 ——
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.reservation_back_verify_enabled = bool(
config.get(
"reservation_back_verify_enabled",
self.reservation_back_verify_enabled,
)
)
except Exception:
self.reservation_back_verify_enabled = True
# 滑动次数重置配置
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 = False
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
# ========== 兼容旧入口:主循环 ==========
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:
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
self._log_kv(
"启动",
"fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)",
分辨率=f"{self.resolution_ratio_x}x{self.resolution_ratio_y}",
needswitch=int(bool(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)
else:
# 无限循环模式(wait_minutes <= 0)
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
while True:
try:
self.run_once_basic()
except KeyboardInterrupt:
# 允许 Ctrl+C 退出
self._log_kv("循环", "收到中断信号,退出循环")
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]:
"""封装到子模块的阶段诊断入口。"""
return douyin_stage.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 基准)。"""
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) -> dict:
"""读取像素阶段状态(用于阶段诊断)。"""
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
)
return douyin_pixel.read_pixel_stage_state_from_screenshot(
pic_path,
resolution_ratio_x,
resolution_ratio_y,
y_pianyi,
lucky_threshold,
)
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)
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)
cv2.imwrite(xin_roi_path, roi)
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)
roi_img = cv2.imread(roi_path, cv2.IMREAD_GRAYSCALE)
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(
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)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
# 记录最佳匹配分数和模板名称
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
# 同时输出到标准 logging(如果已配置,可选)
try:
if not hasattr(self, "_std_logger") or self._std_logger is None:
try:
import douyin_logger
self._std_logger = douyin_logger.get_logger("douyin")
except Exception:
pass
if hasattr(self, "_std_logger") and self._std_logger:
# 构建标准 logging 消息(包含调用者信息)
std_msg_parts = [f"[{tag}]"]
if caller_info:
std_msg_parts.append(f"[调用:{caller_info}]")
if msg:
std_msg_parts.append(str(msg))
for k, v in 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:
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. 若启用高价值预约:先处理"是否需要回退到预约直播间"
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)
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
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
# 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 == "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(2.0)
# 点击进入直播间的位置 (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(0.6)
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(2.0)
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 in ("LIVE_CLOSED",):
# 直播结束:下滑/切下一个
self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
self.swipe_up_to_next_live()
else:
# 未识别出特殊阶段:尽量保持原地,交给上层循环
self._log_kv("阶段", "未匹配到特定阶段", stage=stage)
# ========== 基础动作封装 ==========
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 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)
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_x = 760 * rx // 1080
start_y = 1600 * ry // 2400
end_x = 760 * rx // 1080
end_y = 800 * 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
back_times = max(0, cur_pos - target_pos)
try:
max_back = int(getattr(self, "high_value_fudai_max_swipe_back", 60) or 60)
except Exception:
max_back = 60
if max_back > 0 and back_times > max_back:
back_times = max_back
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 计算回退次数",
current_room_pos=cur_pos,
target_pos=target_pos,
back_times=back_times,
)
except Exception:
pass
if back_times <= 0:
# 认为当前已在目标附近,但仍需校验
pass
else:
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)
# 如果启用了回退校验,进行详细校验
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:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
# 这里不做预约,只根据当前详情是否满足门槛决定参与与否
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,
)
# 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理
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 == "validation_failed":
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理",
)
except Exception:
pass
return
except Exception:
pass
# 额外验证:使用验证函数检查数据合理性
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
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
douyin_fudai_core.basic_join_decision(self, detail)
def _handle_live_room_has_or_not_fudai(self) -> None:
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定“继续找/切换/养号”."""
room_pos_ref: List[int] = [0]
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
if not opened:
# 无福袋,交给 flow_control 的“无福袋处理”逻辑(暂时只做简单滑动/等待)
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=True,
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()