Files
douyin_guaji-main/douyin_fudai.py
T
Your Name b0bd7c72c8 refactor: Remove outdated batch script and enhance configuration settings
- Deleted the obsolete batch script for launching the Web GUI.
- Updated `config.json` to increase `webgui_log_capacity` to 2000 and set `reset_after_swipes` to 15.
- Enabled `reset_after_swipes_enabled` for improved functionality.
- Added a new field `reservation_back_swipe_delay` to enhance reservation handling.
- Improved OCR caching and detection mechanisms in `douyin_fudai.py` for better performance.
- Enhanced logging functionality in `web_gui.py` to handle ANSI escape codes and improve error handling.
2025-12-16 16:49:29 +08:00

5938 lines
289 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.
import os
import sys
import time
from PIL import Image
from datetime import datetime
from Underlying_Operations import underlying_operations
import json
import re
import shutil
import random
import hashlib
import difflib
"""
V3.3.1 版本
"""
def normalize_countdown_text(text: str) -> str:
if not text:
return ''
t = re.sub(r"\s+", "", str(text))
t = t.replace(':', ':')
# 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字)
t = t.translate(str.maketrans({
'O': '0', 'o': '0', 'Q': '0', 'D': '0',
'I': '1', 'l': '1', '|': '1', '!': '1',
'S': '5', 's': '5',
'B': '8',
'G': '6',
'Z': '2',
}))
# 中文:x分y秒 / y秒
m = re.search(r"(\d{1,2})分(\d{1,2})秒", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
if ss >= 60:
mm += ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
m = re.search(r"(\d{1,3})秒", t)
if m:
ss = int(m.group(1))
mm = ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
# 标准样式:11:37后开奖 / 11:37后开奖
m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
# 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释
if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900:
mm, ss = ss, mm
return f"{mm:02d}:{ss:02d}后开奖"
# 识别错序:54后开奖04
m = re.search(r"(\d{1,2})后开奖(\d{2})", t)
if m:
mm = int(m.group(1))
ss = int(m.group(2))
if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900:
mm, ss = ss, mm
return f"{mm:02d}:{ss:02d}后开奖"
# 纯数字 1137 / 5404
digits = ''.join(ch for ch in t if ch.isdigit())
if len(digits) == 4:
a = int(digits[:2])
b = int(digits[2:])
# 生成两种解释:mm:ss 以及交换后的 mm:ss
mm1, ss1 = a, b
mm2, ss2 = b, a
total1 = mm1 * 60 + ss1
total2 = mm2 * 60 + ss2
# 默认相信“从左到右”的顺序:前两位=分,后两位=秒。
# 只有在明显异常(>15分钟)或秒数不合法时才交换。
if ss1 >= 60 and ss2 < 60:
mm, ss = mm2, ss2
elif ss2 >= 60 and ss1 < 60:
mm, ss = mm1, ss1
elif total1 > 900 and total2 <= 900:
mm, ss = mm2, ss2
elif total2 > 900 and total1 <= 900:
mm, ss = mm1, ss1
else:
mm, ss = mm1, ss1
return f"{mm:02d}:{ss:02d}"
# 3 位数字:934 => 09:34
if len(digits) == 3:
mm = int(digits[0])
ss = int(digits[1:])
if ss >= 60:
# 尝试 15:09(OCR 丢 0)
mm2 = int(digits[:2])
ss2 = int(digits[2])
if ss2 < 60:
return f"{mm2:02d}:{ss2:02d}"
mm += ss // 60
ss = ss % 60
return f"{mm:02d}:{ss:02d}"
# 2 位数字:31 => 00:31(更符合临近开奖)
if len(digits) == 2:
return f"00:{int(digits):02d}"
return t
def extract_prize_value_yuan(text: str) -> float:
if not text:
return 0.0
t = re.sub(r"\s+", "", str(text))
# 先去掉倒计时类数字,避免把 00:31 解析成 31 元
t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t)
# 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元
currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t)
yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t)
tagged = currency_matches + yuan_matches
if tagged:
vals = []
for n in tagged:
try:
vals.append(float(n))
except ValueError:
pass
return max(vals) if vals else 0.0
# 去掉常见干扰:份数/参与人数
t = re.sub(r"共\d+份", "", t)
t = re.sub(r"\d+人已参与", "", t)
# 退化:抓小数
decimals = re.findall(r"\d+\.\d+", t)
if decimals:
vals = []
for n in decimals:
try:
vals.append(float(n))
except ValueError:
pass
return max(vals) if vals else 0.0
# 再退化:抓整数
ints = re.findall(r"\d+", t)
if ints:
vals = []
for n in ints:
try:
v = int(n)
except ValueError:
continue
if 1 <= v <= 99999:
vals.append(float(v))
return max(vals) if vals else 0.0
return 0.0
class Tee(object):
"""重写print的函数"""
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
class fudai_analyse:
"""福袋抽奖相关操作类"""
def __init__(self):
self.device_id = 'XXXXXXXXX'
self.y_pianyi = 0 # 应用于不同型号手机,图标相对屏幕的高度位置有偏差
self.resolution_ratio_x = 1080
self.resolution_ratio_y = 2400
# OCR结果缓存:避免短时间内重复识别相同区域
self._ocr_cache: dict[str, tuple[float, str]] = {} # key: (picname, change_color), value: (timestamp, result)
self._ocr_cache_ttl: float = 2.0 # 缓存有效期(秒)
# 检测结果缓存
self._detection_cache: dict[str, tuple[float, object]] = {} # key: method_name, value: (timestamp, result)
self._detection_cache_ttl: float = 1.0 # 检测缓存有效期(秒)
# 预约队列状态文件(用于 Web GUI 展示;子进程写入,Web GUI 进程读取)
self._reservations_state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json")
# 让终端输出更“整行、实时”(避免看起来空白/零散)
try:
sys.stdout.reconfigure(encoding='utf-8', line_buffering=True)
except Exception:
pass
try:
sys.stderr.reconfigure(encoding='utf-8', line_buffering=True)
except Exception:
pass
# 可通过环境变量关闭 Tee 重定向(例如 Web GUI 统一收集日志时)
if not str(os.environ.get("NO_TEE_STDOUT", "")).strip():
# 统一日志文件(默认 logs/unified.log),便于长期追踪与 grep
base_dir = os.path.dirname(__file__)
cfg = {}
try:
cfg_path = os.path.join(base_dir, "config.json")
if os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f) if f.readable() else {}
except Exception:
cfg = {}
enabled = True
try:
enabled = bool(cfg.get("log_unified_enabled", True))
except Exception:
enabled = True
if enabled:
rel = str(cfg.get("log_unified_path") or "logs/unified.log")
log_path = rel if os.path.isabs(rel) else os.path.join(base_dir, rel)
try:
os.makedirs(os.path.dirname(log_path), exist_ok=True)
except Exception:
pass
# 使用 utf-8-sig:文件首次创建时写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码
log_file = open(log_path, 'a', encoding='utf-8-sig', errors='ignore')
else:
# 兼容:若禁用统一日志,则按旧逻辑写一个时间戳文件
timepic = datetime.now().strftime('%Y-%m-%d-%H-%M')
log_file = open(timepic + '.log', 'a', encoding='utf-8-sig', errors='ignore')
sys.stdout = Tee(sys.stdout, log_file)
sys.stderr = Tee(sys.stderr, log_file)
# 结构化日志:本次运行唯一 id + 递增序号(便于 Web GUI 里按 rid/seq 定位)
try:
self._run_id = datetime.now().strftime('%Y%m%d%H%M%S')
except Exception:
self._run_id = str(int(time.time()))
self._log_seq = 0
self.last_find_fudai_time = 0.0
self.last_refresh_zhibo_list_time = 0.0
# 进入直播间计时:用于统计“进入直播间后找到福袋图标耗时”
self._enter_live_ts = 0.0
self._enter_live_reason = ""
self._enter_live_fudai_logged = False
# 无福袋“看门狗”:超时后回到列表重进直播。用户要求先整体关闭,后续再调整。
self.no_fudai_watchdog_enabled = False
self.operation = underlying_operations()
self.config_path = "config.json"
self.contains_not_want = []
self.contains_want = []
self.min_prize_value_yuan = 0.0 # 小于该价值(元)则不参与,0 表示不启用
self.min_participants = 0 # 参与人数小于该值则不参与,0 表示不启用
self.max_participants = 0 # 参与人数大于该值则不参与,0 表示不启用
self.skip_if_countdown_lt_seconds = 15 # 倒计时小于该秒数则不参与(仅 needswitch=True 时生效)
# 切换直播间计数:当上划切换达到阈值后,在当前直播间页面下滑回退到第一个直播间
self.reset_after_swipes_enabled = False # 由 Web/CLI 显式开关
self.reset_after_swipes = 10 # 达到阈值次数后回退,需启用开关后生效
# 高价值福袋:预约参与(避免在倒计时很长时一直卡在直播间等待)
self.high_value_fudai_enabled = False
self.high_value_fudai_threshold_yuan = 1000.0
self.high_value_fudai_join_ahead_seconds = 120 # 开奖前 N 秒回到该直播间并参与
self.high_value_fudai_max_swipe_back = 60 # 为防止回滑过远导致异常,限制最多回退次数
self.high_value_fudai_max_reservations = 5 # 最多记录多少个高价值福袋预约
# 完成某个预约福袋后动作:stay=停留当前直播间;continue=继续执行抢福袋
self.high_value_fudai_after_action = "continue"
self.high_value_fudai_after_stay_seconds = 120
# 高价值直播间“回访”:曾经记录过高价值福袋的直播间,每隔一段时间回去看一眼是否出现新福袋。
# 优先级:预约参与(最高) > 回访(中) > 普通找福袋(低)
self.high_value_room_revisit_enabled = True
self.high_value_room_revisit_interval_seconds = 300 # 默认 5 分钟
self.high_value_room_revisit_watch_window_seconds = 900 # 默认仅在 15 分钟观察窗内回访
self.high_value_room_revisit_skip_if_reservation_within_seconds = 120 # 若离预约参与窗口过近则跳过回访
self.high_value_room_revisit_only_current_run = False # 若为 True,则仅回访本次运行记录的直播间
# 预约回退校验开关:用于在运行时决定是否做回退后详细校验(可通过 Run 面板控制)
self.reservation_back_verify_enabled = True
# 轮询策略:在预计开奖前多少秒开始积极轮询结果(默认 10 秒)
self.poll_before_open_seconds = 10
# 预约抢占最小价值:低于该价值的预约不抢占当前任务(元,默认0表示任何预约可抢占)
self.reservation_preempt_min_value_yuan = 0.0
# 详情页识别兜底(参与按钮 OCR)节流
self.detail_ocr_check_min_interval_seconds = 8.0
# 福袋详情识别异常(时间/价值)时:关闭重开后延迟再截图的秒数
self.fudai_abnormal_reopen_delay_seconds = 1.2
# 定时禁抢:凌晨时段不抢福袋,仅持续养号
self.fudai_quiet_hours_enabled = True
self.fudai_quiet_start_hour = 2
self.fudai_quiet_end_hour = 7
# 运行中动态加载配置(网页端保存 config.json 后可生效)
self._last_config_reload_ts = 0.0
# 按需求:只保留“推荐页养号流程”(纯坐标点击),不再提供“推荐/直播/进入直播间”文本识别流程。
# 养号总开关:关闭时不执行推荐页养号(只原地等待)
self.yanghao_enabled = True
# 推荐页养号:可配置的“时长/间隔(冷却)”
self.yanghao_recommend_duration_seconds = 60
self.yanghao_recommend_interval_seconds = 0 # 0=不限制(每次触发都可执行)
self._yanghao_last_recommend_ts = 0.0
def _log_kv(self, *args, **fields):
"""统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。
兼容性说明:有些地方可能通过 kwargs 传入名为 'tag' 或 'msg' 的键,
为避免出现 "multiple values for argument 'tag'" 错误,这里优先使用位置参数,
并在必要时从 fields 中移除重复键。
"""
# 解析位置参数/关键字,位置参数优先
tag = None
msg = None
if len(args) >= 1:
tag = args[0]
if len(args) >= 2:
msg = args[1]
# 若 kwargs 中包含 'tag'/'msg',且位置参数未提供,则取 kwargs 的值;若位置参数已提供,则删除以避免重复
if 'tag' in fields:
if tag is None:
tag = fields.pop('tag')
else:
# 删除以避免后续处理将其误当作字段
fields.pop('tag', None)
if 'msg' in fields:
if msg is None:
msg = fields.pop('msg')
else:
fields.pop('msg', None)
try:
self._log_seq += 1
except Exception:
self._log_seq = 1
key_map = {
# 通用
"rid": "运行",
"seq": "序号",
"msg": "说明",
"biaoqian": "标签",
"bq": "标签",
"stage": "阶段",
"seen": "识别",
"next": "下一步",
"ok": "成功",
"text": "文本",
"action": "动作",
"result": "结果",
"mode": "模式",
"reason": "原因",
"wait_seconds": "等待秒",
"wait_s": "等待秒",
"remain_to_join_window_s": "距参与窗口秒",
"remain_wait_s": "剩余等待秒",
# 预约
"value_yuan": "价值元",
"future": "开奖时间",
"pos_seen": "发现位置",
"qsize": "队列数量",
"max_try": "最大尝试次数",
"cap": "队列上限",
"dropped": "丢弃数量",
"dropped_value_yuan": "丢弃价值元",
"dropped_future": "丢弃开奖时间",
"back_times": "需回退次数",
"room_pos": "当前位置",
"target_future": "【目标】开奖时间",
"target_value_yuan": "【目标】价值元",
"target_content": "【目标】内容",
"queue_brief": "【队列】摘要",
"attempt": "尝试次数",
"room_title": "直播间名(清洗后)",
"room_title_raw": "直播间名原文",
"room_title_expected": "【预期】直播间名",
"room_title_current": "【当前】直播间名",
"room_title_ratio": "直播间名相似度",
"room_title_raw_expected": "【预期】直播间名原文",
"room_title_raw_current": "【当前】直播间名原文",
# 预约回退校验:匹配调试字段(来自 _match_reservation debug_dict)
"expected_future": "【期望】开奖时间戳",
"actual_future": "【识别】开奖时间戳",
"future_diff_s": "开奖时间差秒",
"expected_value": "【期望】价值元",
"actual_value": "【识别】价值元",
"expected_content": "【期望】内容",
"actual_content": "【识别】内容",
# 新增字段映射
"content": "内容",
"task_count": "任务数",
"countdown": "倒计时",
"min_participants": "最小参与人数",
"max_participants": "最大参与人数",
"min_value_yuan": "最小价值元",
"diag_text": "诊断文本",
"seconds": "耗时秒",
"enter_reason": "进入原因",
"fudai_x": "福袋X坐标",
"participants": "参与人数",
"copies": "份数",
"value_yuan": "价值元",
"keyword": "关键词",
"x": "X坐标",
"y": "Y坐标",
"clicks": "点击次数",
"abnormal": "异常",
"reasons": "原因",
}
flat = []
flat.append("{}={}".format(key_map.get("rid", "运行"), getattr(self, "_run_id", "-")))
flat.append("{}={}".format(key_map.get("seq", "序号"), getattr(self, "_log_seq", 0)))
if msg:
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
if len(m) > 240:
m = m[:240] + "..."
flat.append("{}={}".format(key_map.get("msg", "说明"), m))
for k, v in (fields or {}).items():
if v is None:
continue
s = str(v)
if s == "":
continue
s = s.replace("\r", " ").replace("\n", " ").strip()
if len(s) > 240:
s = s[:240] + "..."
ck = key_map.get(str(k), None)
if not ck:
# 兜底:避免英文 key 出现在日志里
ck = "字段_{}".format(str(k))
flat.append("{}={}".format(ck, s))
# 获取时间戳(格式:HH:MM:SS)
try:
timestamp = datetime.now().strftime('%H:%M:%S')
except Exception:
timestamp = ""
# 构建日志行:格式为 [时间] [标签] 消息 字段...
# 如果消息为空,则只显示字段
log_parts = []
if timestamp:
log_parts.append(f"[{timestamp}]")
log_parts.append(f"[{tag}]")
if msg:
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
if len(m) > 200:
m = m[:200] + "..."
log_parts.append(m)
# 添加字段(使用中文key,格式化值)
for k, v in (fields or {}).items():
if v is None:
continue
key_cn = key_map.get(str(k), None)
if not key_cn:
# 兜底:避免英文 key 出现在日志里
key_cn = "字段_{}".format(str(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)
# 日志自动换行:每行最多130字符,超过则换行缩进继续输出
if len(log_line) <= 130:
print(log_line)
else:
# 超长日志:首行显示时间+标签+消息,后续行显示字段
parts = []
# 首行:时间 + 标签 + 消息
header_parts = []
if timestamp:
header_parts.append(f"[{timestamp}]")
header_parts.append(f"[{tag}]")
if msg:
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
if len(m) > 200:
m = m[:200] + "..."
header_parts.append(m)
parts.append(" ".join(header_parts))
# 字段分行显示
indent = " " # 2个空格缩进
current_line = indent
for k, v in (fields or {}).items():
if v is None:
continue
key_cn = key_map.get(str(k), None)
if not key_cn:
key_cn = "字段_{}".format(str(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
field_str = f"{key_cn}={v_str}"
# 检查是否需要换行(考虑缩进)
if len(current_line) + len(field_str) + 1 > 130:
if current_line.strip():
parts.append(current_line.strip())
current_line = indent + field_str
else:
if current_line == indent:
current_line += field_str
else:
current_line += " " + field_str
if current_line.strip() and current_line != indent:
parts.append(current_line.strip())
print("\n".join(parts))
# 纯坐标点击所需的内部默认坐标(1080x2400 基准,会自动按分辨率缩放)
self.yanghao_fallback_close_x = 1030
self.yanghao_fallback_close_y = 120
self.yanghao_fallback_live_x = 900
self.yanghao_fallback_live_y = 2280
self.yanghao_fallback_enter_live_x = 109
self.yanghao_fallback_enter_live_y = 376
# 关注标签坐标(用于从推荐页面点击顶部“关注”标签)
# 坐标以 1080x2400 分辨率为基准;你提供的矩形为:
# 左上角 (674, 153),右下角 (749, 185),中心点约为 (712, 169)
self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准)
self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准)
# 新养号动作:停留期间可按概率点爱心/收藏,停留结束后自动滑动到下一个
self.yanghao_enable_actions = True
self.yanghao_like_prob = 0.15
self.yanghao_fav_prob = 0.05
self.yanghao_after_dwell_swipe_direction = "up" # up=下一个内容, down=上一个内容
self.yanghao_after_dwell_swipe_distance_px = 900
self.yanghao_like_keywords = ["赞", "喜欢", "Like"]
self.yanghao_fav_keywords = ["收藏", "加入收藏", "取消收藏", "Favorite"]
# 爱心/收藏图标检测(更适合图标,避免文案/层级变化影响)
# 坐标以 1080x2400 为基准,会按当前分辨率缩放。
self.yanghao_like_icon_x = 0
self.yanghao_like_icon_y = 0
self.yanghao_fav_icon_x = 0
self.yanghao_fav_icon_y = 0
# 仅用于“截图检测ROI”的偏移(不影响点击坐标)。用于微调截图中心。
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self.yanghao_icon_roi_size = 180 # 截取检测区域边长(px)
self.yanghao_icon_match_threshold = 0.72
self.yanghao_like_template_path = os.path.join(os.path.dirname(__file__), "assets", "like.png")
self.yanghao_fav_template_path = os.path.join(os.path.dirname(__file__), "assets", "fav.png")
# 桌面图标模板(用于检测是否回到桌面)
self.desktop_icon_template_path = os.path.join(os.path.dirname(__file__), "assets", "desktop.png")
self.desktop_icon_x = 153
self.desktop_icon_y = 260
self.desktop_icon_roi_size = 200
self.desktop_icon_match_threshold = 0.6
# 养号逐步截图(调试用,开启后会比较慢/占空间)
self.yanghao_step_screenshot = False
# “评论/发弹幕”动作:仅在同时检测到爱心+收藏时,按概率触发
self.yanghao_comment_prob = 0.0
self.yanghao_comment_btn_x = 981
self.yanghao_comment_btn_y = 1399
self.yanghao_comment_input_x = 250
self.yanghao_comment_input_y = 2218
self.yanghao_comment_send_x = 906
self.yanghao_comment_send_y = 1298
self.yanghao_comment_close_x = 586
self.yanghao_comment_close_y = 385
self.yanghao_comment_texts = []
self.auto_join_fansclub = False # 是否自动尝试加入粉丝团(可能触发付费/钻石消耗)
self.fansclub_fail_action = "stay" # 粉丝团门槛无法处理时:stay=停留当前直播间,switch=切换下一个
self.last_attend_fail_reason = "" # 最近一次参与失败原因
# 福袋图标检测提速参数(默认更快;可在 config.json 覆盖)
self.fudai_icon_retry_delay_seconds = 0.6
self.fudai_icon_max_wait_seconds = 4.0
# 最多尝试寻找福袋图标次数(默认 5,可由 UI 修改)
self.fudai_find_max_attempts = 5
# 截图阶段诊断(OCR)节流:避免高频截图时反复 OCR 拖慢
self.screenshot_diagnose_min_interval_seconds = 8.0
self._last_diag_ts = 0.0
self._last_diag_stage = "-"
self._last_diag_seen = "-"
# 福袋详情异常重试预算:避免 OCR 异常时单次卡太久
self.fudai_detail_retry_budget_seconds = 10.0
self.load_config()
def load_config(self):
"""从配置文件中加载数据"""
if os.path.exists(self.config_path):
with open(self.config_path, "r", encoding="utf-8") as file:
config = json.load(file)
self.contains_not_want = config.get("contains_not_want", [])
self.contains_want = config.get("contains_want", [])
try:
self.min_prize_value_yuan = float(config.get("min_prize_value_yuan", 0) or 0)
except (TypeError, ValueError):
self.min_prize_value_yuan = 0.0
try:
self.min_participants = int(config.get("min_participants", 0) or 0)
except (TypeError, ValueError):
self.min_participants = 0
try:
self.max_participants = int(config.get("max_participants", 0) or 0)
except (TypeError, ValueError):
self.max_participants = 0
try:
self.skip_if_countdown_lt_seconds = int(config.get("skip_if_countdown_lt_seconds", 15) or 15)
except (TypeError, ValueError):
self.skip_if_countdown_lt_seconds = 15
# 无福袋看门狗(30分钟无福袋回列表重进):默认关闭
try:
self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", False))
except Exception:
self.no_fudai_watchdog_enabled = False
# 福袋图标检测提速参数
try:
self.fudai_icon_retry_delay_seconds = float(config.get("fudai_icon_retry_delay_seconds", self.fudai_icon_retry_delay_seconds) or self.fudai_icon_retry_delay_seconds)
except (TypeError, ValueError):
pass
if self.fudai_icon_retry_delay_seconds < 0.2:
self.fudai_icon_retry_delay_seconds = 0.2
if self.fudai_icon_retry_delay_seconds > 5:
self.fudai_icon_retry_delay_seconds = 5.0
try:
self.fudai_icon_max_wait_seconds = float(config.get("fudai_icon_max_wait_seconds", self.fudai_icon_max_wait_seconds) or self.fudai_icon_max_wait_seconds)
except (TypeError, ValueError):
pass
if self.fudai_icon_max_wait_seconds < 0:
self.fudai_icon_max_wait_seconds = 0.0
if self.fudai_icon_max_wait_seconds > 30:
self.fudai_icon_max_wait_seconds = 30.0
try:
self.fudai_find_max_attempts = int(config.get("fudai_find_max_attempts", self.fudai_find_max_attempts) or self.fudai_find_max_attempts)
except (TypeError, ValueError):
pass
if self.fudai_find_max_attempts < 1:
self.fudai_find_max_attempts = 1
if self.fudai_find_max_attempts > 50:
self.fudai_find_max_attempts = 50
# 截图阶段诊断(OCR)节流
try:
self.screenshot_diagnose_min_interval_seconds = float(
config.get("screenshot_diagnose_min_interval_seconds", self.screenshot_diagnose_min_interval_seconds)
or self.screenshot_diagnose_min_interval_seconds
)
except (TypeError, ValueError):
pass
if self.screenshot_diagnose_min_interval_seconds < 0:
self.screenshot_diagnose_min_interval_seconds = 0.0
if self.screenshot_diagnose_min_interval_seconds > 60:
self.screenshot_diagnose_min_interval_seconds = 60.0
try:
self.reset_after_swipes_enabled = bool(config.get("reset_after_swipes_enabled", False))
except Exception:
self.reset_after_swipes_enabled = False
try:
raw_reset_swipes = config.get("reset_after_swipes", 10)
self.reset_after_swipes = int(10 if raw_reset_swipes is None else raw_reset_swipes)
except (TypeError, ValueError):
self.reset_after_swipes = 10
# 兼容旧配置:若未声明开关但阈值大于0,则自动视为开启
if not config.get("reset_after_swipes_enabled", None) and self.reset_after_swipes > 0:
self.reset_after_swipes_enabled = True
if self.reset_after_swipes < 1:
self.reset_after_swipes = 1
# 高价值福袋预约
try:
self.high_value_fudai_enabled = bool(config.get("high_value_fudai_enabled", False))
except Exception:
self.high_value_fudai_enabled = False
try:
self.high_value_fudai_threshold_yuan = float(config.get("high_value_fudai_threshold_yuan", 1000.0) or 1000.0)
except (TypeError, ValueError):
self.high_value_fudai_threshold_yuan = 1000.0
try:
self.high_value_fudai_join_ahead_seconds = int(config.get("high_value_fudai_join_ahead_seconds", 120) or 120)
except (TypeError, ValueError):
self.high_value_fudai_join_ahead_seconds = 120
try:
self.high_value_fudai_max_swipe_back = int(config.get("high_value_fudai_max_swipe_back", 60) or 60)
except (TypeError, ValueError):
self.high_value_fudai_max_swipe_back = 60
try:
self.high_value_fudai_max_reservations = int(config.get("high_value_fudai_max_reservations", 5) or 5)
except (TypeError, ValueError):
self.high_value_fudai_max_reservations = 5
if self.high_value_fudai_max_reservations < 1:
self.high_value_fudai_max_reservations = 1
if self.high_value_fudai_max_reservations > 50:
self.high_value_fudai_max_reservations = 50
try:
self.high_value_fudai_after_action = str(config.get("high_value_fudai_after_action", "continue") or "continue").strip().lower()
except Exception:
self.high_value_fudai_after_action = "continue"
if self.high_value_fudai_after_action not in ("stay", "continue"):
self.high_value_fudai_after_action = "continue"
try:
self.high_value_fudai_after_stay_seconds = int(config.get("high_value_fudai_after_stay_seconds", 120) or 120)
except (TypeError, ValueError):
self.high_value_fudai_after_stay_seconds = 120
if self.high_value_fudai_after_stay_seconds < 0:
self.high_value_fudai_after_stay_seconds = 0
if self.high_value_fudai_after_stay_seconds > 3600:
self.high_value_fudai_after_stay_seconds = 3600
# 高价值直播间回访
try:
self.high_value_room_revisit_enabled = bool(config.get("high_value_room_revisit_enabled", self.high_value_room_revisit_enabled))
except Exception:
pass
try:
self.reservation_back_verify_enabled = bool(config.get("reservation_back_verify_enabled", True))
except Exception:
self.reservation_back_verify_enabled = True
try:
self.reservation_preempt_min_value_yuan = float(config.get("reservation_preempt_min_value_yuan", self.reservation_preempt_min_value_yuan) or self.reservation_preempt_min_value_yuan)
except (TypeError, ValueError):
pass
if self.reservation_preempt_min_value_yuan < 0:
self.reservation_preempt_min_value_yuan = 0.0
try:
self.poll_before_open_seconds = int(config.get("poll_before_open_seconds", self.poll_before_open_seconds) or self.poll_before_open_seconds)
except (TypeError, ValueError):
pass
if self.poll_before_open_seconds < 0:
self.poll_before_open_seconds = 0
try:
self.high_value_room_revisit_interval_seconds = float(
config.get("high_value_room_revisit_interval_seconds", self.high_value_room_revisit_interval_seconds)
or self.high_value_room_revisit_interval_seconds
)
except (TypeError, ValueError):
pass
if self.high_value_room_revisit_interval_seconds < 60:
self.high_value_room_revisit_interval_seconds = 60.0
if self.high_value_room_revisit_interval_seconds > 1800:
self.high_value_room_revisit_interval_seconds = 1800.0
try:
self.high_value_room_revisit_watch_window_seconds = float(
config.get("high_value_room_revisit_watch_window_seconds", self.high_value_room_revisit_watch_window_seconds)
or self.high_value_room_revisit_watch_window_seconds
)
except (TypeError, ValueError):
pass
if self.high_value_room_revisit_watch_window_seconds < 60:
self.high_value_room_revisit_watch_window_seconds = 60.0
if self.high_value_room_revisit_watch_window_seconds > 7200:
self.high_value_room_revisit_watch_window_seconds = 7200.0
try:
self.high_value_room_revisit_skip_if_reservation_within_seconds = int(
config.get(
"high_value_room_revisit_skip_if_reservation_within_seconds",
self.high_value_room_revisit_skip_if_reservation_within_seconds,
)
or self.high_value_room_revisit_skip_if_reservation_within_seconds
)
except (TypeError, ValueError):
pass
if self.high_value_room_revisit_skip_if_reservation_within_seconds < 0:
self.high_value_room_revisit_skip_if_reservation_within_seconds = 0
if self.high_value_room_revisit_skip_if_reservation_within_seconds > 1800:
self.high_value_room_revisit_skip_if_reservation_within_seconds = 1800
# 详情页 OCR 兜底节流
try:
self.detail_ocr_check_min_interval_seconds = float(
config.get("detail_ocr_check_min_interval_seconds", self.detail_ocr_check_min_interval_seconds)
or self.detail_ocr_check_min_interval_seconds
)
except (TypeError, ValueError):
pass
if self.detail_ocr_check_min_interval_seconds < 0:
self.detail_ocr_check_min_interval_seconds = 0.0
if self.detail_ocr_check_min_interval_seconds > 60:
self.detail_ocr_check_min_interval_seconds = 60.0
# 福袋详情异常(时间/价值)重开延迟
try:
self.fudai_abnormal_reopen_delay_seconds = float(
config.get("fudai_abnormal_reopen_delay_seconds", 1.2) or 1.2
)
except (TypeError, ValueError):
self.fudai_abnormal_reopen_delay_seconds = 1.2
if self.fudai_abnormal_reopen_delay_seconds < 0:
self.fudai_abnormal_reopen_delay_seconds = 0.0
if self.fudai_abnormal_reopen_delay_seconds > 10:
self.fudai_abnormal_reopen_delay_seconds = 10.0
# 福袋详情异常重试预算
try:
self.fudai_detail_retry_budget_seconds = float(
config.get("fudai_detail_retry_budget_seconds", self.fudai_detail_retry_budget_seconds)
or self.fudai_detail_retry_budget_seconds
)
except (TypeError, ValueError):
pass
if self.fudai_detail_retry_budget_seconds < 0:
self.fudai_detail_retry_budget_seconds = 0.0
if self.fudai_detail_retry_budget_seconds > 60:
self.fudai_detail_retry_budget_seconds = 60.0
# 定时禁抢(默认 2:00-7:00)
try:
self.fudai_quiet_hours_enabled = bool(config.get("fudai_quiet_hours_enabled", True))
except Exception:
self.fudai_quiet_hours_enabled = True
try:
self.fudai_quiet_start_hour = int(config.get("fudai_quiet_start_hour", 2) or 2)
except (TypeError, ValueError):
self.fudai_quiet_start_hour = 2
try:
self.fudai_quiet_end_hour = int(config.get("fudai_quiet_end_hour", 7) or 7)
except (TypeError, ValueError):
self.fudai_quiet_end_hour = 7
# 只保留推荐页养号:忽略旧字段与流程开关
try:
self.yanghao_enabled = bool(config.get("yanghao_enabled", True))
except Exception:
self.yanghao_enabled = True
try:
self.yanghao_recommend_duration_seconds = int(config.get("yanghao_recommend_duration_seconds", 60) or 60)
except (TypeError, ValueError):
self.yanghao_recommend_duration_seconds = 60
try:
self.yanghao_recommend_interval_seconds = int(config.get("yanghao_recommend_interval_seconds", 0) or 0)
except (TypeError, ValueError):
self.yanghao_recommend_interval_seconds = 0
# 注意:不再从 config 读取“推荐/直播/进入直播间文本”与“兜底坐标”;统一使用代码内默认坐标。
self.yanghao_enable_actions = bool(config.get("yanghao_enable_actions", True))
try:
self.yanghao_like_prob = float(config.get("yanghao_like_prob", 0.15) or 0.15)
except (TypeError, ValueError):
self.yanghao_like_prob = 0.15
try:
self.yanghao_fav_prob = float(config.get("yanghao_fav_prob", 0.05) or 0.05)
except (TypeError, ValueError):
self.yanghao_fav_prob = 0.05
self.yanghao_after_dwell_swipe_direction = str(
config.get("yanghao_after_dwell_swipe_direction", "up") or "up"
).strip().lower()
try:
self.yanghao_after_dwell_swipe_distance_px = int(
config.get("yanghao_after_dwell_swipe_distance_px", 900) or 900
)
except (TypeError, ValueError):
self.yanghao_after_dwell_swipe_distance_px = 900
lk = config.get("yanghao_like_keywords", ["赞", "喜欢", "Like"]) or ["赞", "喜欢", "Like"]
fk = config.get("yanghao_fav_keywords", ["收藏", "加入收藏", "取消收藏", "Favorite"]) or ["收藏", "加入收藏", "取消收藏", "Favorite"]
if isinstance(lk, list):
self.yanghao_like_keywords = [str(x) for x in lk if str(x).strip()]
if isinstance(fk, list):
self.yanghao_fav_keywords = [str(x) for x in fk if str(x).strip()]
# 图标检测配置(可选)
try:
self.yanghao_like_icon_x = int(config.get("yanghao_like_icon_x", 0) or 0)
except (TypeError, ValueError):
self.yanghao_like_icon_x = 0
try:
self.yanghao_like_icon_y = int(config.get("yanghao_like_icon_y", 0) or 0)
except (TypeError, ValueError):
self.yanghao_like_icon_y = 0
try:
self.yanghao_fav_icon_x = int(config.get("yanghao_fav_icon_x", 0) or 0)
except (TypeError, ValueError):
self.yanghao_fav_icon_x = 0
try:
self.yanghao_fav_icon_y = int(config.get("yanghao_fav_icon_y", 0) or 0)
except (TypeError, ValueError):
self.yanghao_fav_icon_y = 0
# ROI 偏移(可选)
for k, attr in (
("yanghao_like_roi_offset_x", "yanghao_like_roi_offset_x"),
("yanghao_like_roi_offset_y", "yanghao_like_roi_offset_y"),
("yanghao_fav_roi_offset_x", "yanghao_fav_roi_offset_x"),
("yanghao_fav_roi_offset_y", "yanghao_fav_roi_offset_y"),
):
try:
setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr)))
except (TypeError, ValueError):
pass
try:
self.yanghao_icon_roi_size = int(config.get("yanghao_icon_roi_size", 180) or 180)
except (TypeError, ValueError):
self.yanghao_icon_roi_size = 180
try:
self.yanghao_icon_match_threshold = float(config.get("yanghao_icon_match_threshold", 0.72) or 0.72)
except (TypeError, ValueError):
self.yanghao_icon_match_threshold = 0.72
tp_like = str(config.get("yanghao_like_template_path", self.yanghao_like_template_path) or self.yanghao_like_template_path)
tp_fav = str(config.get("yanghao_fav_template_path", self.yanghao_fav_template_path) or self.yanghao_fav_template_path)
base_dir = os.path.dirname(__file__)
if tp_like and (not os.path.isabs(tp_like)):
tp_like = os.path.normpath(os.path.join(base_dir, tp_like))
if tp_fav and (not os.path.isabs(tp_fav)):
tp_fav = os.path.normpath(os.path.join(base_dir, tp_fav))
self.yanghao_like_template_path = tp_like
self.yanghao_fav_template_path = tp_fav
# 逐步截图开关(可选)
try:
self.yanghao_step_screenshot = bool(config.get("yanghao_step_screenshot", False))
except Exception:
self.yanghao_step_screenshot = False
# 评论动作配置
try:
self.yanghao_comment_prob = float(config.get("yanghao_comment_prob", 0.0) or 0.0)
except (TypeError, ValueError):
self.yanghao_comment_prob = 0.0
for k, attr in (
("yanghao_comment_btn_x", "yanghao_comment_btn_x"),
("yanghao_comment_btn_y", "yanghao_comment_btn_y"),
("yanghao_comment_input_x", "yanghao_comment_input_x"),
("yanghao_comment_input_y", "yanghao_comment_input_y"),
("yanghao_comment_send_x", "yanghao_comment_send_x"),
("yanghao_comment_send_y", "yanghao_comment_send_y"),
("yanghao_comment_close_x", "yanghao_comment_close_x"),
("yanghao_comment_close_y", "yanghao_comment_close_y"),
):
try:
setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr)))
except (TypeError, ValueError):
pass
ct = config.get("yanghao_comment_texts", []) or []
if isinstance(ct, list):
self.yanghao_comment_texts = [str(x).strip() for x in ct if str(x).strip()]
self.auto_join_fansclub = bool(config.get("auto_join_fansclub", False))
self.fansclub_fail_action = str(config.get("fansclub_fail_action", "stay") or "stay").lower()
def _maybe_reload_config(self, min_interval_seconds: float = 2.0) -> None:
"""运行中定期从 config.json 重新加载配置,便于网页端随时修改。"""
try:
now = time.time()
if (now - float(self._last_config_reload_ts or 0.0)) < float(min_interval_seconds or 0.0):
return
self._last_config_reload_ts = now
self.load_config()
except Exception:
pass
def _mark_enter_live(self, reason: str = "") -> None:
"""标记一次“已进入直播间”,用于统计后续找到福袋图标的耗时。"""
try:
self._enter_live_ts = float(time.time())
except Exception:
self._enter_live_ts = 0.0
try:
self._enter_live_reason = str(reason or "")
except Exception:
self._enter_live_reason = ""
self._enter_live_fudai_logged = False
def _in_quiet_hours(self, hour: int) -> bool:
"""判断当前小时是否处于禁抢时段(支持跨天区间)。"""
try:
h = int(hour)
except Exception:
return False
try:
start = int(self.fudai_quiet_start_hour)
end = int(self.fudai_quiet_end_hour)
except Exception:
start, end = 2, 7
# 归一化
start = start % 24
end = end % 24
if start == end:
return False
if start < end:
return start <= h < end
# 跨天:例如 22-7
return (h >= start) or (h < end)
def _save_step_screenshot(self, label: str) -> str | None:
"""保存当前屏幕截图为独立文件,便于你逐步核对是否点对了位置。"""
try:
base_dir = os.path.join(os.path.dirname(__file__), "pic")
os.makedirs(base_dir, exist_ok=True)
ok = self._shot_and_diagnose("养号截图", "保存逐步截图({})".format(label), self.device_id)
if not ok:
return None
src = os.path.join(base_dir, "screenshot.png")
if not os.path.exists(src):
return None
safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fa5_-]+", "_", str(label or "step"))
label_dir = os.path.join(base_dir, safe)
os.makedirs(label_dir, exist_ok=True)
# 同时保存一份带时间戳的历史截图 + 覆盖 latest.png
ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
dst_hist = os.path.join(label_dir, f"{ts}.png")
dst_latest = os.path.join(label_dir, "latest.png")
shutil.copyfile(src, dst_hist)
shutil.copyfile(src, dst_latest)
print(f"[养号] 截图已保存:{dst_hist} (latest已更新)")
return dst_hist
except Exception as e:
print(f"[养号] 截图保存失败:{e}")
return None
def _scale_from_base(self, x: int, y: int, base_w: int = 1080, base_h: int = 2400) -> tuple[int, int]:
try:
sx = int(int(x) * int(self.resolution_ratio_x) / int(base_w))
sy = int(int(y) * int(self.resolution_ratio_y) / int(base_h))
except Exception:
sx, sy = int(x), int(y)
return sx, sy
def _capture_roi_screenshot(self, label: str, center_x: int, center_y: int, size_px: int) -> str | None:
"""截屏并裁剪指定坐标附近 ROI,保存到 pic/<label>/latest.png(覆盖)。"""
try:
base_dir = os.path.join(os.path.dirname(__file__), "pic")
os.makedirs(base_dir, exist_ok=True)
ok = self._shot_and_diagnose("ROI截图", "截取ROI({})".format(label), self.device_id)
if not ok:
return None
src = os.path.join(base_dir, "screenshot.png")
if not os.path.exists(src):
return None
safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fa5_-]+", "_", str(label or "roi"))
label_dir = os.path.join(base_dir, safe)
os.makedirs(label_dir, exist_ok=True)
dst = os.path.join(label_dir, "latest.png")
img = Image.open(src).convert("RGB")
w, h = img.size
half = int(max(40, min(int(size_px), 600)) / 2)
x1 = max(0, int(center_x) - half)
y1 = max(0, int(center_y) - half)
x2 = min(w, int(center_x) + half)
y2 = min(h, int(center_y) + half)
img.crop((x1, y1, x2, y2)).save(dst)
print(f"[养号] ROI截图已保存:{dst} (center={center_x},{center_y} size={half*2})")
return dst
except Exception as e:
print(f"[养号] ROI截图失败:{e}")
return None
def _match_icon_template(self, roi_path: str, template_path: str) -> tuple[bool, float]:
"""用模板匹配判断 ROI 是否包含目标图标。返回 (detected, score)。"""
try:
import cv2
import numpy as np
if not roi_path or not os.path.exists(roi_path):
return False, 0.0
if not template_path or not os.path.exists(template_path):
return False, 0.0
roi_bgr = cv2.imdecode(np.fromfile(roi_path, dtype=np.uint8), cv2.IMREAD_COLOR)
tpl_bgr = cv2.imdecode(np.fromfile(template_path, dtype=np.uint8), cv2.IMREAD_COLOR)
if roi_bgr is None or tpl_bgr is None:
return False, 0.0
roi_gray = cv2.cvtColor(roi_bgr, cv2.COLOR_BGR2GRAY)
tpl_gray = cv2.cvtColor(tpl_bgr, cv2.COLOR_BGR2GRAY)
# 模板必须小于 ROI
rh, rw = roi_gray.shape[:2]
th, tw = tpl_gray.shape[:2]
if th >= rh or tw >= rw:
# 模板过大时先缩小到 ROI 的 80%
scale = min((rw * 0.8) / max(tw, 1), (rh * 0.8) / max(th, 1))
if scale <= 0:
return False, 0.0
tpl_gray = cv2.resize(tpl_gray, (max(1, int(tw * scale)), max(1, int(th * scale))))
res = cv2.matchTemplate(roi_gray, tpl_gray, cv2.TM_CCOEFF_NORMED)
_min, max_val, _min_loc, _max_loc = cv2.minMaxLoc(res)
score = float(max_val or 0.0)
detected = score >= float(self.yanghao_icon_match_threshold or 0.72)
return detected, score
except Exception:
return False, 0.0
def _yanghao_idle(self, total_seconds: int) -> None:
"""养号等待。
- 若启用 `yanghao_enable_actions`:停留期间可按概率点爱心/收藏,停留结束后自动滑动。
- 否则:保持原有“分段等待 + 可选轻微滑动 + 定时休息”。
"""
if total_seconds <= 0:
return
if self.yanghao_enable_actions:
# 循环:持续检测图标;都未检测到则立刻下滑继续;检测到则停留 10-15 秒并按概率执行动作,然后再下滑。
need_settle_after_swipe = False
def _step_shot(label: str) -> None:
# 环境变量优先:YANGHAO_STEP_SCREENSHOT=1
try:
env_on = bool(str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip())
except Exception:
env_on = False
if env_on or bool(getattr(self, "yanghao_step_screenshot", False)):
self._save_step_screenshot(label)
def _do_swipe_next() -> None:
nonlocal need_settle_after_swipe
_step_shot("before_swipe")
dist = int(self.yanghao_after_dwell_swipe_distance_px or 900)
if dist < 200:
dist = 200
if dist > 1400:
dist = 1400
x = int(1080 * 0.7)
y_mid = int(2400 * 0.55)
if str(self.yanghao_after_dwell_swipe_direction or "up").lower() == "up":
# up:上滑切换到下一个内容(手指从下往上)
y1 = y_mid + int(dist / 2)
y2 = y_mid - int(dist / 2)
else:
# down:下滑回到上一个内容(手指从上往下)
y1 = y_mid - int(dist / 2)
y2 = y_mid + int(dist / 2)
self.swipe(x, y1, x, y2, 180)
print("[养号] 动作: 下滑/切换 direction={} dist={}px".format(self.yanghao_after_dwell_swipe_direction, dist))
_step_shot("after_swipe")
# 标记:下滑后下一轮截图/检测前需要随机等待,避免动画未结束影响识别
need_settle_after_swipe = True
def _scaled_click(base_x: int, base_y: int) -> None:
sx, sy = self._scale_from_base(int(base_x), int(base_y))
self.operation.click(self.device_id, sx, sy)
def _human_delay(min_s: float = 0.4, max_s: float = 1.2) -> None:
try:
mn = float(min_s)
mx = float(max_s)
if mx < mn:
mx = mn
self.operation.delay(random.uniform(mn, mx))
except Exception:
self.operation.delay(1)
def _detect_icon(action: str, base_x: int, base_y: int, template_path: str, roi_label: str) -> tuple[bool, float]:
nonlocal need_settle_after_swipe
if need_settle_after_swipe:
# 下滑后:先随机等一下,再进行截图与模板匹配
_human_delay(1.0, 2.2)
need_settle_after_swipe = False
_step_shot(f"before_detect_{roi_label}")
if int(base_x or 0) <= 0 or int(base_y or 0) <= 0:
return False, 0.0
# ROI 中心点允许独立偏移(仅影响截图检测,不影响点击坐标)
off_x = 0
off_y = 0
if action == "爱心":
off_x = int(self.yanghao_like_roi_offset_x or 0)
off_y = int(self.yanghao_like_roi_offset_y or 0)
elif action == "收藏":
off_x = int(self.yanghao_fav_roi_offset_x or 0)
off_y = int(self.yanghao_fav_roi_offset_y or 0)
sx, sy = self._scale_from_base(int(base_x), int(base_y))
if off_x or off_y:
try:
sx = int(sx) + int(off_x * int(self.resolution_ratio_x) / 1080)
sy = int(sy) + int(off_y * int(self.resolution_ratio_y) / 2400)
except Exception:
pass
roi_path = self._capture_roi_screenshot(roi_label, sx, sy, int(self.yanghao_icon_roi_size or 180))
if not template_path or not os.path.exists(template_path):
print(f"[养号] 检测: {action} -> 失败(缺少模板文件:{template_path})")
return False, 0.0
detected, score = self._match_icon_template(roi_path, template_path)
print(f"[养号] 检测: {action} -> {'检测到' if detected else '未检测到'}(score={score:.3f})")
return detected, score
use_icon = (
int(self.yanghao_like_icon_x or 0) > 0
and int(self.yanghao_like_icon_y or 0) > 0
and int(self.yanghao_fav_icon_x or 0) > 0
and int(self.yanghao_fav_icon_y or 0) > 0
)
start_ts = time.time()
while True:
if time.time() - start_ts >= total_seconds:
return
if not use_icon:
# 未配置图标检测就退化为“原地等待”
self.operation.delay(int(max(1, total_seconds)))
return
like_ok, _like_score = _detect_icon("爱心", self.yanghao_like_icon_x, self.yanghao_like_icon_y, self.yanghao_like_template_path, "action_like_roi")
fav_ok, _fav_score = _detect_icon("收藏", self.yanghao_fav_icon_x, self.yanghao_fav_icon_y, self.yanghao_fav_template_path, "action_fav_roi")
if (not like_ok) and (not fav_ok):
# 两个都没检测到:立刻下滑继续检测
_human_delay(0.3, 0.8)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
continue
# 检测到其中任意一个:在这里停留 10-15 秒,并按概率执行动作
dwell = int(random.randint(10, 15))
print(f"[养号] 检测到图标,停留 {dwell}s 后再切换")
# 仅当“同时检测到爱心+收藏”时,按概率触发评论动作
if like_ok and fav_ok and float(self.yanghao_comment_prob or 0) > 0 and random.random() < float(self.yanghao_comment_prob):
if self.yanghao_comment_texts:
msg = random.choice(self.yanghao_comment_texts)
print("[养号] 动作: 评论(prob={}) -> {}".format(self.yanghao_comment_prob, msg))
try:
_step_shot("comment_before_open")
_scaled_click(self.yanghao_comment_btn_x, self.yanghao_comment_btn_y)
_human_delay(0.8, 1.6)
_step_shot("comment_after_open")
_scaled_click(self.yanghao_comment_input_x, self.yanghao_comment_input_y)
_human_delay(0.6, 1.2)
_step_shot("comment_after_focus")
# 输入随机文本(优先 ADBKeyboard;否则走剪贴板/兜底)
ix, iy = self._scale_from_base(int(self.yanghao_comment_input_x), int(self.yanghao_comment_input_y))
prev_ime = ""
try:
ok_ime, prev_ime, _adb_ime = self.operation.ensure_adbkeyboard_ime(self.device_id)
except Exception:
ok_ime = False
ok_input = False
if ok_ime:
try:
ok_input = self.operation.input_text_adbkeyboard(self.device_id, msg, restore_prev=False)
except Exception:
ok_input = False
if not ok_input:
ok_input = bool(self.operation.paste_text_at(self.device_id, ix, iy, msg))
print(f"[养号] 评论输入{'成功' if ok_input else '失败'}")
_step_shot("comment_after_input")
_human_delay(0.6, 1.4)
# 发送:改为键盘确认(优先 ADBKeyBoard 的 SEND editor action;兜底 Enter)
try:
self.operation.confirm_from_keyboard(self.device_id)
except Exception:
pass
_human_delay(0.8, 1.6)
_step_shot("comment_after_send")
_scaled_click(self.yanghao_comment_close_x, self.yanghao_comment_close_y)
_human_delay(0.6, 1.2)
_step_shot("comment_after_close")
# 恢复原输入法(如果之前切换过)
if prev_ime:
try:
self.operation.restore_ime(self.device_id, prev_ime)
except Exception:
pass
except Exception as e:
print(f"[养号] 动作: 评论失败:{e}")
else:
print("[养号] 动作: 评论(prob={}) -> 跳过(未配置文案列表)".format(self.yanghao_comment_prob))
if like_ok and float(self.yanghao_like_prob or 0) > 0 and random.random() < float(self.yanghao_like_prob):
_human_delay(0.3, 0.9)
_step_shot("before_like_click")
_scaled_click(self.yanghao_like_icon_x, self.yanghao_like_icon_y)
_human_delay(0.2, 0.6)
_step_shot("after_like_click")
print("[养号] 动作: 点爱心(prob={})".format(self.yanghao_like_prob))
else:
print("[养号] 动作: 跳过点爱心(prob={})".format(self.yanghao_like_prob))
if fav_ok and float(self.yanghao_fav_prob or 0) > 0 and random.random() < float(self.yanghao_fav_prob):
_human_delay(0.3, 0.9)
_step_shot("before_fav_click")
_scaled_click(self.yanghao_fav_icon_x, self.yanghao_fav_icon_y)
_human_delay(0.2, 0.6)
_step_shot("after_fav_click")
print("[养号] 动作: 点收藏(prob={})".format(self.yanghao_fav_prob))
else:
print("[养号] 动作: 跳过点收藏(prob={})".format(self.yanghao_fav_prob))
# 停留
self.operation.delay(dwell)
# 接着下滑
_human_delay(0.4, 1.0)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
# unreachable
return
start_ts = time.time()
while True:
now = time.time()
elapsed = now - start_ts
if elapsed >= total_seconds:
return
# 分段等待(避免一次 sleep 太久,看起来更自然)
remaining = int(total_seconds - (time.time() - start_ts))
if remaining <= 0:
return
chunk = 10 if remaining > 10 else remaining
self.operation.delay(chunk)
def _yanghao_try_tap_text_or_fallback(self, text: str, fx: int, fy: int, contains: bool = True, wait_after: float = 1.2, use_fallback: bool = True, tap_timeout: float = 1.5) -> bool:
ok = False
# 测试模式下尽量快(避免用户以为卡死)
if str(os.environ.get("FAST_UI", "")).strip() in ("1", "true", "True"):
wait_after = 0.2
try:
ok = self.operation.tap_by_text(self.device_id, text, contains=contains, timeout_seconds=tap_timeout)
except Exception:
ok = False
if ok:
print("[养号] 点击 '{}':UI 命中".format(text))
else:
if use_fallback:
print("[养号] 点击 '{}':UI 未命中,坐标兜底 ({},{})".format(text, fx, fy))
self.click(int(fx), int(fy))
ok = True
else:
print("[养号] 点击 '{}':UI 未命中,跳过兜底".format(text))
if wait_after and wait_after > 0:
self.operation.delay(wait_after)
return ok
def _yanghao_try_multi_texts(self, texts: list[str], contains: bool = True, wait_after: float = 1.2, tap_timeout: float = 2.5) -> bool:
"""依次尝试多组文案(无坐标兜底)。"""
for idx, t in enumerate(texts, 1):
ok = self._yanghao_try_tap_text_or_fallback(
t,
0,
0,
contains=contains,
wait_after=wait_after if idx == len(texts) else 0.0,
use_fallback=False,
tap_timeout=tap_timeout,
)
if ok:
return True
return False
def _yanghao_tap_close_icon(self) -> None:
"""仅使用系统返回键退出当前页(不再尝试坐标点击)。"""
print("[养号] 发送系统返回键 1/1")
self.operation.click_back(self.device_id)
self.operation.delay(0.8)
def _yanghao_recommend_flow(self, total_seconds: int) -> None:
"""按你的需求执行:X 退出直播 -> 点推荐 -> 养号 -> 点直播 -> 点“点击进入直播间”。
如果识别不到文字,会使用坐标兜底;兜底仍失败时就退化成原地养号(不阻塞主流程)。
"""
try:
print("[养号] 推荐页流程:退出直播→推荐→养号→直播→进入直播间")
capture_steps = str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip() in ("1", "true", "True")
if capture_steps:
self._save_step_screenshot("start")
print("[养号] Step1/5:系统返回键退出当前页")
self._yanghao_tap_close_icon()
print("[养号] step1: 已发送系统返回键(1次)")
if capture_steps:
self._save_step_screenshot("step1_close")
print("[养号] Step2/5:再次发送返回键")
self.operation.click_back(self.device_id)
self.operation.delay(1.2)
if capture_steps:
self._save_step_screenshot("step2_back")
print("[养号] Step3/5:在当前页停留/浏览 {} 秒".format(int(total_seconds)))
self._yanghao_idle(total_seconds)
print("[养号] step3: 停留/浏览完成 {} 秒".format(total_seconds))
if capture_steps:
self._save_step_screenshot("step3_browse_done")
print("[养号] Step4/5:回到『直播』")
print("[养号] step4: 坐标点击直播 -> ({},{})".format(self.yanghao_fallback_live_x, self.yanghao_fallback_live_y))
self.click(int(self.yanghao_fallback_live_x), int(self.yanghao_fallback_live_y))
self.operation.delay(1.5)
if capture_steps:
self._save_step_screenshot("step4_live")
print("[养号] Step5/5:点击『点击进入直播间』")
print("[养号] step5: 坐标点击进入直播间 -> ({},{}) 连点两次".format(self.yanghao_fallback_enter_live_x, self.yanghao_fallback_enter_live_y))
self.click(int(self.yanghao_fallback_enter_live_x), int(self.yanghao_fallback_enter_live_y))
self.operation.delay(0.6)
self.click(int(self.yanghao_fallback_enter_live_x), int(self.yanghao_fallback_enter_live_y))
self.operation.delay(2.0)
if capture_steps:
self._save_step_screenshot("step5_enter")
print("[养号] 推荐页流程完成")
except Exception as e:
print("[养号] 推荐页流程失败,退化为原地养号:{}".format(e))
self._yanghao_idle(total_seconds)
def _yanghao_wait(self, total_seconds: int) -> None:
if total_seconds <= 0:
return
if not bool(getattr(self, "yanghao_enabled", True)):
# 用户要求:关闭养号后不要再等待太久,而是继续执行主流程
print(f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)")
try:
self.operation.delay(1)
except Exception:
pass
return
# 只保留推荐页养号;增加“间隔(冷却)”控制,避免触发过于频繁
try:
now = time.time()
interval = int(self.yanghao_recommend_interval_seconds or 0)
if interval > 0 and self._yanghao_last_recommend_ts > 0:
dt = now - float(self._yanghao_last_recommend_ts)
if dt < interval:
remain = int(interval - dt)
print(f"[养号] 推荐页养号冷却中,剩余 {remain}s,跳过本次(改为等待 {int(total_seconds)}s)")
self.operation.delay(int(max(1, total_seconds)))
return
self._yanghao_last_recommend_ts = time.time()
except Exception:
pass
self._yanghao_recommend_flow(total_seconds)
def _yanghao_get_recommend_seconds(self) -> int:
s = 60
try:
s = int(self.yanghao_recommend_duration_seconds or 60)
except Exception:
s = 60
if s < 1:
s = 1
if s > 3600:
s = 3600
return s
def _maybe_reset_after_swipes(self, needswitch: bool, swipe_times: int) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。"""
if not needswitch:
return swipe_times
if not bool(getattr(self, "reset_after_swipes_enabled", False)):
return swipe_times
threshold = max(1, int(self.reset_after_swipes or 0))
if swipe_times < threshold:
return swipe_times
print("已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(swipe_times, threshold))
# 回退次数按当前已切换次数来(更符合“回到本轮第一个直播间”的语义)
back_times = int(swipe_times)
if back_times <= 0:
return 0
# 下滑回退:与上划切换相反方向
for i in range(back_times):
self.swipe(760, 800, 760, 1600, 200)
print("回退直播间 {}/{}".format(i + 1, back_times))
self.operation.delay(2)
# 回到第一个后,计数归零
self.operation.delay(3)
return 0
def deal_robot_pic_change_color(self):
"""处理人机验证的图片,转为黑白图"""
self.cut_pic(143, 884, 936, 1380, 'save', 'robot_verification')
path = os.path.dirname(__file__) + '/pic/save'
pic = path + '/robot_verification.png'
img = Image.open(pic)
img = img.convert('RGB')
width, height = img.size
for x in range(5, width - 40):
for y in range(20, height - 30):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
img.putpixel((x, y), (255, 255, 255)) # 白色
elif current_color[0] < 35 and current_color[1] < 20 and current_color[2] < 20:
img.putpixel((x, y), (0, 0, 0)) # 白色
else:
img.putpixel((x, y), (128, 128, 128)) # 黑色
save_pic = path + '/robot_verification_new.png'
img.save(save_pic)
def check_robot_pic_distance(self):
"""处理人机验证的图片"""
self.cut_pic(143, 884, 936, 1380, '', 'robot_verification')
path = os.path.dirname(__file__) + '/pic'
pic = path + '/robot_verification.png'
img = Image.open(pic)
img = img.convert('RGB')
width, height = img.size
printed_first_result = False # 用于记录第一个结果是否已经输出过
printed_second_result = False # 用于记录第二个结果是否已经输出过
for y in range(20, height - 30):
for x in range(5, width - 40):
current_color = img.getpixel((x, y))
if current_color[0] > 240 and current_color[1] > 240 and current_color[2] > 240:
if not printed_first_result: # 确保只输出一次第一个结果
print(x, y)
printed_first_result = True
break
if printed_first_result: # 如果已经输出过第一个结果,则退出外层循环
break
for x1 in range(x, width - 40):
current_color = img.getpixel((x1, y))
if current_color[0] < 50 and current_color[1] < 55 and current_color[2] < 85 and current_color[0] + \
current_color[1] + current_color[2] < 150:
if not printed_second_result: # 确保只输出一次第二个结果
print(x1, y)
printed_second_result = True
print("需要滑动的距离为{}".format(x1 - x))
return x1 - x
def deal_robot_pic(self):
"""处理人机验证的图片"""
self.cut_pic(143, 884, 936, 1380, 'save', 'robot_verification')
path = os.path.dirname(__file__) + '/pic/save'
pic = path + '/robot_verification.png'
img = Image.open(pic)
img = img.convert('RGB')
width, height = img.size
threshold = 90 # 阈值,用于判断颜色偏差是否较大
for x in range(5, width - 40):
for y in range(20, height - 30):
# 获取当前像素点的颜色
if x > 5 and y > 20 and x < width - 40 and y < height - 30: # 跳过图片边沿的像素点
# 获取当前像素点的颜色
current_color = img.getpixel((x, y))
# if len(current_color) != 3:
# raise ValueError(f"Invalid color format at ({x}, {y}): {current_color}")
# # 获取周围像素点的颜色
num_deviant_neighbors = 0
for dx in range(-1, 2):
for dy in range(-1, 2):
if 0 <= x + dx < width and 0 <= y + dy < height: # 确保不超出图像边界
neighbor_color = img.getpixel((x + dx, y + dy))
if isinstance(neighbor_color, tuple) and len(neighbor_color) == 3: # 检查颜色格式
neighbor_color = tuple(
min(max(int(c), 0), 255) for c in neighbor_color) # 确保颜色值在0到255之间
channel_diffs = [abs(a - b) for a, b in zip(current_color, neighbor_color)]
# 如果每个通道的偏差都大于30,则将邻居像素点计数为偏差点
if all(diff > 70 for diff in channel_diffs):
num_deviant_neighbors += 1
# color_diff = sum(abs(a - b) for a, b in zip(current_color, neighbor_color))
# if color_diff > threshold:
# num_deviant_neighbors += 1
# 如果偏差大于阈值的邻居数量大于4,则认为是偏差点
if num_deviant_neighbors > 3:
img.putpixel((x, y), (255, 255, 255)) # 白色
else:
img.putpixel((x, y), (0, 0, 0)) # 黑色
save_pic = path + '/robot_verification_new.png'
img.save(save_pic)
def check_detail_height(self):
"""判定福袋弹窗的高度,会因为抽奖所需任务不同稍有区别,分别有不要任务、1/2/3个任务
优化:
- 提取公共的像素检测逻辑,减少代码重复
- 优化检测顺序(先检测最常见的2个任务)
- 添加边界检查
"""
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
pic = None
for attempt in range(3):
try:
pic = Image.open(pic1_path)
# 强制加载,尽早暴露截断/0字节问题
pic.load()
break
except (IOError, OSError, Image.UnidentifiedImageError):
if attempt < 2:
try:
# 重新截图一次再试
self.operation.get_screenshot(self.device_id)
self.operation.delay(0.2)
except Exception:
pass
pic = None
if pic is None:
self._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN")
return 0
pic_new = pic.convert('RGBA')
pix = pic_new.load()
width, height = pic_new.size
# 参与按钮的x坐标
x = 536 * self.resolution_ratio_x // 1080
if not (0 <= x < width):
return 0
# 定义检测点的y坐标和对应的任务数(按常见程度排序:2任务最常见)
# 格式:(base_y, y_pianyi_offset, task_count)
check_points = [
(983, 0, 2), # 2个任务(最常见)
(983, self.y_pianyi, 2),
(983, -self.y_pianyi, 2),
(883, 0, 3), # 3个任务
(883, self.y_pianyi, 3),
(883, -self.y_pianyi, 3),
(1058, 0, 1), # 1个任务
(1058, self.y_pianyi, 1),
(1058, -self.y_pianyi, 1),
]
# 参与按钮颜色范围(RGB)- 精度优化:适度放宽范围提高容错性
def _check_pixel_color(y_coord: int) -> bool:
"""检查指定y坐标的像素颜色是否匹配参与按钮"""
if not (0 <= y_coord < height):
return False
try:
p = pix[x, y_coord]
if not (isinstance(p, tuple) and len(p) >= 3):
return False
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 优化:适度放宽颜色范围(±2),提高在不同屏幕色温/亮度下的识别率
# 但保持中心值权重,避免误判
return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86
except (IndexError, TypeError):
return False
# 按顺序检测
for base_y, dy, task_count in check_points:
y = base_y * self.resolution_ratio_y // 2400 + dy
if _check_pixel_color(y):
self._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count)
return task_count
# 如果都没检测到,检查是否是人机校验
if self.check_have_robot_analyse():
self.deal_robot_analyse()
self._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0)
return 0
def check_have_fudai(self):
"""判定直播页面福袋的小图标是否存在"""
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
return self.check_have_fudai_with_ready_screenshot(False)
def check_have_fudai_with_ready_screenshot(self, screenshot_ready: bool = False):
"""判定直播页面福袋的小图标是否存在。
screenshot_ready=True 表示外层已完成截图(pic/screenshot.png 已更新),本方法首轮直接复用该截图,避免重复截图。
"""
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
loop = 0
retry_delay_s = float(getattr(self, "fudai_icon_retry_delay_seconds", 0.6) or 0.6)
max_wait_s = float(getattr(self, "fudai_icon_max_wait_seconds", 4.0) or 4.0)
if retry_delay_s < 0.2:
retry_delay_s = 0.2
if max_wait_s < 0:
max_wait_s = 0.0
max_loops = int(max(2, min(12, (max_wait_s / retry_delay_s) + 1)))
try:
user_max = int(getattr(self, 'fudai_find_max_attempts', 5) or 5)
except Exception:
user_max = 5
# 限制实际循环次数为两者的最小值,便于通过 UI 控制最大尝试次数
max_loops = int(min(max_loops, max(1, user_max)))
while loop < max_loops:
# 首轮可复用外层已截图;未命中才继续短等+重试
if not (screenshot_ready and loop == 0):
# 找福袋是高频路径:默认关闭 OCR 阶段诊断(使用缓存阶段信息),减少耗时
self._shot_and_diagnose("找福袋图标", "判定是否存在福袋", self.device_id, diagnose=False)
try:
pic = Image.open(pic1_path)
pic.load()
except Exception:
# 截图文件可能是 0 字节/截断:重试截图再继续下一轮
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
loop += 1
if loop < max_loops:
self.operation.delay(retry_delay_s)
continue
# pic_new = Image.open(cut_pic_path)
pic_new = pic.convert('RGBA')
detected = False
detected_x = None
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
try:
import numpy as _np
# 计算检测区域,考虑分辨率缩放和偏移
y0 = 403 * self.resolution_ratio_y // 2400 + self.y_pianyi
x1 = max(0, 41 * self.resolution_ratio_x // 1080)
x2 = min(pic_new.size[0], 410 * self.resolution_ratio_x // 1080)
y_top = max(0, y0 - 3)
y_bottom = min(pic_new.size[1], y0 + 4)
# 边界检查
if x1 >= x2 or y_top >= y_bottom:
detected = False
else:
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert('RGB')
arr = _np.array(roi)
if arr.size > 0:
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
# 原来的范围:R[193-203], G[176-193], B[237-247]
# 优化后:适度放宽范围,但保持中心值权重
mask_center = (r >= 190) & (r <= 206) & (g >= 173) & (g <= 196) & (b >= 234) & (b <= 250)
# 速度优化:使用更宽松的预筛选,减少计算量
mask = mask_center
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
cols = _np.sum(mask, axis=0)
# 至少需要2个像素匹配(避免单个噪点误判)
valid_cols = cols >= 2
if valid_cols.any():
# 找到第一个有效匹配的列
col_idx = int(_np.argmax(valid_cols))
# 计算检测到的x坐标:转换为1080基准坐标,确保精度
detected_x = int((x1 + col_idx) * 1080.0 / max(1, int(self.resolution_ratio_x)))
detected = True
self.last_find_fudai_time = time.time()
except (ImportError, ValueError, IndexError, AttributeError) as e:
# numpy不可用或计算错误,回退到逐像素检测
detected = False
# numpy 未命中/不可用时回退到原始逐像素检查
if not detected:
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
# 计算实际扫描范围,防止越界
scan_x_start = 41 * self.resolution_ratio_x // 1080
scan_x_end = min(410 * self.resolution_ratio_x // 1080, pic_width)
scan_y = 403 * self.resolution_ratio_y // 2400 + self.y_pianyi
# 确保y坐标在有效范围内
if 0 <= scan_y < pic_height:
# 精度优化:同时检查上下几行像素,提高检测准确性
for offset_y in [0, -1, 1, -2, 2]: # 检查当前行及上下2行
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
for x_scaled in range(scan_x_start, scan_x_end):
try:
px = pix[x_scaled, check_y]
# 检查RGB值是否匹配福袋图标颜色(适度放宽范围)
if len(px) >= 3 and 190 <= px[0] <= 206 and 173 <= px[1] <= 196 and 234 <= px[2] <= 250:
# 转换回1080基准坐标
detected_x = int(x_scaled * 1080.0 / max(1, int(self.resolution_ratio_x)))
detected = True
self.last_find_fudai_time = time.time()
break
except (IndexError, TypeError):
continue
if detected:
break
if detected:
break
except Exception as e:
# 像素检测失败,记录但不影响主流程
pass
if detected:
# 额外兜底:防止‘开奖结果’弹窗被错当作福袋图标(例如弹窗区域颜色/像素相近)
try:
# 优化:轻量 OCR 诊断 - 稍微扩大区域确保完整
self.cut_pic(350, 650, 750, 765, '', 'diag_result')
diag_txt = str(self.operation.analyse_pic_word('diag_result') or "")
if any(k in diag_txt for k in ("没有抽中", "抽中福袋", "未中奖", "开奖")):
print(f"[误判防护] 在检测到可能福袋时同时识别到结果弹窗文字,忽略此次福袋检测 diag='{diag_txt}'")
detected = False
except Exception:
# 若诊断失败则继续按原逻辑处理
pass
# 统计:每次“进入直播间”后首次找到福袋图标耗时
try:
enter_ts = float(getattr(self, "_enter_live_ts", 0.0) or 0.0)
except Exception:
enter_ts = 0.0
try:
already = bool(getattr(self, "_enter_live_fudai_logged", False))
except Exception:
already = False
if (enter_ts > 0) and (not already):
try:
dt = float(time.time() - enter_ts)
except Exception:
dt = -1.0
if dt >= 0:
try:
reason = str(getattr(self, "_enter_live_reason", "") or "")
except Exception:
reason = ""
self._enter_live_fudai_logged = True
try:
print("[性能] 进入直播间到识别福袋耗时:{:.2f} 秒 进入原因={}".format(round(dt, 2), reason))
except Exception:
pass
try:
self._log_kv(
"性能",
"进入直播间后找到福袋耗时",
seconds=round(dt, 2),
enter_reason=reason,
fudai_x=int(detected_x or 0),
)
except Exception:
pass
return int(detected_x or 0)
loop += 1
if loop >= 4:
self.deal_robot_analyse()
elif loop < 2 and self.check_zhibo_is_closed():
return False
if loop < max_loops:
self.operation.delay(retry_delay_s)
return False
def check_in_fudai_detail(self) -> bool:
"""判断当前是否处于"福袋详情页"。
优先使用像素快速判定(复用 check_detail_height 的阈值,但不调用其本体以避免打印/人机副作用),
若未命中则做一次轻量 OCR(仅参与按钮区域)兜底。
"""
# 检查缓存(避免短时间内重复检测)
cache_key = "check_in_fudai_detail"
now = time.time()
if cache_key in self._detection_cache:
cached_ts, cached_result = self._detection_cache[cache_key]
if (now - cached_ts) < self._detection_cache_ttl:
return bool(cached_result)
try:
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
try:
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert('RGBA')
except (IOError, OSError, Image.UnidentifiedImageError):
# 截图异常:尝试补一次截图
try:
self.operation.get_screenshot(self.device_id)
pic0 = Image.open(pic1_path)
pic0.load()
pic = pic0.convert('RGBA')
except Exception:
self._detection_cache[cache_key] = (now, False)
return False
pix = pic.load()
width, height = pic.size
x = 536 * self.resolution_ratio_x // 1080
# 边界检查
if not (0 <= x < width):
self._detection_cache[cache_key] = (now, False)
return False
# 三种高度的参与按钮 y(分别对应 3/2/1 个任务),再考虑 y_pianyi 偏移
base_ys = (883, 983, 1058)
y_pianyi_val = int(getattr(self, 'y_pianyi', 0) or 0)
offsets = (0, y_pianyi_val, -y_pianyi_val)
# 优化:先检查最常见的2个任务的情况
for base_y in base_ys:
y0 = base_y * self.resolution_ratio_y // 2400
for dy in offsets:
y = y0 + dy
if not (0 <= y < height):
continue
try:
p = pix[x, y]
if not (isinstance(p, tuple) and len(p) >= 3):
continue
r, g, b = int(p[0]), int(p[1]), int(p[2])
# 参与按钮颜色范围(RGB)
if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84:
self._detection_cache[cache_key] = (now, True)
return True
except (IndexError, TypeError):
continue
except Exception:
pass
# OCR 兜底较重:加节流,避免正常直播页每轮都跑 OCR
try:
min_interval = float(getattr(self, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0)
except Exception:
min_interval = 8.0
try:
now = time.time()
last = float(getattr(self, "_last_detail_ocr_check_ts", 0.0) or 0.0)
if min_interval > 0 and (now - last) < min_interval:
return False
self._last_detail_ocr_check_ts = now
self.cut_pic(306, 2030, 780, 2110, '', 'diag_attend_btn')
t_btn = str(self.operation.analyse_pic_word('diag_attend_btn', 1) or "")
if any(k in t_btn for k in ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")):
return True
except Exception:
pass
return False
def cut_pic(self, x_top=1, y_top=1, x_bottom=2, y_bottom=2, target='', cut_pic_name='', y_pianyi=0):
"""裁剪图片方法"""
self.operation.cut_pic(
(x_top * self.resolution_ratio_x // 1080, y_top * self.resolution_ratio_y // 2400 + y_pianyi),
(x_bottom * self.resolution_ratio_x // 1080, y_bottom * self.resolution_ratio_y // 2400 + y_pianyi),
target,
cut_pic_name)
def _shot_and_diagnose(self, tag="", next_step="", device_id="", diagnose: bool = True, force_diagnose_once: bool = False):
"""统一截图入口:每次截图后输出当前阶段、识别到的关键内容、以及下一步是什么。"""
did = device_id or getattr(self, "device_id", "")
try:
ok = self.operation.get_screenshot(did)
except Exception as e:
print(f"[截图] 截图失败:{e}")
ok = False
# 弹窗守护:有些系统弹窗(例如 vivo 停止充电提醒)会遮挡 UI。
# 若检测到则按一次返回键关闭,避免主流程卡住。
try:
self._popup_back_guard()
except Exception:
pass
stage = getattr(self, "_last_diag_stage", "-")
seen = getattr(self, "_last_diag_seen", "-")
do_diag = bool(diagnose)
if do_diag:
try:
min_interval = float(getattr(self, "screenshot_diagnose_min_interval_seconds", 8.0) or 0.0)
except Exception:
min_interval = 8.0
now = time.time()
last_ts = float(getattr(self, "_last_diag_ts", 0.0) or 0.0)
# force_diagnose_once=True:本次截图必须做一次诊断(用于“只截一次图就能判阶段”的场景)
if bool(force_diagnose_once) or (min_interval <= 0 or (now - last_ts) >= min_interval):
stage, seen = self._diagnose_stage_from_current_screen()
self._last_diag_ts = now
self._last_diag_stage = stage
self._last_diag_seen = seen
# 保留 [截图] 前缀,追加结构化字段,方便定位“此刻在做什么/下一步是什么”
self._log_kv(
"截图",
"截图+阶段诊断",
biaoqian=tag or "-",
stage=stage,
seen=seen,
next=next_step or "-",
ok=int(bool(ok)),
)
return ok
def _popup_back_guard(self) -> bool:
"""检测到特定弹窗时按一次返回键关闭(节流)。
当前仅处理:vivo 设备“停止充电提醒”弹窗(有时会遮挡福袋按钮/导致识别异常)。
"""
try:
min_interval = float(getattr(self, "popup_back_min_interval_seconds", 6.0) or 0.0)
except Exception:
min_interval = 6.0
now = time.time()
try:
last = float(getattr(self, "_last_popup_back_ts", 0.0) or 0.0)
except Exception:
last = 0.0
if min_interval > 0 and (now - last) < min_interval:
return False
# 购物红包弹窗:检测到就点击关闭按钮(530, 1647)
try:
if self._check_shopping_redpacket_popup():
self._last_popup_back_ts = now
self._log_kv("弹窗", "检测到购物红包弹窗:点击关闭按钮", kind="shopping_redpacket", action="click_close")
try:
# 点击关闭按钮坐标 (530, 1647),基于1080x2400分辨率(click方法内部会自动缩放)
self.click(530, 1647)
print(f"检测到购物红包弹窗,点击关闭按钮 -> (530, 1647)")
except Exception:
pass
try:
self.operation.delay(0.8)
except Exception:
pass
return True
except Exception:
pass
# 购物券/新客专享券等底部弹窗:检测到就按返回键
try:
enabled_coupon = bool(getattr(self, "coupon_popup_back_enabled", True))
except Exception:
enabled_coupon = True
if enabled_coupon:
try:
if self._check_coupon_popup():
self._last_popup_back_ts = now
self._log_kv("弹窗", "检测到优惠券弹窗:按返回键关闭", kind="coupon_popup", action="back")
try:
self.operation.click_back(self.device_id)
except Exception:
pass
try:
self.operation.delay(0.8)
except Exception:
pass
return True
except Exception:
pass
# 停止充电弹窗:检测到就按返回键
try:
if self.check_stop_charging():
self._last_popup_back_ts = now
self._log_kv("弹窗", "检测到系统弹窗:按返回键关闭", kind="stop_charging", action="back")
try:
self.operation.click_back(self.device_id)
except Exception:
pass
try:
self.operation.delay(0.8)
except Exception:
pass
return True
except Exception:
pass
return False
def _check_coupon_popup(self) -> bool:
"""检测直播间内的“购物券/新客专享券”等营销弹窗(底部大弹窗)。
设计目标:宁可漏检,不要误判;因此采用 OCR 关键词命中(标题/按钮)。
"""
# 使用当前截图(由 _shot_and_diagnose 刚刚更新),避免额外截图开销
try:
# 标题区域:"一分钟得30元购物券"/"购物券"/"新客专享" 等
self.cut_pic(60, 1260, 1020, 1480, '', 'diag_coupon_title')
t1 = str(self.operation.analyse_pic_word('diag_coupon_title') or "")
except Exception:
t1 = ""
try:
# 按钮区域:"开心收下"/"收下"/"立即领取" 等
self.cut_pic(260, 2080, 820, 2240, '', 'diag_coupon_btn')
t2 = str(self.operation.analyse_pic_word('diag_coupon_btn', 1) or "")
except Exception:
t2 = ""
hay = (t1 + " " + t2).strip()
if not hay:
return False
# 关键词:尽量选择高辨识度且不易出现在其他页面的词
keys_any = (
"购物券",
"新客",
"专享券",
"领取",
"收下",
"开心收下",
)
if any(k in hay for k in keys_any):
# 进一步约束:至少满足“券/新客”之一,减少误判
if ("券" in hay) or ("新客" in hay) or ("购物券" in hay):
return True
return False
def _check_shopping_redpacket_popup(self) -> bool:
"""检测直播间内的"购物红包"弹窗(中央红色弹窗)。
检测区域:(244, 461) 到 (847, 539) 出现"邀你抢购物红包"这几个字。
优化:尝试多种OCR模式,放宽关键词匹配,提高识别成功率。
"""
# 使用当前截图(由 _shot_and_diagnose 刚刚更新),避免额外截图开销
try:
# 检测区域:从(244, 461)到(847, 539)识别"邀你抢购物红包"
# 稍微扩大区域,提高容错性
self.cut_pic(230, 450, 860, 550, '', 'diag_shopping_redpacket')
except Exception:
return False
# 尝试多种OCR模式(change_color=0, 1, 2),提高识别成功率
# change_color=0: 保持彩色(默认,适合红色弹窗)
# change_color=1: 二值化(阈值128,适合对比度高的场景)
# change_color=2: 二值化(阈值180,适合对比度较低的场景)
texts = []
for ocr_mode in [0, 1, 2]:
try:
t = str(self.operation.analyse_pic_word('diag_shopping_redpacket', ocr_mode) or "")
hay = t.strip() if t else ""
if hay:
texts.append(hay)
# 如果当前模式已经识别到关键词,直接返回True,不必继续尝试(优化性能)
# 放宽关键词匹配:只要包含"购物红包"或"邀你抢"等关键词即可
if any(kw in hay for kw in ("邀你抢购物红包", "抢购物红包", "购物红包", "邀你抢", "抢红包")):
return True
except Exception:
continue
# 如果单个模式都没识别到,合并所有识别结果再次检查(提高容错性)
if texts:
combined_text = " ".join(texts).strip()
# 进一步放宽匹配:只要包含关键字的任意组合即可
if any(kw in combined_text for kw in ("购物红包", "邀你抢", "抢红包")):
return True
return False
def _diagnose_stage_from_current_screen(self):
"""仅基于当前截图做轻量诊断(不触发额外截图)。
优化:按常见程度排序检测,优先检测最常见的场景,减少不必要的OCR调用。
"""
# 优化:先检测最常见的场景(直播间),减少OCR调用
# 1. 先快速检测福袋详情页(使用像素检测,最快)
try:
if self.check_in_fudai_detail():
return "FUDai_DETAIL", "像素检测确认"
except Exception:
pass
# 2. 检测抽奖结果弹窗(用户最关心的结果)
t_result = ""
try:
# 优化:稍微扩大区域确保完整
self.cut_pic(350, 650, 750, 765, '', 'diag_result')
t_result = str(self.operation.analyse_pic_word('diag_result') or "")
except Exception:
pass
if t_result and ("没有抽中" in t_result or "抽中福袋" in t_result):
return "FUDai_RESULT", "结果='{}'".format(t_result)
# 3. 检测推荐页面(优先级提高,放在关注列表之前,避免误判)
# 优化:基于关注标签坐标(712, 169)精确定位标签栏区域,提高识别精准度
# 标签栏区域:x方向包含"推荐"、"关注"、"直播"等标签,y方向在标签中心附近
t_recommend = ""
try:
# 精确定位标签栏:基于关注标签(712, 169),标签栏大致在x=400-900, y=140-200
# 缩小区域减少干扰,提高识别精准度(优先保证精准)
self.cut_pic(400, 140, 900, 200, '', 'diag_recommend_title')
# 尝试多种OCR模式,优先使用彩色模式(change_color=0),识别失败再尝试二值化
t_recommend = str(self.operation.analyse_pic_word('diag_recommend_title', 0) or "")
if not t_recommend or ("推荐" not in t_recommend and "关注" not in t_recommend and "直播" not in t_recommend):
# 如果彩色模式识别失败或未识别到关键词,尝试二值化模式(提高对比度)
t_recommend = str(self.operation.analyse_pic_word('diag_recommend_title', 1) or "")
except Exception:
pass
# 也检查"猜你喜欢"区域(通常在底部)
t_guess_like = ""
try:
self.cut_pic(440, 1570, 640, 1640, '', 'diag_guess_like')
t_guess_like = str(self.operation.analyse_pic_word('diag_guess_like', 1) or "")
except Exception:
pass
# 推荐页面判断:
# 1. 如果识别到"推荐"关键词,且同时包含其他标签(如"关注"、"直播"等),通常是推荐页面
# 2. 如果有"猜你喜欢",则是推荐页面
# 3. 如果只有"推荐"且没有明显的列表特征,也是推荐页面
if "推荐" in t_recommend:
# 推荐页面顶部通常会有多个标签(推荐、关注、直播等)
# 如果同时包含"推荐"和其他导航标签,判定为推荐页面
if "直播" in t_recommend or "关注" in t_recommend:
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果有"猜你喜欢",也是推荐页面
if "猜你喜欢" in t_guess_like or "猜你喜欢" in t_recommend:
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend or t_guess_like)
# 如果只有"推荐"关键词,也是推荐页面(推荐页面是默认首页)
return "RECOMMEND_PAGE", "标题='{}'".format(t_recommend)
# 如果没有"推荐"但有"猜你喜欢",也可能是推荐页面
if "猜你喜欢" in t_guess_like:
return "RECOMMEND_PAGE", "标题='{}'".format(t_guess_like)
# 4. 关注列表 / 直播列表(较常见)
# 优化:基于关注标签坐标(712, 169)精确定位标签区域,缩小识别范围提高精准度
t_follow = ""
t_list = ""
try:
# 精确定位关注标签区域:基于坐标(712, 169),标签范围约x=674-749, y=153-185
# 稍微扩大一点区域以提高容错性,但保持精确:x=650-800, y=145-195
self.cut_pic(650, 145, 800, 195, '', 'diag_follow_title')
# 优先使用彩色模式,识别失败再尝试二值化
t_follow = str(self.operation.analyse_pic_word('diag_follow_title', 0) or "")
if not t_follow or "关注" not in t_follow:
t_follow = str(self.operation.analyse_pic_word('diag_follow_title', 1) or "")
except Exception:
pass
try:
# 直播列表标签也在标签栏区域,使用相似的精确区域
self.cut_pic(650, 145, 800, 195, '', 'diag_list_title')
t_list = str(self.operation.analyse_pic_word('diag_list_title', 0) or "")
if not t_list or "正在直播" not in t_list:
t_list = str(self.operation.analyse_pic_word('diag_list_title', 1) or "")
except Exception:
pass
# 记录诊断时看到的"关注页标题",便于后续逻辑复用(避免重复 OCR)
try:
self._last_follow_list_title_text = str(t_follow or "").strip()
except Exception:
self._last_follow_list_title_text = ""
# 注意:如果标题区域包含"推荐",已经在前面判定为推荐页面
# 只有当没有"推荐"关键词时,才判定为关注列表
if "关注" in t_follow and "推荐" not in t_follow:
return "FOLLOW_LIST", "标题='{}'".format(t_follow)
if "正在直播" in t_list:
return "LIVE_LIST", "标题='{}'".format(t_list)
# 4. 福袋详情页(参与按钮区域,OCR兜底)
t_btn = ""
try:
self.cut_pic(306, 2030, 780, 2110, '', 'diag_attend_btn')
t_btn = str(self.operation.analyse_pic_word('diag_attend_btn', 1) or "")
except Exception:
pass
if t_btn and any(k in t_btn for k in ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看")):
return "FUDai_DETAIL", "参与按钮='{}'".format(t_btn)
# 粉丝团加入页(点击“加入粉丝团/点亮粉丝团”后可能进入单独页面)
t_fc = ""
try:
self.cut_pic(200, 1940, 880, 2140, '', 'diag_fansclub_join')
t_fc = str(self.operation.analyse_pic_word('diag_fansclub_join', 1) or "")
except Exception:
pass
if "加入粉丝团" in t_fc:
return "FANSCLUB_JOIN", "按钮='{}'".format(t_fc)
# 直播间已结束
t_status = ""
try:
self.cut_pic(350, 100, 740, 300, '', 'diag_status')
t_status = str(self.operation.analyse_pic_word('diag_status') or "")
except Exception:
pass
if "已结束" in t_status:
return "LIVE_CLOSED", "状态='{}'".format(t_status)
# 避免在日志中出现无意义内容:两者都为空时不输出识别字段
if (not str(t_list or "").strip()) and (not str(t_follow or "").strip()):
return "LIVE_OR_UNKNOWN", ""
return "LIVE_OR_UNKNOWN", "列表标题='{}' 关注标题='{}'".format(t_list, t_follow)
def check_have_robot_analyse(self):
"""检查是否存在人机校验"""
self.cut_pic(130, 790, 680, 870, '', 'zhibo_yanzheng')
result = self.operation.analyse_pic_word('zhibo_yanzheng', 1)
if "验证" in result:
print("存在滑动图片人机校验,需要等待完成验证.")
return 1
elif "形状相同" in result:
print("存在点击图片人机校验,需要等待完成验证.")
return 2
self.cut_pic(340, 1415, 700, 1518, '', 'zhibo_yanzheng')
result = self.operation.analyse_pic_word('zhibo_yanzheng')
if "开始检测" in result:
print("存在人脸识别人机校验,需要等待完成验证.")
return 3
return False
def deal_swipe_robot_analyse(self, distance=400):
"""处理滑动图片的人机验证"""
if distance:
targetx = (222 + distance) * self.resolution_ratio_x // 1080
else:
targetx = 622 * self.resolution_ratio_x // 1080
self.swipe(222, 1444, targetx, 1444, 300)
print("滑轨滑动{}距离解锁人机验证".format(distance))
self.operation.delay(1)
def deal_robot_analyse(self):
"""处理人机校验,包含各种情况"""
swipe_times = 0
while swipe_times < 10:
robot_result = self.check_have_robot_analyse()
if robot_result == 1:
distance = self.check_robot_pic_distance()
self.deal_swipe_robot_analyse(distance)
self.operation.delay(10)
self._shot_and_diagnose("人机校验", "校验后复查", self.device_id)
elif robot_result == 2:
print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟")
self.click(910, 800) # 点击关闭
self.operation.delay(1800)
break
elif robot_result == 3:
print("无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟")
self.operation.click_back(self.device_id)
self.operation.delay(2)
self.operation.click_back(self.device_id)
self.operation.delay(1800)
break
else:
break
swipe_times += 1
if swipe_times >= 10:
print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟")
self.click(910, 800) # 点击关闭
self.operation.delay(1800)
def swipe(self, left_up_x=0, left_up_y=0, right_down_x=1080, right_down_y=1500, steps=200):
"""调整比例后划动屏幕"""
left_up_x = left_up_x * self.resolution_ratio_x // 1080
right_down_x = right_down_x * self.resolution_ratio_x // 1080
left_up_y = left_up_y * self.resolution_ratio_y // 2400
right_down_y = right_down_y * self.resolution_ratio_y // 2400
self.operation.swipe(self.device_id, left_up_x, left_up_y, right_down_x, right_down_y, steps)
def click(self, x=500, y=500):
"""调整比例后点击坐标位置"""
x = x * self.resolution_ratio_x // 1080
y = y * self.resolution_ratio_y // 2400
self.operation.click(self.device_id, x, y)
def reflash_zhibo(self):
"""在关注列表,下拉刷新直播间"""
print("下划刷新直播间列表")
self.swipe(760, 700, 760, 1500)
self.operation.delay(5)
def check_in_follow_list(self):
"""判断是否界面在我的关注的列表页"""
# 优化:扩大识别区域,识别整行文字
# 注意:直播间顶部也可能出现"关注"按钮(会误判)。
# 扩大区域:从左边界(420->300)到右边界(660->780),扩大高度(220->240)以包含完整文字
self.cut_pic(300, 120, 780, 240, '', 'zhibo_follow_list_title')
zhibo_list_title = self.operation.analyse_pic_word('zhibo_follow_list_title')
try:
self._last_follow_list_title_text = str(zhibo_list_title or "").strip()
except Exception:
self._last_follow_list_title_text = ""
if "关注" in str(zhibo_list_title or ""):
print("当前界面在用户关注列表")
return True
return False
def check_in_zhibo_list(self):
"""检查是否当前在关注的直播列表"""
# 优化:扩大识别区域,识别整行文字
# 扩大区域:从左边界(400->350)到右边界(675->730),扩大高度(230->250)以包含完整文字
self.cut_pic(350, 135, 730, 250, '', 'zhibo_list_title')
zhibo_list_title = self.operation.analyse_pic_word('zhibo_list_title')
if "正在直播" in zhibo_list_title:
print("当前界面已经在关注的直播间列表")
return True
return False
def check_zhibo_is_closed(self):
"""检查当前直播间是否关闭"""
self.cut_pic(350, 100, 740, 300, '', 'zhibo_status')
zhibo_list_title = self.operation.analyse_pic_word('zhibo_status')
if "已结束" in zhibo_list_title:
print("当前直播间已关闭")
return True
print("当前直播间正常进行中")
return False
def check_zhibo_is_closed_guess_whatyoulike(self):
"""检查当前直播间是否关闭-判断猜你喜欢的位置"""
self.cut_pic(440, 1570, 640, 1640, '', 'zhibo_status')
zhibo_list_title = self.operation.analyse_pic_word('zhibo_status', 1)
if "猜你喜欢" in zhibo_list_title:
print("当前直播间已关闭")
return True
return False
def back_to_zhibo_list(self):
"""功能初始化,回到直播间列表"""
click_back_times = 0
while click_back_times < 4:
self._shot_and_diagnose("回到直播列表", "判断所在页面", self.device_id)
if self.check_in_zhibo_list():
return False
elif self.check_in_follow_list():
self.click(390, 590)
print("点击打开直播间的列表")
self.operation.delay(2)
return False
self.operation.click_back(self.device_id)
self.operation.delay(2)
click_back_times += 1
def into_zhibo_from_list(self):
"""从直播列表进入直播间"""
# 按用户指定:不走任何“打开直播间列表/判断列表是否为空”等旧路径,
# 统一只执行固定流程进入直播间。
try:
self._shot_and_diagnose("从列表进直播", "固定流程进入直播间(715,166)->(109,376)x2", self.device_id, diagnose=True, force_diagnose_once=True)
except Exception:
pass
try:
st = str(getattr(self, "_last_diag_stage", "") or "")
seen = str(getattr(self, "_last_diag_seen", "") or "")
except Exception:
st, seen = "", ""
self._log_kv("流程", "进入直播间:固定流程", stage=st or "-", seen=seen or "-")
# Step1: 切换到直播列表
print("固定流程:点击715,166切到直播列表")
self.click(715, 166)
self.operation.delay(0.8)
# Step2: 连点两次进入直播间
print("固定流程:点击109,376两次进入直播间")
self.click(109, 376)
self.operation.delay(0.6)
self.click(109, 376)
try:
self._mark_enter_live("fixed_enter_live")
except Exception:
pass
self.operation.delay(2.2)
return
def check_zhibo_list_have_zhibo(self):
"""检查直播列表是否存在直播的内容"""
self._shot_and_diagnose("直播列表", "判定列表是否为空", self.device_id)
path = os.path.dirname(__file__) + '/pic'
pic1_path = path + '/screenshot.png'
pic = Image.open(pic1_path)
# pic_new = Image.open(cut_pic_path)
pic_new = pic.convert('RGBA')
pix = pic_new.load()
if pix[290 * self.resolution_ratio_x // 1080, 490 * self.resolution_ratio_y // 2400][0] == 255 and \
pix[290 * self.resolution_ratio_x // 1080, 490 * self.resolution_ratio_y // 2400][1] == 255 and \
pix[290 * self.resolution_ratio_x // 1080, 490 * self.resolution_ratio_y // 2400][2] == 255:
print('直播间列表为空')
return False
print('直播间列表存在直播的内容')
return True
def check_zhibo_have_popup(self):
"""判断直播间是否弹出了节假日红包弹窗"""
self.cut_pic(425, 880, 660, 960, '', 'zhibo_hongbao')
zhibo_list_title = self.operation.analyse_pic_word('zhibo_hongbao', 1)
if "最高金额" in zhibo_list_title:
print("直播间有红包弹窗")
return True
return False
def check_no_fudai_time(self):
"""无福袋等待时间检查"""
if not bool(getattr(self, "no_fudai_watchdog_enabled", False)):
return 0
if 3 <= self.operation.get_current_hour() <= 6: # 如果是凌晨3-6点
self.last_find_fudai_time = 0.00
elif self.last_find_fudai_time == 0.00 or self.last_find_fudai_time == 0: # 如果过了不挂机时间,把当前时间赋值给上次找到福袋的时间
self.last_find_fudai_time = time.time()
if self.last_find_fudai_time > 0:
current_time = time.time()
wait_time = current_time - self.last_find_fudai_time
wait_time = round(wait_time, 1)
if wait_time > 18000:
wait_time = 0
if wait_time > 1:
print("距离上一次识别到福袋已经过去{}秒".format(wait_time))
return wait_time
return 0
def get_fudai_contain(self, renwu=2):
"""获取福袋的内容和倒计时"""
def _parse_mm_ss(text: str):
m = re.search(r"(\d{1,2})[::](\d{2})", str(text or ""))
if not m:
return None
try:
return int(m.group(1)), int(m.group(2))
except Exception:
return None
def _extract_2digits(text: str) -> str:
digits = ''.join(ch for ch in str(text or '') if ch.isdigit())
if len(digits) >= 2:
return digits[:2]
if len(digits) == 1:
return '0' + digits
return ''
def _read_countdown_split(box: tuple[int, int, int, int]) -> str:
"""将倒计时区域按三等分切成“分钟段/秒段/后开奖段”,分别OCR分钟与秒,组合为 mm:ss。"""
try:
x1, y1, x2, y2 = box
w = max(1, int(x2 - x1))
seg = max(1, w // 3)
# 前 1/3:分钟;中 1/3:秒(第三段通常包含“后开奖”)
self.cut_pic(x1, y1, x1 + seg, y2, '', 'fudai_countdown_m', self.y_pianyi)
self.cut_pic(x1 + seg, y1, x1 + 2 * seg, y2, '', 'fudai_countdown_s', self.y_pianyi)
mm_raw = self.operation.analyse_pic_word('fudai_countdown_m', 0)
ss_raw = self.operation.analyse_pic_word('fudai_countdown_s', 0)
mm = _extract_2digits(mm_raw)
ss = _extract_2digits(ss_raw)
if mm and ss:
return f"{mm}:{ss}"
except Exception:
return ''
return ''
def _extract_participants_and_clean(text: str):
if not text:
return 0, 0, ''
compact = re.sub(r"\s+", "", str(text))
# 例如:共1份1173人已参与
copies = 0
participants = 0
m = re.search(r"共(\d+)份", compact)
if m:
copies = int(m.group(1))
m = re.search(r"(\d+)人已参与", compact)
if m:
participants = int(m.group(1))
# 清理掉份数/参与人数等尾巴,避免干扰关键词匹配
cleaned = re.sub(r"共\d+份", "", compact)
cleaned = re.sub(r"\d+人已参与", "", cleaned)
return participants, copies, cleaned
countdown_box = None
if renwu == 2: # 如果是2个任务的
# 优化:稍微缩小宽度(1000->980),增加高度(1460->1470),减少右侧干扰,确保内容完整
self.cut_pic(390, 1240, 980, 1470, '', 'fudai_content', self.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字
countdown_box = (390, 1110, 690, 1230)
self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度(1560->1580),确保包含"元"等单位文字
self.cut_pic(390, 1460, 1000, 1580, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格
elif renwu == 1: # 如果是1个任务的
# 优化:稍微缩小宽度,增加高度,减少干扰
self.cut_pic(390, 1300, 980, 1530, '', 'fudai_content', self.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度,确保完整
countdown_box = (390, 1180, 690, 1300)
self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度,包含单位
self.cut_pic(390, 1520, 1000, 1630, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格
elif renwu == 3: # 如果是3个任务的
# 优化:稍微缩小宽度,增加高度
self.cut_pic(390, 1160, 980, 1390, '', 'fudai_content', self.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度
countdown_box = (390, 1010, 690, 1130)
self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度
self.cut_pic(390, 1380, 1000, 1490, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格
else:
# 优化:稍微缩小宽度,增加高度
self.cut_pic(390, 1600, 980, 1830, '', 'fudai_content', self.y_pianyi) # 福袋内容详情
# 优化:稍微扩大高度
countdown_box = (390, 1460, 690, 1580)
self.cut_pic(*countdown_box, '', 'fudai_countdown', self.y_pianyi) # 完整福袋详情倒计时
# 优化:增加高度
self.cut_pic(390, 1820, 1000, 1930, '', 'fudai_value', self.y_pianyi) # 奖品价值/价格
fudai_content_raw = self.operation.analyse_pic_word('fudai_content', 0)
participants, copies, fudai_content_text = _extract_participants_and_clean(fudai_content_raw)
self._log_kv("福袋", "识别福袋内容", level="INFO", content=fudai_content_text[:60] if fudai_content_text else "未识别到")
# 记录进入直播间到识别到福袋的耗时(仅记录一次)
try:
if getattr(self, "_enter_live_ts", 0.0) and not getattr(self, "_enter_live_fudai_logged", False):
try:
secs = float(time.time() - float(self._enter_live_ts or 0.0))
except Exception:
secs = -1.0
reason = str(getattr(self, "_enter_live_reason", "") or "")
# 结构化输出,方便统一日志与后端统计解析
self._log_kv("性能", "进入直播间到识别福袋耗时", seconds=round(secs, 2), enter_reason=reason)
try:
self._enter_live_fudai_logged = True
except Exception:
pass
except Exception:
pass
if copies:
self._log_kv("福袋", "识别福袋信息", copies=copies, participants=participants if participants else 0)
# 倒计时:优先用“分割小区域”快速 OCR(更快、更稳定),失败再 OCR 整块。
time_text = ''
try:
if countdown_box:
split_raw = _read_countdown_split(countdown_box)
split_text = normalize_countdown_text(split_raw)
if _parse_mm_ss(split_text):
time_text = split_text
except Exception:
pass
if not time_text:
time_raw = self.operation.analyse_pic_word('fudai_countdown', 0)
time_text = normalize_countdown_text(time_raw)
self._log_kv("福袋", "识别倒计时", countdown=time_text if time_text else "未识别到")
value_raw = self.operation.analyse_pic_word('fudai_value', 0)
prize_value_yuan = extract_prize_value_yuan(value_raw)
if prize_value_yuan:
if float(prize_value_yuan).is_integer():
show_value = int(prize_value_yuan)
else:
show_value = prize_value_yuan
self._log_kv("福袋", "识别奖品价值", value_yuan=show_value)
return fudai_content_text, time_text, participants, copies, prize_value_yuan
def check_contain(self, contains=''):
"""检查福袋内容是否是想要,从配置文件config中读取"""
if 0 < self.operation.get_current_hour() < 7:
print("凌晨不对福袋内容做要求")
return False
for contain in self.contains_want:
if contain in contains:
print("福袋内容是想要的")
return False
for contain in self.contains_not_want:
if contain in contains:
print("福袋内容不是想要的")
return True
print("福袋内容未明确是否想要")
return False
def attend_choujiang(self):
"""点击参与抽奖"""
self.last_attend_fail_reason = ""
click_times = 0
while click_times < 2:
self.cut_pic(306, 2030, 780, 2110, '', 'attend_button') # 参与福袋抽奖的文字
attend_button_text = self.operation.analyse_pic_word('attend_button', 1)
self._log_kv("参与", "识别参与按钮", text=attend_button_text)
if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖
self._log_kv("参与", "已参与,等待开奖", result="已参与")
self.click(500, 470) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif "还需看播" in attend_button_text: # 如果识别到已经参与抽奖
# 策略:检测到需要看播时长则默认不参与
self.last_attend_fail_reason = "watch_required"
self._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛")
self.click(500, 470) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "无法参与" in attend_button_text: # 如果识别到无法参与抽奖
self._log_kv("参与", "无法参与(条件不满足)", result="无法参与")
self.click(500, 470) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "时长不足" in attend_button_text: # 如果识别到无法参与抽奖
self._log_kv("参与", "无法参与(看播时长不足)", result="时长不足")
self.click(500, 470) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "评论" in attend_button_text:
self.click(500, 2060) # 点击参与抽奖
self._log_kv("参与", "点击参与抽奖", action="点击参与", mode="评论")
return True
elif "参与抽奖" in attend_button_text:
self.click(500, 2060) # 点击参与抽奖
self._log_kv("参与", "点击参与抽奖", action="点击参与", mode="普通")
return True
elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text:
# 需要粉丝团门槛:先点击尝试进入加入/点亮流程
self.last_attend_fail_reason = "fansclub_required"
self.click(500, 2060) # 点击加入粉丝团/点亮粉丝团按钮
self._log_kv("参与", "粉丝团门槛:已点击加入按钮", result="需要粉丝团")
self.operation.delay(2)
if not self.auto_join_fansclub:
self._log_kv("参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15)
self.operation.delay(15)
# 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。
def _recover_to_fudai_detail_after_fansclub(max_steps: int = 4) -> bool:
for i in range(int(max_steps or 4)):
try:
self._shot_and_diagnose("粉丝团", "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), self.device_id)
except Exception:
pass
try:
st, seen = self._diagnose_stage_from_current_screen()
except Exception:
st, seen = "", ""
if st == "FUDai_DETAIL":
return True
if st == "FANSCLUB_JOIN":
# 在加入页点击底部“加入粉丝团”按钮(与详情页按钮同位置)
self._log_kv("参与", "粉丝团加入页:点击加入粉丝团", stage=st, seen=seen, attempt=i + 1)
try:
self.click(500, 2060)
except Exception:
pass
self.operation.delay(2)
# 尝试返回到详情
try:
self.operation.click_back(self.device_id)
self.operation.delay(1)
except Exception:
pass
continue
# 已经回到直播间/列表时:不要继续按返回键,避免退出直播
if st in ("LIVE_OR_UNKNOWN", "FOLLOW_LIST", "LIVE_LIST"):
self._log_kv("参与", "已离开福袋详情:停止继续返回", stage=st, seen=seen)
return False
# 其它未知弹窗:尝试一次返回
self._log_kv("参与", "粉丝团流程:尝试返回", stage=st, seen=seen)
try:
self.operation.click_back(self.device_id)
self.operation.delay(1)
except Exception:
pass
return False
_recover_to_fudai_detail_after_fansclub(4)
# 加入后再判定一次按钮文本,看是否已变为可参与/已参与
self._shot_and_diagnose("福袋详情", "加入粉丝团后复查参与按钮", self.device_id)
self.cut_pic(306, 2030, 780, 2110, '', 'attend_button')
attend_button_text2 = self.operation.analyse_pic_word('attend_button', 1)
self._log_kv("参与", "加入粉丝团后复查按钮", text=attend_button_text2)
if "参与成功" in attend_button_text2 or "还需看播" in attend_button_text2:
if "还需看播" in attend_button_text2:
self.last_attend_fail_reason = "watch_required"
self._log_kv("参与", "加入粉丝团后仍需看播:默认不参与", result="看播门槛")
self.click(500, 470)
self.operation.delay(1)
return False
self._log_kv("参与", "已参与成功", result="已参与")
self.click(500, 470)
self.operation.delay(1)
return True
if "评论" in attend_button_text2 or "参与抽奖" in attend_button_text2 or "开始观看" in attend_button_text2:
self.click(500, 2060)
self._log_kv("参与", "加入粉丝团后点击参与抽奖", action="点击参与")
return True
# 仍然是粉丝团门槛或识别失败:安全退出当前页面/详情,交由外层策略决定
self._log_kv("参与", "粉丝团门槛仍未解决:退出并返回失败", result="未解决")
try:
self.operation.click_back(self.device_id)
self.operation.delay(0.8)
except Exception:
pass
try:
self.click(500, 470)
self.operation.delay(0.8)
except Exception:
pass
return False
elif "开始观看" in attend_button_text:
# 多数情况下“开始观看”意味着需要先看播满足门槛;按策略默认不参与
self.last_attend_fail_reason = "watch_required"
self._log_kv("参与", "需要开始观看/看播门槛:默认不参与", result="看播门槛")
self.click(500, 470)
self._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif "活动已结束" in attend_button_text:
self.click(500, 440) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "活动已结束:关闭详情", result="已结束")
return False
elif "开通店铺会员" in attend_button_text:
self.operation.click_back(self.device_id)
self.operation.delay(1)
self.click(500, 440) # 点击刚才打开福袋的旁边位置
self._log_kv("参与", "店铺会员弹窗:关闭", result="会员弹窗")
self.operation.delay(1)
return False
else:
self._log_kv("参与", "参与按钮文本未匹配", result="未匹配", text=attend_button_text)
click_times = 2
return False
self._log_kv("参与", "参与抽奖多次点击失败", result="多次失败")
return False
def check_lucky_draw_result(self):
"""判定福袋抽奖的结果
优化:
- 添加OCR结果缓存,避免重复识别
- 优化识别顺序(先识别最常见的"没有抽中")
- 速度优化:减少不必要的截图和OCR调用
"""
# 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过)
cache_key = ('lucky_draw_result', 0)
now = time.time()
need_screenshot = True
# 检查缓存是否有效
if cache_key in self._ocr_cache:
cached_ts, cached_result = self._ocr_cache[cache_key]
# 如果缓存还在有效期内,且结果明确(包含"没有抽中"或"抽中"),可以复用
if (now - cached_ts) < 0.5 and cached_result and ("没有抽中" in cached_result or "抽中福袋" in cached_result):
need_screenshot = False
if need_screenshot:
self._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", self.device_id)
# 优化:稍微扩大区域(655->650, 755->765),确保包含完整的开奖结果文字
self.cut_pic(350, 650, 750, 765, '', 'lucky_draw_result') # 没有抽中福袋位置
# 诊断开始时间
t0 = time.time()
# 检查缓存
if cache_key in self._ocr_cache:
cached_ts, cached_result = self._ocr_cache[cache_key]
if (now - cached_ts) < self._ocr_cache_ttl:
lucky_draw_result = cached_result
else:
lucky_draw_result = self.operation.analyse_pic_word('lucky_draw_result')
self._ocr_cache[cache_key] = (now, lucky_draw_result)
else:
lucky_draw_result = self.operation.analyse_pic_word('lucky_draw_result')
self._ocr_cache[cache_key] = (now, lucky_draw_result)
dur = time.time() - t0
try:
brief = (lucky_draw_result or "").replace("\n", " ")[:140]
except Exception:
brief = ""
print(f"[开奖诊断] lucky_draw_result=" + repr(brief) + f" ocr_dur={dur:.2f}s")
if "没有抽中" in (lucky_draw_result or ""):
# 速度优化:使用缓存避免重复OCR
cache_key2 = ('no_award_confirm', 0)
if cache_key2 in self._ocr_cache:
cached_ts2, cached_result2 = self._ocr_cache[cache_key2]
if (now - cached_ts2) < self._ocr_cache_ttl:
no_award_confirm = cached_result2
else:
t1 = time.time()
# 优化:稍微扩大区域(1200->1195, 1350->1355),确保按钮文字完整
self.cut_pic(340, 1195, 740, 1355, '', 'no_award_confirm') # 我知道了按钮的位置
no_award_confirm = self.operation.analyse_pic_word('no_award_confirm')
self._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
dur2 = time.time() - t1
else:
t1 = time.time()
self.cut_pic(340, 1200, 730, 1350, '', 'no_award_confirm') # 我知道了按钮的位置
no_award_confirm = self.operation.analyse_pic_word('no_award_confirm')
self._ocr_cache[cache_key2] = (time.time(), no_award_confirm)
dur2 = time.time() - t1
try:
dur2
except NameError:
dur2 = 0.0
try:
brief2 = (no_award_confirm or "").replace("\n", " ")[:140]
except Exception:
brief2 = ""
print(f"[开奖诊断] no_award_confirm=" + repr(brief2) + f" ocr_dur={dur2:.2f}s")
if "我知道了" in (no_award_confirm or ""):
return 1
elif "领取并使用" in (no_award_confirm or ""):
return 2
return 3
elif "抽中福袋" in (lucky_draw_result or ""):
print("恭喜中奖了!")
# 速度优化:优先检测第一个常见位置,命中即返回
y_value = [1438, 1490]
for y in y_value:
cache_key3 = (f'have_read_user_agreement_{y}', 0)
have_read_user_agreement = None
if cache_key3 in self._ocr_cache:
cached_ts3, cached_result3 = self._ocr_cache[cache_key3]
if (now - cached_ts3) < self._ocr_cache_ttl:
have_read_user_agreement = cached_result3
if not have_read_user_agreement:
t2 = time.time()
# 优化:稍微扩大区域(y±30->y±35),确保协议文字完整识别
self.cut_pic(280, y - 35, 670, y + 35, '', f'have_read_user_agreement_{y}') # 已经阅读并同意用户协议
have_read_user_agreement = self.operation.analyse_pic_word(f'have_read_user_agreement_{y}')
self._ocr_cache[cache_key3] = (time.time(), have_read_user_agreement)
dur3 = time.time() - t2
try:
brief3 = (have_read_user_agreement or "").replace("\n", " ")[:140]
except Exception:
brief3 = ""
print(f"[开奖诊断] have_read_user_agreement=" + repr(brief3) + f" ocr_dur={dur3:.2f}s")
else:
dur3 = 0.0
if "已阅读" in (have_read_user_agreement or ""):
return y
return False
def check_have_reward_notice_confirm(self):
"""判断是否有领奖的二次确认提醒"""
self._shot_and_diagnose("领奖确认", "识别是否有我知道了", self.device_id)
self.cut_pic(370, 1350, 680, 1440, '', 'reward_notice_confirm') # 提醒领取奖品的弹窗
reward_notice_confirm = self.operation.analyse_pic_word('reward_notice_confirm', 1)
if "我知道了" in reward_notice_confirm:
print("存在奖品领取提醒")
return True
return False
def check_in_order_confirm_page(self):
"""判断是否在中奖下单后的购买成功的页面"""
self._shot_and_diagnose("下单结果", "识别是否购买成功页", self.device_id)
self.cut_pic(370, 120, 700, 220, '', 'order_confirm') # 提醒领取奖品的弹窗
order_confirm = self.operation.analyse_pic_word('order_confirm')
if "购买成功" in order_confirm:
print("福袋商品下单成功!")
return True
return False
def get_reward(self, reward_y=0):
"""中奖后领奖然后返回"""
self.operation.save_reward_pic(self.device_id)
self.click(243, reward_y) # 勾选协议
self.operation.delay(1)
self.click(540, reward_y - 140) # 点击领取
print("勾选协议,点击领取奖品")
self.operation.delay(5)
self.click(886, 2170) # 点击下单
print("点击下单")
self.operation.delay(10)
while self.check_in_order_confirm_page():
# self.click(80, 180) # 点击回退按钮
self.operation.click_back(self.device_id)
print("点击回退按钮")
self.operation.delay(4)
print("下完单返回到直播间")
self.operation.delay(4)
if self.check_lucky_draw_result():
print("领奖弹窗未关闭,点击关闭弹窗")
self.click(540, reward_y + 180)
print("点击坐标位置:540 {}关闭领奖弹窗".format((reward_y + 180) * self.resolution_ratio_y // 2400))
self.operation.delay(2)
self.operation.save_reward_pic(self.device_id)
print("保存关闭领奖弹窗后的截图")
self.operation.click_back(self.device_id)
self.operation.delay(2)
if self.check_have_reward_notice_confirm():
print("提醒领奖弹窗未关闭,点击我知道了,关闭弹窗")
self.click(540, 1400) # 点击我知道了
self.operation.delay(2)
self.operation.delay(30)
print("关闭中奖提醒后等待30S")
def deal_battery_level(self):
"""针对电量不足的情况做处理"""
while self.operation.get_battery_level(self.device_id) < 30:
print("设备电量较低,退出到直播列表,等待电量恢复后继续挂机")
self.back_to_zhibo_list()
self.operation.delay(1800) # 挂机30分钟
def check_stop_charging(self):
"""针对vivo设备,判断长时间连接弹出停止充电的弹窗"""
self.cut_pic(225, 1951, 865, 2051, '', 'charging_stop_notice')
charging_stop_notice = self.operation.analyse_pic_word('charging_stop_notice')
if "充电" in charging_stop_notice:
print("设备弹出停止充电提醒!")
return True
return False
def fudai_choujiang(self, device_id="", y_pianyi=0, needswitch=False,
wait_minutes=15):
"""福袋抽奖主逻辑,默认不切换直播间"""
print("[启动] fudai_choujiang 开始执行")
self.device_id = device_id
self.y_pianyi = y_pianyi
self.resolution_ratio_x, self.resolution_ratio_y = self.operation.get_device_resolution(self.device_id)
print("[启动] 设备分辨率获取完成,开始初始化变量")
wait_times = 0 # 当前直播间的等待次数,累计4次没有福袋,则切换直播间
swipe_times = 0 # 向上滑动的次数,当超出一定值,退出返回直播列表
fudai_not_open_times = 0 # 无法打开福袋的次数
# 高价值福袋预约队列:记录多个预约,按开奖时间顺序依次回退
# item: {future_ts, prize_value_yuan, content, pos_seen, created_ts}
reservations = []
room_pos = 0 # 当前“直播间位置”计数:上划 +1,下滑 -1(仅在本次连续切换过程中有效)
reservation_focus_until_ts = 0.0 # 回退到预约直播间后,在该时间前不允许上划离开
reservation_after_action_pending = False
current_room_title = "" # 最近一次 OCR 识别到的直播间名(用于 Web 核对)
current_room_title_raw = "" # 最近一次 OCR 识别到的直播间名原文(未清洗,用于核对)
reset_to_list_after_reservations = False # 达到“无福袋切换阈值”后,等待预约处理完再回到列表第一个直播间
# 高价值直播间回访表(仅在本次连续切换过程中有效):key=直播间名(清洗后)
high_value_room_watch = {}
revisit_forced_x = None # 回访过程中如果已确认该直播间存在福袋,则把 x 提前算好供后续流程复用
# 回退速度参数:每次回退滑动后的等待(秒)。值越小越快,但过小可能导致 UI 未稳定。
# 行为:当启用回退校验时使用较慢的默认值(保持兼容);否则使用可配置的“快速回退”值以加快速度。
try:
verify_delay = float(getattr(self, "reservation_back_swipe_delay_seconds", 1.2) or 1.2)
except Exception:
verify_delay = 1.2
try:
fast_delay = getattr(self, "reservation_back_swipe_delay_fast_seconds", None)
if fast_delay is not None:
fast_delay = float(fast_delay)
except Exception:
fast_delay = None
# 选择:若启用了回退校验,保持原来的(较慢)延迟;否则使用用户配置的快速延迟(若未配置则回退到原始值)。
use_fast = not bool(getattr(self, "reservation_back_verify_enabled", False))
if use_fast and (fast_delay is not None):
reservation_back_swipe_delay_s = fast_delay
else:
reservation_back_swipe_delay_s = verify_delay
if reservation_back_swipe_delay_s < 0.4:
reservation_back_swipe_delay_s = 0.4
# 切换直播间后的等待(秒):原本固定 5 秒会显著拖慢整体节奏
try:
post_switch_delay_s = float(getattr(self, "post_switch_delay_seconds", 1.2) or 1.2)
except Exception:
post_switch_delay_s = 1.2
if post_switch_delay_s < 0.6:
post_switch_delay_s = 0.6
# 预约队列状态:写入文件(跨进程可读)
def _write_reservations_state(reason: str = "") -> None:
try:
state_path = getattr(self, "_reservations_state_path", "")
if not state_path:
state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
items = []
for r in reservations:
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 = ""
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 ""),
}
)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"room_pos": int(room_pos),
"current_room_title": str(current_room_title or ""),
"current_room_title_raw": str(current_room_title_raw or ""),
"reservations": items,
}
tmp = state_path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
os.replace(tmp, state_path)
except Exception:
pass
# 高价值直播间永久记录:写入文件(跨进程可读,跨运行持久化)
def _load_high_value_rooms_map() -> dict:
path = os.path.join(os.path.dirname(__file__), "state", "high_value_rooms.json")
try:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
# 兼容两种格式:{"rooms": [...]} 或 直接是 [...]
rooms = None
if isinstance(data, dict):
rooms = data.get("rooms")
elif isinstance(data, list):
rooms = data
out: dict[str, dict] = {}
if isinstance(rooms, list):
for it in rooms:
if not isinstance(it, dict):
continue
key = str(it.get("room_title") or "").strip()
if not key:
continue
out[key] = dict(it)
return out
except Exception:
return {}
def _write_high_value_rooms_state(rooms_map: dict, reason: str = "") -> None:
try:
state_path = os.path.join(os.path.dirname(__file__), "state", "high_value_rooms.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
rooms = []
for k, v in (rooms_map or {}).items():
if not k:
continue
item = dict(v or {})
item["room_title"] = str(k)
rooms.append(item)
rooms.sort(key=lambda x: float(x.get("last_seen_ts") or 0.0), reverse=True)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"total": int(len(rooms)),
"rooms": rooms,
}
tmp = state_path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
os.replace(tmp, state_path)
except Exception:
pass
print("[启动] 开始加载高价值直播间映射")
high_value_rooms_map = _load_high_value_rooms_map()
print(f"[启动] 高价值直播间映射加载完成,共 {len(high_value_rooms_map)} 个")
# 本次运行记录的高价值直播间 key 集合(用于可选的"仅回访本次运行记录"逻辑)
run_high_value_rooms: set = set()
def _touch_high_value_room(
title_norm: str,
title_raw: str,
prize_value_yuan: float,
reason: str = "",
increment: bool = True,
key_kind: str = "norm",
content: str = "",
pos_seen: int | None = None,
alias_norm: str = "",
alias_raw: str = "",
merged_from: str = "",
merged_ratio: float | None = None,
) -> None:
nonlocal high_value_rooms_map
try:
key = str(title_norm or "").strip()
except Exception:
key = ""
if not key:
return
now0 = time.time()
ex = high_value_rooms_map.get(key) or {}
def _append_unique_list_field(field: str, val: str, cap: int = 8) -> None:
if not val:
return
try:
arr = ex.get(field)
if not isinstance(arr, list):
arr = []
if val not in arr:
arr.insert(0, val)
if len(arr) > cap:
arr = arr[:cap]
ex[field] = arr
except Exception:
pass
if float(ex.get("first_seen_ts") or 0.0) <= 0:
ex["first_seen_ts"] = now0
ex["last_seen_ts"] = now0
if "seen_count" not in ex:
ex["seen_count"] = 0
if increment:
try:
ex["seen_count"] = int(ex.get("seen_count") or 0) + 1
except Exception:
ex["seen_count"] = 1
if pos_seen is not None:
try:
ex["pos_seen"] = int(pos_seen)
except Exception:
pass
ex["pos_updated_ts"] = now0
if title_raw:
ex["room_title_raw_last"] = str(title_raw)
if alias_raw:
_append_unique_list_field("alias_raw", str(alias_raw), cap=8)
if alias_norm and alias_norm != key:
_append_unique_list_field("alias_norm", str(alias_norm), cap=8)
if merged_from and merged_from != key:
ex["merged_from_last"] = str(merged_from)
if merged_ratio is not None:
try:
ex["merged_ratio_last"] = float(merged_ratio)
except Exception:
pass
if key_kind:
ex["key_kind"] = str(key_kind)
if content:
ex["last_content"] = str(content)
try:
pv = float(prize_value_yuan or 0.0)
except Exception:
pv = 0.0
ex["last_prize_value_yuan"] = pv
try:
ex["max_prize_value_yuan"] = max(float(ex.get("max_prize_value_yuan") or 0.0), pv)
except Exception:
ex["max_prize_value_yuan"] = pv
high_value_rooms_map[key] = ex
_write_high_value_rooms_state(high_value_rooms_map, reason=reason)
# 若为本次运行的记录(例如新增预约),也加入 run_high_value_rooms 以便运行期回访
try:
add_to_run = False
if isinstance(reason, str) and "reservation" in reason:
add_to_run = True
if increment:
add_to_run = True
if add_to_run:
try:
run_high_value_rooms.add(key)
except Exception:
pass
except Exception:
pass
def _fallback_room_key_from_raw(raw_text: str) -> str:
try:
s = str(raw_text or "")
except Exception:
s = ""
s = s.replace("\r", " ").replace("\n", " ").replace("\t", " ")
s = re.sub(r"\s+", "", s).strip()
# key 需要稳定可读:限制长度,避免极端 OCR 输出撑爆 UI
if len(s) > 64:
s = s[:64]
return s
def _fallback_room_key_unknown(future_ts: float, pv: float, content: str) -> str:
try:
ft = int(float(future_ts or 0.0))
except Exception:
ft = 0
try:
pv_i = int(float(pv or 0.0))
except Exception:
pv_i = 0
c0 = str(content or "")
c0 = re.sub(r"\s+", "", c0)
if len(c0) > 10:
c0 = c0[:10]
return f"unknown@{ft}_{pv_i}_{c0}"
# 启动即写一次状态文件:Web 端可立即显示"脚本在跑/更新时间"
print("[启动] 准备写入初始状态文件")
_write_reservations_state("init")
print("[启动] 初始状态文件写入完成,准备进入主循环")
# 预约回退后,校验通过时可“直接复用已打开的详情”,避免再次找福袋/误切
forced_detail = None
forced_fudai_x = None
# 卡死自救:若画面长时间不变化,则按一次返回键(避免一直卡在某个页面/弹窗)。
stuck_last_hash = ""
stuck_same_since = 0.0
stuck_last_check_ts = 0.0
stuck_last_back_ts = 0.0
def _read_screen_hash() -> str:
try:
p = os.path.join(os.path.dirname(__file__), 'pic', 'screenshot.png')
with open(p, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
except Exception:
return ""
def _stuck_guard_tick() -> None:
"""周期性检测画面是否冻结;冻结则按一次返回键(节流)。"""
nonlocal stuck_last_hash, stuck_same_since, stuck_last_check_ts, stuck_last_back_ts
now = time.time()
# 频率控制:避免过于频繁截图
if stuck_last_check_ts and (now - stuck_last_check_ts) < 8:
return
stuck_last_check_ts = now
try:
self.operation.get_screenshot(self.device_id)
except Exception:
return
h = _read_screen_hash()
if not h:
return
if h != stuck_last_hash:
stuck_last_hash = h
stuck_same_since = 0.0
return
# 画面未变化
if stuck_same_since <= 0:
stuck_same_since = now
return
# 冻结超过阈值:按一次返回(节流避免连按)
if (now - stuck_same_since) >= 25 and (now - stuck_last_back_ts) >= 60:
stuck_last_back_ts = now
self._log_kv("自救", "疑似卡死:画面长时间未变化,按返回键一次", stuck_seconds=int(now - stuck_same_since))
try:
self.operation.click_back(self.device_id)
except Exception:
pass
self.operation.delay(1)
# 重新开始计时,等待下一轮检测
stuck_same_since = 0.0
def _compact_text(s: str) -> str:
try:
t = str(s or "")
except Exception:
t = ""
t = t.replace(" ", "")
t = re.sub(r"\s+", "", t)
return t
def _room_title_has_ellipsis(s: str) -> bool:
try:
t = str(s or "")
except Exception:
return False
if "…" in t:
return True
if re.search(r"\.{3,}", t):
return True
return False
def _strip_room_noise_text(s: str) -> str:
"""移除直播间名 OCR 常见噪音(点赞/关注/粉丝等)。"""
try:
t = str(s or "")
except Exception:
return ""
t = t.replace("\r", "\n").replace("\t", " ")
t = re.sub(r"[\s\u3000]+", " ", t).strip()
# 计数噪音:例如 1.2万点赞 / 234点赞 / 3W点赞
# 注意:OCR 常把它“粘在标题后面”,因此这里不依赖单词边界 \b。
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞)", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*关注", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*粉丝", " ", t)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*人(?:在线|在看)?", " ", t)
# “本场点赞/本场点(赞)”等(常见粘连/截断:本场点、本场点贊)
t = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
t = re.sub(r"本场\s*(?:点赞|点\s*赞|点贊|点)", " ", t)
# 孤立词也剔除(基本不会是标题本体)
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "人在线", "在线"):
t = t.replace(w, " ")
t = re.sub(r"\s+", " ", t).strip()
return t
def _extract_room_title_candidate(raw_text: str) -> str:
"""从 OCR 原文中提取更像“直播间名”的片段。
规则来自你的反馈:
- “xx万点赞/关注”等是多余文字
- 直播间名常以 .../… 结尾(省略号)
"""
t = _strip_room_noise_text(raw_text)
if not t:
return ""
segs = [x.strip() for x in re.split(r"[\n ]+", t) if x.strip()]
best = ""
best_score = -999
for seg in segs:
if not seg:
continue
# 仍带计数的段基本不是标题(即使粘连也先切掉尾部噪音)
seg2 = re.sub(r"\d+(?:\.\d+)?\s*[万wW]?\s*(?:点赞|赞|关注|粉丝)$", "", seg).strip()
if not seg2:
continue
seg = seg2
score = len(seg)
if _room_title_has_ellipsis(seg):
score += 30
if re.search(r"[\u4e00-\u9fffA-Za-z]", seg):
score += 5
if score > best_score:
best_score = score
best = seg
if best:
m = re.search(r"(.*?)(…|\.{3,})", best)
if m:
cand = (m.group(1) + m.group(2)).strip()
return cand if cand else best.strip()
return best.strip()
m2 = re.search(r"(.*?)(…|\.{3,})", t)
if m2:
cand2 = (m2.group(1) + m2.group(2)).strip()
if cand2:
return cand2
return t.strip()
def _normalize_room_title(t: str) -> str:
# 先提取“更像标题”的片段,避免把点赞/关注也拼进 key
s = _extract_room_title_candidate(str(t or ""))
s = s.replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
# 去掉常见无关词
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
s = s.replace(w, "")
# 去掉“数量+关键词”的残留(OCR 粘连场景兜底)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?(?:点赞|赞|关注|粉丝)", "", s)
# 去掉“本场点赞/本场点(赞)”残留(OCR 缺字/粘连兜底)
s = re.sub(r"\d+(?:\.\d+)?[万wW]?本场(?:点赞|点赞|点贊|点)", "", s)
s = re.sub(r"本场(?:点赞|点赞|点贊|点)", "", s)
# 只保留中文/字母/数字
s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]", "", s)
return s
def _resolve_high_value_room_key(title_norm: str, title_raw: str, pos_seen0: int | None = None) -> tuple[str, str, str, float]:
"""将本次识别结果映射到“历史表”里的 canonical key。
返回:(key, key_kind, merged_from, merged_ratio)
- merged_from:本次候选 key(若发生合并)
- merged_ratio:合并相似度
"""
try:
cand_norm = str(title_norm or "").strip()
except Exception:
cand_norm = ""
try:
cand_raw = str(title_raw or "").strip()
except Exception:
cand_raw = ""
key_kind0 = "norm"
key0 = cand_norm
if not key0:
try:
key0 = _normalize_room_title(cand_raw)
except Exception:
key0 = ""
if not key0:
if cand_raw:
key0 = _fallback_room_key_from_raw(cand_raw)
key_kind0 = "raw"
else:
return "", "unknown", "", 0.0
# 已存在:直接使用
if key0 in (high_value_rooms_map or {}):
try:
kk = str((high_value_rooms_map.get(key0) or {}).get("key_kind") or key_kind0)
except Exception:
kk = key_kind0
return key0, kk, "", 1.0
# 仅对 norm key 合并(raw/unknown 不做合并,避免误归类)
if key_kind0 != "norm" or len(key0) < 3:
return key0, key_kind0, "", 0.0
best_key = ""
best_ratio = 0.0
best_pos_ok = False
def _digits_stripped(x: str) -> str:
try:
return re.sub(r"\d+", "", str(x or ""))
except Exception:
return ""
key0_nod = _digits_stripped(key0)
for k, v in (high_value_rooms_map or {}).items():
if not k or str(k).startswith("unknown@"):
continue
k_norm = str(k)
if len(k_norm) < 3:
continue
try:
ratio = float(difflib.SequenceMatcher(None, key0, k_norm).ratio())
except Exception:
ratio = 0.0
# 去数字对比:处理“1/7/0 等数字混入标题”或 OCR 把笔画误成数字的情况
try:
k_nod = _digits_stripped(k_norm)
if key0_nod and k_nod and len(key0_nod) >= 3 and len(k_nod) >= 3:
ratio2 = float(difflib.SequenceMatcher(None, key0_nod, k_nod).ratio())
ratio = max(ratio, ratio2)
except Exception:
pass
# 包含关系通常意味着同一个标题被截断/省略
if (key0 in k_norm or k_norm in key0) and min(len(key0), len(k_norm)) >= 4:
ratio = max(ratio, 0.86)
pos_ok = False
if pos_seen0 is not None:
try:
pos_k = int((v or {}).get("pos_seen") or 0)
except Exception:
pos_k = 0
if pos_k > 0:
try:
pos_ok = abs(int(pos_seen0) - pos_k) <= 2
except Exception:
pos_ok = False
thr = 0.88
if pos_ok:
# 同一位置附近出现的标题,容忍更高:多用于 OCR 单字错/漏字
thr = 0.78
if ratio >= thr and ratio > best_ratio:
best_ratio = ratio
best_key = str(k)
best_pos_ok = bool(pos_ok)
if best_key:
if best_pos_ok and best_ratio >= 0.80:
return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio)
if best_ratio >= 0.88:
return best_key, str((high_value_rooms_map.get(best_key) or {}).get("key_kind") or "norm"), key0, float(best_ratio)
return key0, key_kind0, "", 0.0
def _read_live_room_title(label: str = "") -> str:
"""读取当前直播间顶部区域的“主播名/直播间名”(OCR,尽量轻量)。"""
nonlocal current_room_title, current_room_title_raw
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
# 直播间名识别“像福袋详情一样”——默认保持彩色(change_color=0),识别为空/过短再逐级重试。
# 经验:强二值化会吃掉 UI 字体细节;更容易出现“只识别到最后1个字”的情况。
try:
min_len = int(getattr(self, "room_title_min_len", 3) or 3)
except Exception:
min_len = 3
def _ocr_try(cut_name: str, change_color: int) -> tuple[str, str]:
try:
raw0 = self.operation.analyse_pic_word(cut_name, change_color)
except Exception:
raw0 = ""
raw_text0 = str(raw0 or "").replace("\r", "\n").strip()
cand_raw0 = _extract_room_title_candidate(raw_text0)
title0 = _normalize_room_title(cand_raw0)
return title0, cand_raw0
def _pick_best(cands: list[tuple[str, str, str]]) -> tuple[str, str]:
# cands: [(title_norm, raw_text, tag)]
best = ("", "")
best_score = -1
for t_norm, t_raw, tag in cands:
if not t_raw and not t_norm:
continue
ln = len(t_norm or "")
# 过短通常是裁剪/误识别;仍保留作为最后兜底,但降低得分。
score = ln
if ln >= min_len:
score += 10
if ln == 1:
score -= 4
if ln == 2:
score -= 1
if _room_title_has_ellipsis(t_raw or ""):
score += 8
# 偏好来自“更大ROI + 非二值化”的结果
if tag.endswith("_cc0"):
score += 2
if tag.startswith("large"):
score += 2
if tag.startswith("mid"):
score += 1
if score > best_score:
best_score = score
best = (t_norm, t_raw)
return best
cands: list[tuple[str, str, str]] = []
# mid ROI:优先使用更大区域,减少“只截到尾巴1个字”。
try:
# 1080x2400 基准;覆盖主播名区域,尽量避开右侧按钮
self.cut_pic(80, 128, 560, 230, '', 'live_room_title_mid', self.y_pianyi)
t, r = _ocr_try('live_room_title_mid', 0)
cands.append((t, r, 'mid_cc0'))
# 轻量备选:若背景/前景反差大,二值化可能帮助
if len(t or "") < min_len:
t1, r1 = _ocr_try('live_room_title_mid', 1)
cands.append((t1, r1, 'mid_cc1'))
except Exception:
pass
# large ROI:进一步扩大,兼容机型/系统字体/刘海偏移。
if not cands or max(len(x[0] or "") for x in cands) < min_len:
try:
self.cut_pic(40, 110, 660, 260, '', 'live_room_title_large', self.y_pianyi)
t2, r2 = _ocr_try('live_room_title_large', 0)
cands.append((t2, r2, 'large_cc0'))
if len(t2 or "") < min_len:
t3, r3 = _ocr_try('live_room_title_large', 1)
cands.append((t3, r3, 'large_cc1'))
except Exception:
pass
# small ROI:最后兜底(历史区域)。
if not cands or max(len(x[0] or "") for x in cands) <= 1:
try:
self.cut_pic(138, 144, 335, 185, '', 'live_room_title_small', self.y_pianyi)
t4, r4 = _ocr_try('live_room_title_small', 0)
cands.append((t4, r4, 'small_cc0'))
except Exception:
pass
title, raw_text = _pick_best(cands)
# 注意:若本次识别为空,不应沿用上一次的直播间名,否则会把预约/回访归到错误直播间。
current_room_title_raw = raw_text
if title:
current_room_title = title
# 若该直播间已存在于“永久历史记录”中,则刷新其当前位置。
# 位置会随着上划/下滑变化,因此需要在每次识别到直播间名时更新。
try:
cand_norm = _normalize_room_title(title or raw_text)
except Exception:
cand_norm = ""
key_key, key_kind, merged_from, merged_ratio = _resolve_high_value_room_key(
cand_norm,
raw_text,
pos_seen0=int(room_pos),
)
if key_key and (key_key in high_value_rooms_map):
_touch_high_value_room(
key_key,
raw_text,
0.0,
reason="pos_refresh",
increment=False,
key_kind=key_kind,
pos_seen=int(room_pos),
alias_norm=cand_norm,
alias_raw=str(raw_text or ""),
merged_from=merged_from,
merged_ratio=merged_ratio,
)
return title
def _match_reservation(item: dict, detail: tuple) -> tuple:
"""校验回退后的福袋详情是否匹配预约。返回 (ok, reason, debug_dict)"""
try:
expected_value = float(item.get("prize_value_yuan") or 0.0)
except Exception:
expected_value = 0.0
try:
expected_future = float(item.get("future_ts") or 0.0)
except Exception:
expected_future = 0.0
expected_content = _compact_text(item.get("content") or "")
fc, tt, participants, copies, pv, cd = detail
actual_content = _compact_text(fc or "")
try:
actual_value = float(pv or 0.0)
except Exception:
actual_value = 0.0
try:
actual_future = float(cd[1] if cd else 0.0)
except Exception:
actual_future = 0.0
# 检查是否为“观看XX分钟”类任务:若是,则视为任务型福袋,回退校验应判为不匹配(跳过预约)
try:
fc_full = str(fc or "")
chinese_num_chars = "零一二三四五六七八九十百千两"
patt = rf"(?:观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟"
if re.search(patt, fc_full):
return False, "watch_task_detected", {
"expected_future": expected_future,
"actual_future": actual_future,
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
except Exception:
pass
# future 必须可验证(否则无法确认回退成功)
if not (expected_future > 0 and actual_future > 0):
return False, "future_missing", {
"expected_future": expected_future,
"actual_future": actual_future,
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
future_diff = abs(expected_future - actual_future)
# value/content 二选一命中即可(OCR 有误差,且部分福袋可能不展示价值)
value_ok = False
if expected_value > 0 and actual_value > 0:
tol = max(50.0, expected_value * 0.25)
value_ok = abs(expected_value - actual_value) <= tol
content_ok = False
if expected_content and actual_content:
content_ok = (expected_content in actual_content) or (actual_content in expected_content)
if not (value_ok or content_ok):
return False, "content_or_value_mismatch", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
# 优先用 future 精确匹配;但在“内容+价值都一致”时,允许一定范围的 future 偏差,避免 OCR 倒计时误读导致误判。
# 说明:正常情况下 future_diff 应该很小;若 future_diff 过大仍会判不匹配。
if future_diff > 180:
if value_ok and content_ok and future_diff <= 1200:
return True, "future_mismatch_relaxed", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
return False, "future_mismatch", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
return True, "ok", {
"expected_future": expected_future,
"actual_future": actual_future,
"future_diff_s": int(future_diff),
"expected_value": expected_value,
"actual_value": actual_value,
"expected_content": expected_content,
"actual_content": actual_content,
}
def _validate_back_to_reservation(item: dict, quick: bool = False) -> bool:
"""回退后校验:必须看到福袋并且详情匹配预约。通过则保留详情供后续流程直接参与。"""
nonlocal forced_detail, forced_fudai_x, current_room_title, current_room_title_raw
# 若开关关闭,则跳过复杂校验,直接认为回退成功以加速流程
try:
if not bool(getattr(self, "reservation_back_verify_enabled", True)):
self._log_kv("预约", "回退校验已被禁用:跳过校验")
return True
except Exception:
pass
# 先用“直播间名”做一次快速判断:不匹配则大概率回错房间,优先驱动微调继续找
try:
expected_title = _normalize_room_title(item.get("room_title") or "")
except Exception:
expected_title = ""
expected_title_raw = str(item.get("room_title_raw") or "").strip()
if expected_title:
current_title = _read_live_room_title("back")
current_title_raw = str(current_room_title_raw or "").strip()
if current_title:
current_room_title = current_title
ratio = 0.0
try:
ratio = float(difflib.SequenceMatcher(None, expected_title, current_title).ratio())
except Exception:
ratio = 0.0
if current_title:
self._log_kv(
"预约",
"回退校验:直播间名对比",
room_title_expected=expected_title,
room_title_current=current_title,
room_title_raw_expected=expected_title_raw,
room_title_raw_current=current_title_raw,
room_title_ratio=round(ratio, 3),
)
# 强不匹配:直接失败(避免打开错误福袋详情浪费时间)
if current_title and (expected_title not in current_title) and (current_title not in expected_title) and ratio < 0.45:
return False
x2 = 0
max_checks = 1 if quick else 3
for i in range(max_checks):
try:
x2 = self.check_have_fudai() or 0
except Exception:
x2 = 0
if x2:
break
self._log_kv("预约", "回退校验:未发现福袋", attempt=i + 1)
self.operation.delay(0.5 if quick else 1)
if not x2:
self._log_kv("预约", "回退校验失败:未发现福袋", result="未发现福袋")
return False
# 打开详情并确认进入详情页(避免点击后截图过早导致读错屏)
if not _ensure_fudai_detail_open(int(x2), quick=bool(quick)):
self._log_kv("预约", "回退校验失败:未能打开福袋详情", result="详情未打开")
return False
# 详情页刚出现时可能仍在动画/加载,稍等再识别更稳定
self.operation.delay(0.6 if quick else 1.1)
detail2 = _read_fudai_detail_with_retries(int(x2))
if not detail2:
self._log_kv("预约", "回退校验失败:详情读取异常", result="详情异常")
# 兜底:确保已关闭详情
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if self.check_in_fudai_detail():
_close_fudai_detail(int(x2), reason="回退校验/详情异常")
self.operation.delay(0.8)
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if self.check_in_fudai_detail():
try:
self.operation.click_back(self.device_id)
except Exception:
pass
return False
ok, reason, dbg = _match_reservation(item, detail2)
if not ok:
self._log_kv("预约", "回退校验失败:福袋详情不匹配", result="不匹配", reason=reason, **dbg)
_close_fudai_detail(int(x2), reason="回退校验不匹配")
self.operation.delay(0.8)
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if self.check_in_fudai_detail():
try:
self.operation.click_back(self.device_id)
except Exception:
pass
self.operation.delay(0.8)
return False
self._log_kv("预约", "回退校验通过:已回到目标直播间", result="匹配", **dbg)
forced_detail = detail2
forced_fudai_x = int(x2)
return True
def _seek_reservation_room(item: dict, max_adjust: int = 6) -> bool:
"""回退后定位:不做微调滑动;最多校验5次,仍失败则放弃该福袋。"""
max_try = 5
for i in range(1, max_try + 1):
if _validate_back_to_reservation(item, quick=True):
return True
self._log_kv("预约", "回退校验未通过,继续识别", attempt=i, max_try=max_try)
self.operation.delay(0.6)
return False
def _sorted_reservations() -> None:
nonlocal reservations
reservations.sort(key=lambda x: float(x.get("future_ts") or 0.0))
def _reservation_key(it: dict) -> tuple:
# 粗粒度去重:future_ts(秒) + 内容
try:
ts = int(float(it.get("future_ts") or 0.0))
except Exception:
ts = 0
return (ts, str(it.get("content") or ""))
def _add_reservation(future_ts: float, pv: float, content: str) -> None:
nonlocal reservations, room_pos, current_room_title, current_room_title_raw
title = _read_live_room_title("reserve")
title_raw = str(current_room_title_raw or "").strip()
# 标题过短通常是裁剪/识别抖动(例如只剩“卷”);视为不可靠,允许短重试。
try:
min_len = int(getattr(self, "room_title_min_len", 3) or 3)
except Exception:
min_len = 3
if min_len < 1:
min_len = 1
def _title_ok(t: str, raw: str) -> bool:
try:
t1 = str(t or "")
except Exception:
t1 = ""
if len(t1) >= min_len:
return True
try:
n2 = _normalize_room_title(raw or "")
except Exception:
n2 = ""
return len(n2) >= min_len
# 直播间名 OCR 有时会短暂为空(顶部遮挡/弹窗/网络抖动);高价值预约属于低频事件,允许短重试。
if (not (title or title_raw)) or (not _title_ok(title, title_raw)):
try:
retry_n = int(getattr(self, "room_title_retry_times_for_reservation", 2) or 0)
except Exception:
retry_n = 2
retry_n = max(0, min(5, retry_n))
for _ in range(retry_n):
try:
self.operation.delay(0.25)
except Exception:
pass
title = _read_live_room_title("reserve_retry")
title_raw = str(current_room_title_raw or "").strip()
if _title_ok(title, title_raw):
break
item = {
"future_ts": float(future_ts),
"prize_value_yuan": float(pv or 0.0),
"content": content or "",
"pos_seen": int(room_pos),
"created_ts": time.time(),
"room_title": title,
"room_title_raw": title_raw,
}
if title:
current_room_title = title
# 预约去重:开奖时间 OCR 可能抖动(±1s),上划/下滑回去也可能重复触发。
try:
dedup_tol_s = float(getattr(self, "reservation_dedup_future_ts_tolerance_seconds", 2.0) or 2.0)
except Exception:
dedup_tol_s = 2.0
if dedup_tol_s < 0:
dedup_tol_s = 0.0
if dedup_tol_s > 30:
dedup_tol_s = 30.0
key = _reservation_key(item)
for ex in reservations:
same_key = _reservation_key(ex) == key
same_by_tol = False
if not same_key:
# 内容一致且开奖时间足够接近,则视为同一条预约(容忍 OCR 1~2 秒抖动)
try:
ex_content = str(ex.get("content") or "")
except Exception:
ex_content = ""
if ex_content and ex_content == str(content or ""):
try:
ex_ft = float(ex.get("future_ts") or 0.0)
except Exception:
ex_ft = 0.0
try:
ft0 = float(future_ts or 0.0)
except Exception:
ft0 = 0.0
if ex_ft > 0 and ft0 > 0 and abs(ex_ft - ft0) <= dedup_tol_s:
same_by_tol = True
if same_key or same_by_tol:
# 已存在:更新价值/位置
try:
ex["prize_value_yuan"] = float(pv or ex.get("prize_value_yuan") or 0.0)
except Exception:
pass
if same_by_tol:
# 选择更早的开奖时间,减少抖动导致的“越跳越远”
try:
ex_ft2 = float(ex.get("future_ts") or 0.0)
except Exception:
ex_ft2 = 0.0
try:
ft2 = float(future_ts or 0.0)
except Exception:
ft2 = 0.0
if ex_ft2 > 0 and ft2 > 0:
ex["future_ts"] = min(ex_ft2, ft2)
try:
ex["pos_seen"] = int(room_pos)
except Exception:
pass
if title_raw:
ex["room_title_raw"] = title_raw
if title:
ex["room_title"] = title
# 去重更新也应有日志:否则用户会觉得“怎么有的没记录”
try:
dt_str_u = datetime.fromtimestamp(float(ex.get("future_ts") or future_ts)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_str_u = str(ex.get("future_ts") or future_ts)
self._log_kv(
"预约",
"预约已存在:更新/去重",
mode=("same_key" if same_key else "future_tol"),
tol_s=float(dedup_tol_s),
value_yuan=float(pv or ex.get("prize_value_yuan") or 0.0),
future=dt_str_u,
pos_seen=int(room_pos),
room_title=str(ex.get("room_title") or ""),
room_title_raw=str(ex.get("room_title_raw") or ""),
qsize=len(reservations),
)
# 永久记录该直播间:抖动合并时不累计 seen_count,但刷新 last_seen/max_value
try:
cand_norm_persist = _normalize_room_title(title or title_raw)
except Exception:
cand_norm_persist = ""
key_title_persist, key_kind, merged_from, merged_ratio = _resolve_high_value_room_key(
cand_norm_persist,
title_raw,
pos_seen0=int(room_pos),
)
if not key_title_persist:
if title_raw:
key_title_persist = _fallback_room_key_from_raw(title_raw)
key_kind = "raw"
else:
key_title_persist = _fallback_room_key_unknown(future_ts, pv, content)
key_kind = "unknown"
if key_title_persist:
_touch_high_value_room(
key_title_persist,
title_raw,
float(pv or 0.0),
reason="reservation_dedup",
increment=False,
key_kind=key_kind,
content=str(content or ""),
pos_seen=int(room_pos),
alias_norm=cand_norm_persist,
alias_raw=str(title_raw or ""),
merged_from=merged_from,
merged_ratio=merged_ratio,
)
self._log_kv(
"预约",
"永久直播间记录:已更新(去重)",
key_kind=key_kind,
room_key=str(key_title_persist),
)
_sorted_reservations()
_write_reservations_state("dedup_update")
# 同步刷新“高价值回访表”
try:
key_title = _normalize_room_title(title or title_raw)
except Exception:
key_title = ""
if key_title:
now0 = time.time()
try:
interval_s = float(getattr(self, "high_value_room_revisit_interval_seconds", 300) or 300)
except Exception:
interval_s = 300.0
try:
window_s = float(getattr(self, "high_value_room_revisit_watch_window_seconds", 900) or 900)
except Exception:
window_s = 900.0
exw = high_value_room_watch.get(key_title) or {}
exw["room_title"] = str(title or "")
exw["room_title_raw"] = str(title_raw or "")
exw["pos_seen"] = int(room_pos)
exw["last_record_ts"] = now0
exw["watch_until_ts"] = now0 + max(60.0, window_s)
if float(exw.get("next_check_ts") or 0.0) <= 0:
exw["next_check_ts"] = now0 + max(60.0, interval_s)
high_value_room_watch[key_title] = exw
return ex
reservations.append(item)
_sorted_reservations()
_write_reservations_state("add")
# 永久记录该直播间(高价值福袋来源):仅在“新增预约”时计数
try:
cand_norm_persist2 = _normalize_room_title(title or title_raw)
except Exception:
cand_norm_persist2 = ""
key_title_persist, key_kind, merged_from, merged_ratio = _resolve_high_value_room_key(
cand_norm_persist2,
title_raw,
pos_seen0=int(room_pos),
)
if not key_title_persist:
if title_raw:
key_title_persist = _fallback_room_key_from_raw(title_raw)
key_kind = "raw"
else:
key_title_persist = _fallback_room_key_unknown(future_ts, pv, content)
key_kind = "unknown"
_touch_high_value_room(
key_title_persist,
title_raw,
float(pv or 0.0),
reason="reservation",
increment=True,
key_kind=key_kind,
content=str(content or ""),
pos_seen=int(room_pos),
alias_norm=cand_norm_persist2,
alias_raw=str(title_raw or ""),
merged_from=merged_from,
merged_ratio=merged_ratio,
)
self._log_kv(
"预约",
"永久直播间记录:已写入",
key_kind=key_kind,
room_key=str(key_title_persist),
)
try:
dt_str = datetime.fromtimestamp(float(future_ts)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_str = str(future_ts)
self._log_kv(
"预约",
"记录预约",
value_yuan=float(pv or 0.0),
future=dt_str,
pos_seen=int(room_pos),
room_title=title,
room_title_raw=title_raw,
qsize=len(reservations),
)
# 把该直播间加入“高价值回访表”
try:
key_title = _normalize_room_title(title or title_raw)
except Exception:
key_title = ""
if key_title:
now0 = time.time()
try:
interval_s = float(getattr(self, "high_value_room_revisit_interval_seconds", 300) or 300)
except Exception:
interval_s = 300.0
try:
window_s = float(getattr(self, "high_value_room_revisit_watch_window_seconds", 900) or 900)
except Exception:
window_s = 900.0
exw = high_value_room_watch.get(key_title) or {}
exw["room_title"] = str(title or "")
exw["room_title_raw"] = str(title_raw or "")
exw["pos_seen"] = int(room_pos)
exw["last_record_ts"] = now0
exw["watch_until_ts"] = now0 + max(60.0, window_s)
# next_check_ts:首次记录后推迟 interval,再回访
if float(exw.get("next_check_ts") or 0.0) <= 0:
exw["next_check_ts"] = now0 + max(60.0, interval_s)
high_value_room_watch[key_title] = exw
cap = int(self.high_value_fudai_max_reservations or 5)
if cap < 1:
cap = 1
if len(reservations) > cap:
# 队列溢出:丢弃“最低价值”的预约(同价值时优先丢弃开奖更晚的;再同则丢弃更早创建的)
def _drop_key(r: dict):
try:
pv2 = float(r.get("prize_value_yuan") or 0.0)
except Exception:
pv2 = 0.0
try:
ft2 = float(r.get("future_ts") or 0.0)
except Exception:
ft2 = 0.0
try:
ct2 = float(r.get("created_ts") or 0.0)
except Exception:
ct2 = 0.0
return (pv2, -ft2, ct2)
dropped = min(reservations, key=_drop_key)
try:
dt = datetime.fromtimestamp(float(dropped.get("future_ts") or 0.0)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt = str(dropped.get("future_ts"))
try:
reservations.remove(dropped)
except ValueError:
# 兜底:若 remove 失败,按末尾弹出
dropped = reservations.pop()
_sorted_reservations()
# 若仍超出(理论上不会),继续丢弃最低价值
while len(reservations) > cap:
try:
drop2 = min(reservations, key=_drop_key)
reservations.remove(drop2)
except Exception:
reservations = reservations[:cap]
break
_sorted_reservations()
self._log_kv(
"预约",
"预约队列已满,丢弃最低价值",
cap=cap,
dropped_value_yuan=dropped.get("prize_value_yuan"),
dropped_future=dt,
qsize=len(reservations),
)
_write_reservations_state("drop_low_value")
return item
def _clear_reservations(reason: str) -> None:
nonlocal reservations, room_pos, reservation_focus_until_ts
if reservations:
self._log_kv("预约", "清空预约队列", reason=reason, dropped=len(reservations))
reservations = []
room_pos = 0
reservation_focus_until_ts = 0.0
_write_reservations_state("clear")
def swipe_up_switch(msg: str) -> None:
nonlocal swipe_times, room_pos
self.swipe(760, 1600, 760, 800, 200)
print(msg)
swipe_times += 1
room_pos += 1
# 有预约队列时,不做“达到阈值后自动回到第一个直播间”的重置,避免破坏位置计数
if not reservations:
swipe_times = self._maybe_reset_after_swipes(needswitch, swipe_times)
def _swipe_up_return(times: int, reason: str) -> None:
"""用于“回访后返回原位置”的上划:不计入 swipe_times,避免影响切换阈值。"""
nonlocal room_pos
t = int(times or 0)
if t <= 0:
return
print(reason)
for i in range(t):
self.swipe(760, 1600, 760, 800, 200)
print("回到原位置 {}/{}".format(i + 1, t))
self.operation.delay(reservation_back_swipe_delay_s)
room_pos += t
def _revisit_should_skip_for_reservation(now_ts: float) -> bool:
"""若离预约参与窗口太近,则跳过回访(避免影响高级预约参与)。"""
if not (reservations and self.high_value_fudai_enabled):
return False
try:
skip_s = int(getattr(self, "high_value_room_revisit_skip_if_reservation_within_seconds", 120) or 120)
except Exception:
skip_s = 120
if skip_s <= 0:
return False
_sorted_reservations()
target0 = reservations[0]
try:
future_ts0 = float(target0.get("future_ts") or 0.0)
except Exception:
future_ts0 = 0.0
if future_ts0 <= 0:
return False
try:
ahead0 = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead0 = 120
est_back = int(room_pos - int(target0.get("pos_seen") or 0))
if est_back < 0:
est_back = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
if max_back > 0:
est_back = min(est_back, max_back)
dynamic_ahead = float(max(ahead0, est_back * reservation_back_swipe_delay_s + 18))
remain = (future_ts0 - dynamic_ahead) - now_ts
return remain <= float(skip_s)
def _maybe_revisit_high_value_room() -> bool:
"""高价值直播间定时回访:回到曾记录过高价值福袋的直播间看一眼是否出现新福袋。
返回 True 表示本轮已执行回访动作(无论成功与否),主循环可直接继续下一轮。
"""
nonlocal high_value_room_watch, room_pos, reservation_focus_until_ts, revisit_forced_x
if not needswitch:
return False
if not self.high_value_fudai_enabled:
return False
if not bool(getattr(self, "high_value_room_revisit_enabled", True)):
return False
now_ts = time.time()
if reservation_focus_until_ts > 0 and now_ts < reservation_focus_until_ts:
return False
if _revisit_should_skip_for_reservation(now_ts):
return False
# 清理过期观察窗
for k in list(high_value_room_watch.keys()):
try:
until_ts = float(high_value_room_watch[k].get("watch_until_ts") or 0.0)
except Exception:
until_ts = 0.0
if until_ts > 0 and now_ts > until_ts:
high_value_room_watch.pop(k, None)
if not high_value_room_watch:
return False
due = []
for k, v in high_value_room_watch.items():
try:
nct = float(v.get("next_check_ts") or 0.0)
except Exception:
nct = 0.0
# 若启用了“仅回访本次运行记录”,跳过非本运行记录的 key
try:
if bool(getattr(self, "high_value_room_revisit_only_current_run", False)) and (k not in run_high_value_rooms):
continue
except Exception:
pass
if nct > 0 and nct <= now_ts:
due.append((nct, k, v))
if not due:
return False
due.sort(key=lambda x: x[0])
_, key, entry = due[0]
try:
interval_s = float(getattr(self, "high_value_room_revisit_interval_seconds", 300) or 300)
except Exception:
interval_s = 300.0
# 计算回退次数(仅支持回退到更早位置)
try:
pos_seen = int(entry.get("pos_seen") or 0)
except Exception:
pos_seen = 0
back_times = int(room_pos - pos_seen)
if back_times <= 0:
entry["next_check_ts"] = now_ts + max(60.0, interval_s)
high_value_room_watch[key] = entry
return False
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
if max_back > 0:
back_times = min(back_times, max_back)
expected_title = _normalize_room_title(entry.get("room_title") or entry.get("room_title_raw") or "")
self._log_kv(
"回访",
"高价值直播间到期回访",
room_title_expected=expected_title,
pos_seen=pos_seen,
room_pos=int(room_pos),
back_times=int(back_times),
)
# 回到目标直播间
swipe_down_back(back_times, "[回访] 回到高价值直播间检查新福袋(回退{}次)".format(back_times))
# 校验直播间名
current_title = _read_live_room_title("revisit")
current_title_raw = str(current_room_title_raw or "").strip()
ratio = 0.0
try:
ratio = float(difflib.SequenceMatcher(None, expected_title, current_title).ratio())
except Exception:
ratio = 0.0
self._log_kv(
"回访",
"回访校验:直播间名对比",
room_title_expected=expected_title,
room_title_current=current_title,
room_title_raw_expected=str(entry.get("room_title_raw") or ""),
room_title_raw_current=current_title_raw,
room_title_ratio=round(ratio, 3),
)
ok_room = True
if expected_title and current_title:
if (expected_title not in current_title) and (current_title not in expected_title) and ratio < 0.45:
ok_room = False
# 更新 next_check_ts(无论成功与否都节流)
entry["next_check_ts"] = time.time() + max(60.0, interval_s)
high_value_room_watch[key] = entry
if not ok_room:
self._log_kv("回访", "回访校验失败:直播间名不匹配,返回原位置")
_swipe_up_return(back_times, "[回访] 校验失败:回到原位置(上划{}次)".format(back_times))
return True
# 校验通过:快速看一眼是否有新福袋;无则返回原位置
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
x_local = 0
try:
x_local = int(self.check_have_fudai_with_ready_screenshot(True) or 0)
except Exception:
x_local = 0
if not x_local:
self._log_kv("回访", "回访结果:未发现新福袋,返回原位置")
_swipe_up_return(back_times, "[回访] 未发现新福袋:回到原位置(上划{}次)".format(back_times))
return True
# 发现福袋:留在当前直播间,让主流程继续处理(不返回)
revisit_forced_x = x_local
# 延长观察窗(该房间仍活跃)
try:
window_s = float(getattr(self, "high_value_room_revisit_watch_window_seconds", 900) or 900)
except Exception:
window_s = 900.0
entry["watch_until_ts"] = time.time() + max(60.0, window_s)
entry["pos_seen"] = int(room_pos)
high_value_room_watch[key] = entry
self._log_kv("回访", "回访结果:发现福袋,交给主流程处理", fudai_x=int(x_local))
return False
def _close_fudai_detail(fudai_x: int | None = None, reason: str | None = None) -> None:
"""尽量稳妥地关闭福袋详情页。
优先点击右上角“X”关闭图标(通过图像识别),失败再使用旧的点击关闭兜底。
"""
if reason:
print("关闭福袋详情: {}".format(reason))
closed_ok = False
try:
closed_ok = bool(self.operation.tap_close_icon(
self.device_id,
screen_width=int(self.resolution_ratio_x or 1080),
timeout_seconds=1.5,
))
except Exception:
closed_ok = False
if closed_ok:
return
# 兜底:点击中间区域(通常可关闭弹窗)
try:
self.click(540, 470)
return
except Exception:
pass
# 最后兜底:沿用旧逻辑(依赖小福袋 x 定位)
if fudai_x is not None:
try:
self.click(int(fudai_x) + 45, 430)
except Exception:
pass
def _ensure_fudai_detail_open(fudai_x: int, quick: bool = False) -> bool:
"""确保福袋详情页已真正打开。
解决问题:点击后立刻截图/识别时,UI 可能仍在动画/加载,导致读错屏。
"""
timeout_s = 3.2 if quick else 4.5
step_s = 0.45
start = time.time()
# 先点击一次打开
try:
self.click(int(fudai_x) + 45, 430)
except Exception:
pass
while (time.time() - start) < timeout_s:
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if self.check_in_fudai_detail():
return True
self.operation.delay(step_s)
# 兜底:再点一次并短等一次
try:
self.click(int(fudai_x) + 45, 430)
except Exception:
pass
self.operation.delay(0.8)
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
return bool(self.check_in_fudai_detail())
def _reservation_should_preempt() -> bool:
"""当预约进入参与窗口时,中断当前长等待(如等待开奖结果),优先处理预约。"""
if not (reservations and self.high_value_fudai_enabled):
return False
_sorted_reservations()
target = reservations[0]
try:
future_ts = float(target.get("future_ts") or 0.0)
except Exception:
future_ts = 0.0
if future_ts <= 0:
return False
try:
ahead0 = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead0 = 120
est_back_times = int(room_pos - int(target.get("pos_seen") or 0))
if est_back_times < 0:
est_back_times = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
dynamic_ahead = float(max(ahead0, est_back_times * reservation_back_swipe_delay_s + 18))
# 若预约价值低于最低抢占阈值,则不抢占当前正在执行的任务
try:
pv = float(target.get("prize_value_yuan") or 0.0)
except Exception:
pv = 0.0
try:
minv = float(getattr(self, "reservation_preempt_min_value_yuan", 0.0) or 0.0)
except Exception:
minv = 0.0
if pv < minv:
return False
return time.time() >= (future_ts - dynamic_ahead)
def swipe_down_back(times: int, reason: str) -> None:
nonlocal room_pos
t = int(times or 0)
if t <= 0:
return
print(reason)
for i in range(t):
# 下滑回到上一个直播间(与上划切换相反方向)
self.swipe(760, 800, 760, 1600, 200)
print("回退直播间 {}/{}".format(i + 1, t))
self.operation.delay(reservation_back_swipe_delay_s)
room_pos -= t
def _is_abnormal_time_value(time_text, prize_value_yuan, countdown_result):
"""判断时间/价值是否异常(用于触发再截图/重开兜底)。"""
reasons = []
tt = str(time_text or "").strip()
if not tt:
reasons.append("time_empty")
if not countdown_result:
reasons.append("time_parse_fail")
# 价值:仅当你配置了最低价值或启用了高价值预约时,才强制要求识别出合理价值
require_value = bool((self.min_prize_value_yuan and float(self.min_prize_value_yuan) > 0) or self.high_value_fudai_enabled)
try:
pv = float(prize_value_yuan)
if pv < 0:
reasons.append("value_negative")
if pv > 2000000:
reasons.append("value_too_large")
if require_value and pv <= 0:
reasons.append("value_missing_or_zero")
except Exception:
if require_value:
reasons.append("value_parse_fail")
return (len(reasons) > 0), reasons
def _read_fudai_detail_once(label: str):
"""读取一次福袋详情(不额外触发其它截图)。返回 (content,time,participants,copies,value,countdown_result,abnormal,reasons)"""
# 速度优化:只在第一次调用时截图和诊断,后续重试时复用已有截图
if label == "first":
self._shot_and_diagnose("福袋详情", "识别内容/倒计时/价值({})".format(label), self.device_id)
# 后续重试时仅确保有最新截图,但跳过诊断以节省时间
elif label in ("retry1", "reopen"):
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
renwu = self.check_detail_height()
fc, tt, participants, copies, pv = self.get_fudai_contain(renwu)
cd = self.operation.check_countdown(tt)
abnormal, reasons = _is_abnormal_time_value(tt, pv, cd)
# 速度优化:只在第一次识别时检测任务区,减少OCR调用
# 额外检测任务区是否包含"观看X分钟"提示(尤其在存在任务时要优先跳过)
try:
if renwu and int(renwu) > 0 and label == "first":
# 速度优化:先检查福袋内容中是否已经包含"观看",避免不必要的OCR
chinese_num_chars = "零一二三四五六七八九十百千两"
patt_watch = rf"(?:需?看|观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟"
if fc and re.search(patt_watch, fc):
reasons = list(reasons) if reasons else []
reasons.append('watch_task_detected')
else:
# 只在福袋内容中未检测到时才进行OCR识别
task_texts = []
try:
# 优先使用用户指定的精确区域(速度最快,范围最小)
self.operation.cut_pic((50, 1675), (1029, 1920), '', 'task_user_area')
pic_name = 'task_user_area.png'
p1 = os.path.join(os.getcwd(), 'pic', pic_name)
p2 = os.path.join(os.path.dirname(__file__), 'pic', pic_name)
used_path = None
if os.path.exists(p1):
used_path = p1
elif os.path.exists(p2):
used_path = p2
if used_path:
txt_area = str(self.operation.analyse_pic_word('task_user_area', 0) or "").strip()
if txt_area:
task_texts.append(txt_area)
print(f"[OCR调试] task_user_area file={used_path} text={txt_area}")
except Exception:
pass
# 速度优化:如果第一个区域已识别到观看任务,跳过备选区域OCR
full_task_txt = (fc or "") + " " + " ".join(task_texts) if task_texts else (fc or "")
if not re.search(patt_watch, full_task_txt):
# 优化:调整任务区域坐标,减少无关干扰,提高识别精度
# 只在第一个区域未检测到时,才OCR备选区域(最多2个,而非3个)
boxes = [
(360, 980, 1000, 1240), # 优先识别中间区域(最常见)- 缩小宽度减少干扰
(360, 1000, 1000, 1280), # 备选区域 - 缩小宽度减少干扰
]
for idx_b, b in enumerate(boxes, 1):
try:
x1, y1, x2, y2 = b
self.cut_pic(x1, y1, x2, y2, '', f'fudai_task_once_{idx_b}', self.y_pianyi)
txt = str(self.operation.analyse_pic_word(f'fudai_task_once_{idx_b}', 0) or "").strip()
if txt:
task_texts.append(txt)
# 速度优化:一旦检测到观看任务,立即停止后续OCR
full_task_txt = (fc or "") + " " + " ".join(task_texts)
if re.search(patt_watch, full_task_txt):
break
except Exception:
continue
full_task_txt = (fc or "") + " " + " ".join(task_texts) if task_texts else (fc or "")
if re.search(patt_watch, full_task_txt):
reasons = list(reasons) if reasons else []
reasons.append('watch_task_detected')
except Exception:
pass
self._log_kv("详情", f"读取福袋详情({label})",
content=(fc or "-")[:60],
time_text=(tt or "-")[:30],
value_yuan=pv,
countdown=cd if cd else "未解析",
abnormal=abnormal,
reasons=",".join(reasons) if reasons else "无")
return fc, tt, participants, copies, pv, cd, abnormal, reasons
def _read_fudai_detail_with_retries(fudai_x: int):
"""异常兜底链路:再截图一次;仍异常则关闭重开+延迟x秒再截图;仍异常则判定无福袋。"""
budget_s = float(getattr(self, "fudai_detail_retry_budget_seconds", 10.0) or 0.0)
start_ts = time.time()
# 进入兜底前先确认确实在详情页(避免截图过早/页面未切换导致读错屏)
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if not self.check_in_fudai_detail():
_ensure_fudai_detail_open(int(fudai_x), quick=True)
self.operation.delay(0.6)
def _over_budget() -> bool:
return (budget_s > 0) and ((time.time() - start_ts) > budget_s)
fc, tt, participants, copies, pv, cd, abnormal, reasons = _read_fudai_detail_once("first")
# 若识别到 'watch_task_detected',立即作为需跳过的场景处理
try:
if reasons and isinstance(reasons, (list, tuple)) and ('watch_task_detected' in reasons):
print("[跳过] 详情识别包含观看任务,跳过该福袋")
_close_fudai_detail(fudai_x, reason="watch_task_detected")
self.operation.delay(1)
return None
except Exception:
pass
if abnormal and _over_budget():
print("[异常] 详情读取超出预算 {} 秒:提前放弃本次详情识别".format(budget_s))
_close_fudai_detail(fudai_x, reason="异常/超预算")
self.operation.delay(1)
return None
if abnormal:
fc, tt, participants, copies, pv, cd, abnormal, reasons = _read_fudai_detail_once("retry1")
try:
if reasons and isinstance(reasons, (list, tuple)) and ('watch_task_detected' in reasons):
print("[跳过] 详情识别包含观看任务(retry),跳过该福袋")
_close_fudai_detail(fudai_x, reason="watch_task_detected")
self.operation.delay(1)
return None
except Exception:
pass
if abnormal and _over_budget():
print("[异常] 详情读取超出预算 {} 秒:提前放弃本次详情识别".format(budget_s))
_close_fudai_detail(fudai_x, reason="异常/超预算")
self.operation.delay(1)
return None
if abnormal:
delay_s = float(self.fudai_abnormal_reopen_delay_seconds or 0.0)
# 速度优化:缩短重开延迟(从默认值或配置值减少20%)
delay_s = max(0.5, delay_s * 0.8) # 最少0.5秒,减少20%延迟
print("[异常] 时间/价值异常仍未恢复:关闭并重开福袋详情,延迟 {} 秒再截图".format(delay_s))
_close_fudai_detail(fudai_x, reason="异常/关闭重开")
# 速度优化:缩短关闭后的等待时间(从0.8秒减少到0.5秒)
self.operation.delay(0.5)
# reopen
_ensure_fudai_detail_open(int(fudai_x), quick=True)
self.operation.delay(delay_s)
fc, tt, participants, copies, pv, cd, abnormal, reasons = _read_fudai_detail_once("reopen")
if abnormal:
try:
if reasons and isinstance(reasons, (list, tuple)) and ('watch_task_detected' in reasons):
print("[跳过] 详情识别包含观看任务(reopen),跳过该福袋")
_close_fudai_detail(fudai_x, reason="watch_task_detected")
self.operation.delay(1)
return None
except Exception:
pass
if abnormal:
print("[异常] 时间/价值持续异常:关闭福袋详情并判定无福袋,继续其它流程")
_close_fudai_detail(fudai_x, reason="异常/持续异常")
self.operation.delay(1)
return None
return fc, tt, participants, copies, pv, cd
print("[启动] 进入主循环")
loop_count = 0
while True:
loop_count += 1
if loop_count % 10 == 1: # 每10次循环打印一次,避免日志过多
print(f"[主循环] 第 {loop_count} 次循环开始")
# 支持网页端随时修改配置:定期 reload
self._maybe_reload_config(2.0)
# 卡死自救(不改变主流程;仅在疑似冻结时按一次返回)
_stuck_guard_tick()
# 清理已到期的预约:若预约的开奖时间已到或已过去,立即删除该预约并写状态(不再等待)
try:
if reservations:
now_ts_drop = time.time()
dropped = 0
for r in list(reservations):
try:
ft = float(r.get("future_ts") or 0.0)
except Exception:
ft = 0.0
if ft > 0 and now_ts_drop >= ft:
try:
reservations.remove(r)
except Exception:
try:
reservations.pop()
except Exception:
pass
dropped += 1
if dropped:
self._log_kv("预约", "到期删除过期预约", dropped=dropped, qsize=len(reservations))
_write_reservations_state("drop_expired_by_time")
except Exception:
pass
# 入口门禁:先截图判断是否处于直播间;若不在直播间则先进入直播间,再开始判断福袋。
try:
# 只截图一次,用这张截图做阶段判断
if loop_count <= 3 or loop_count % 20 == 0:
print(f"[主循环] 第 {loop_count} 次:准备截图判断当前状态")
self._shot_and_diagnose("主循环", "先判断是否在直播间", self.device_id, diagnose=False)
if loop_count <= 3 or loop_count % 20 == 0:
print(f"[主循环] 第 {loop_count} 次:截图完成,开始诊断阶段")
st0, seen0 = self._diagnose_stage_from_current_screen()
try:
self._last_diag_stage = st0
self._last_diag_seen = seen0
except Exception:
pass
except Exception:
st0, seen0 = "LIVE_OR_UNKNOWN", ""
# 若当前截图诊断为推荐页面(RECOMMEND_PAGE),点击关注标签然后点击进入直播间
try:
if st0 == "RECOMMEND_PAGE":
self._log_kv("流程", "检测到推荐页面,点击关注标签并进入直播间", stage=st0, seen=seen0)
try:
# 点击关注标签(顶部标签栏的关注标签,坐标基于1080x2400分辨率)
follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 712))
follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 169))
self.click(follow_tab_x, follow_tab_y)
print(f"检测到推荐页面,点击关注标签 -> ({follow_tab_x}, {follow_tab_y})")
self.operation.delay(2)
# 点击进入直播间的位置(连点两次)
enter_live_x = int(getattr(self, "yanghao_fallback_enter_live_x", 109))
enter_live_y = int(getattr(self, "yanghao_fallback_enter_live_y", 376))
self.click(enter_live_x, enter_live_y)
self.operation.delay(0.6)
self.click(enter_live_x, enter_live_y)
print(f"点击进入直播间位置 -> ({enter_live_x}, {enter_live_y}) 连点两次")
self.operation.delay(2)
continue # 继续下一轮循环
except Exception as e:
print(f"处理推荐页面时出错: {e}")
# 如果出错,尝试回退
try:
self.operation.click_back(self.device_id)
self.operation.delay(1)
except Exception:
pass
except Exception:
pass
# 若当前截图诊断为 LIVE_OR_UNKNOWN,额外检查是否是推荐页面(可能误判)
try:
if st0 == "LIVE_OR_UNKNOWN":
# 复用推荐页面的识别逻辑,检查标题区域
t_recommend_check = ""
t_guess_like_check = ""
try:
# 识别推荐页面标题区域(和 RECOMMEND_PAGE 一样的区域)
self.cut_pic(200, 80, 880, 280, '', 'diag_recommend_title_check')
t_recommend_check = str(self.operation.analyse_pic_word('diag_recommend_title_check') or "")
except Exception:
pass
try:
# 检查"猜你喜欢"区域(和 RECOMMEND_PAGE 一样的区域)
self.cut_pic(440, 1570, 640, 1640, '', 'diag_guess_like_check')
t_guess_like_check = str(self.operation.analyse_pic_word('diag_guess_like_check', 1) or "")
except Exception:
pass
# 如果识别到推荐页面的特征,执行和 RECOMMEND_PAGE 一样的操作
is_recommend_page = False
if "推荐" in t_recommend_check:
if "直播" in t_recommend_check or "关注" in t_recommend_check:
is_recommend_page = True
elif "猜你喜欢" in t_guess_like_check or "猜你喜欢" in t_recommend_check:
is_recommend_page = True
else:
is_recommend_page = True # 只有"推荐"关键词也判定为推荐页面
elif "猜你喜欢" in t_guess_like_check:
is_recommend_page = True
if is_recommend_page:
self._log_kv("流程", "LIVE_OR_UNKNOWN阶段检测到推荐页面,点击关注标签并进入直播间", stage=st0, seen=seen0)
try:
# 点击关注标签(顶部标签栏的关注标签,坐标基于1080x2400分辨率)
follow_tab_x = int(getattr(self, "yanghao_follow_tab_x", 712))
follow_tab_y = int(getattr(self, "yanghao_follow_tab_y", 169))
self.click(follow_tab_x, follow_tab_y)
print(f"LIVE_OR_UNKNOWN阶段检测到推荐页面,点击关注标签 -> ({follow_tab_x}, {follow_tab_y})")
self.operation.delay(2)
# 点击进入直播间的位置(连点两次)
enter_live_x = int(getattr(self, "yanghao_fallback_enter_live_x", 109))
enter_live_y = int(getattr(self, "yanghao_fallback_enter_live_y", 376))
self.click(enter_live_x, enter_live_y)
self.operation.delay(0.6)
self.click(enter_live_x, enter_live_y)
print(f"点击进入直播间位置 -> ({enter_live_x}, {enter_live_y}) 连点两次")
self.operation.delay(2)
continue # 继续下一轮循环
except Exception as e:
print(f"LIVE_OR_UNKNOWN阶段处理推荐页面时出错: {e}")
# 如果出错,尝试回退
try:
self.operation.click_back(self.device_id)
self.operation.delay(1)
except Exception:
pass
except Exception:
pass
# 若当前截图诊断为关注列表(FOLLOW_LIST),点击关注位置并回到直播间
try:
if st0 == "FOLLOW_LIST":
self._log_kv("流程", "检测到关注列表,点击关注位置并返回直播间", stage=st0, seen=seen0)
try:
# 点击关注位置(关注列表页中的位置,进入直播间列表)
self.click(390, 590)
print("检测到关注列表,点击关注位置进入直播间列表")
self.operation.delay(2)
# 进入直播间
self.into_zhibo_from_list()
continue # 继续下一轮循环
except Exception as e:
print(f"处理关注列表时出错: {e}")
# 如果出错,尝试回退
try:
self.operation.click_back(self.device_id)
self.operation.delay(1)
except Exception:
pass
except Exception:
pass
# 若当前截图诊断为结果弹窗(FUDai_RESULT),则根据识别内容立即处理(避免后续误判/延迟)
try:
if st0 == "FUDai_RESULT":
self._log_kv("流程", "检测到开奖结果弹窗,立即处理", stage=st0, seen=seen0)
try:
res = self.check_lucky_draw_result()
if res is False:
# 未识别到明确结果文本,尝试关闭弹窗保守处理
try:
self.click(540, 1270)
self.operation.delay(1)
except Exception:
pass
elif res in (1, 2, 3):
# 未中奖类:点击“我知道了”并记录
try:
self.click(540, 1270)
print("检测到未中奖弹窗,点击我知道了关闭")
self.operation.delay(2)
except Exception:
pass
else:
# 返回 y 坐标表示中奖流程,转入领奖
try:
print("检测到中奖结果,执行领奖流程")
self.get_reward(res)
except Exception:
pass
except Exception:
pass
# 处理完弹窗后继续下一轮主循环
continue
except Exception:
pass
# 检测是否意外返回桌面(不在抖音前台),若是则尝试通过点击桌面图标 -> 直播 -> 进入直播间 恢复
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):
print(f"[自救] 发现前台包: {top_pkg}(疑似已回到桌面/非抖音),直接点击预设坐标尝试恢复进入直播间")
try:
# 直接点击桌面图标的预设坐标
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)
print(f"[自救] 点击直播按钮 -> ({lx},{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)
print(f"[自救] 点击进入直播间 -> ({ex},{ey}) 连点两次")
self.click(ex, ey)
self.operation.delay(0.6)
self.click(ex, ey)
self.operation.delay(2.0)
except Exception:
pass
# 重新开始下一轮判断
continue
except Exception:
pass
except Exception:
pass
if st0 in ("FOLLOW_LIST", "LIVE_LIST"):
self._log_kv("流程", "不在直播间:先进入直播间", stage=st0, seen=seen0)
try:
self.into_zhibo_from_list()
except Exception:
pass
# 进入直播间后重新开始下一轮(后续再判断福袋)
continue
if st0 == "LIVE_CLOSED":
self._log_kv("流程", "直播间已结束:返回并重新进入直播间", stage=st0, seen=seen0)
try:
self.operation.click_back(self.device_id)
self.operation.delay(2)
except Exception:
pass
try:
self.into_zhibo_from_list()
except Exception:
pass
continue
# 若预约队列中有到达“开奖前 N 秒”的项:按开奖时间顺序,只回退参与距离当前最近的那一个
# 说明:当多个预约同时进入参与窗口时,只处理最早开奖的一项;其余留在队列里,避免连续回退导致位置计数漂移。
if reservations and self.high_value_fudai_enabled:
_sorted_reservations()
try:
ahead = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead = 120
now_ts = time.time()
# 若刚回退到某个预约直播间且处于停留窗口:不触发其它预约回退
if reservation_focus_until_ts > 0 and now_ts < reservation_focus_until_ts:
pass
else:
# 动态提前量:考虑回退步数耗时 + 回退校验耗时,避免提前量太小导致回退后错过
target0 = reservations[0]
future_ts = float(target0.get("future_ts") or 0.0)
est_back_times = int(room_pos - int(target0.get("pos_seen") or 0))
if est_back_times < 0:
est_back_times = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
dynamic_ahead = int(max(ahead, est_back_times * reservation_back_swipe_delay_s + 18))
if future_ts > 0 and now_ts >= (future_ts - dynamic_ahead):
# 弹出最早到达参与窗口的预约项进行处理(先写状态以便 GUI 实时更新)
item = reservations.pop(0)
_write_reservations_state("pop_for_attend")
# 若开奖时间已明显过去(例如超过 5 秒),直接丢弃该项并继续
try:
now_check = time.time()
if float(item.get("future_ts") or 0.0) + 5.0 < now_check:
try:
dt_str2 = datetime.fromtimestamp(float(item.get("future_ts") or 0.0)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_str2 = str(item.get("future_ts"))
self._log_kv(
"预约",
"到达参与窗口但已过期,直接丢弃",
future=dt_str2,
qsize=len(reservations),
)
_write_reservations_state("drop_expired_after_pop")
continue
except Exception:
pass
try:
dt_str = datetime.fromtimestamp(float(item.get("future_ts") or 0.0)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_str = str(item.get("future_ts"))
back_times = int(room_pos - int(item.get("pos_seen") or 0))
if back_times < 0:
back_times = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
# 约定:max_back=0 表示不限制回退次数
if max_back > 0:
back_times = min(back_times, max_back)
self._log_kv(
"预约",
"到达参与窗口,准备回退参与",
value_yuan=item.get("prize_value_yuan"),
future=dt_str,
qsize=len(reservations),
back_times=back_times,
room_pos=room_pos,
pos_seen=item.get("pos_seen"),
remain_to_join_window_s=int(max(0, (float(item.get("future_ts") or 0.0) - time.time() - dynamic_ahead))),
)
swipe_down_back(back_times, "[预约] 回退到预约直播间(回退{}次)".format(back_times))
# 回退后必须校验:确实回到目标直播间,且福袋详情能对应上
if not _seek_reservation_room(item, max_adjust=6):
# 只丢弃当前预约项(已从队列 pop 出来);其余预约继续保留
self._log_kv("预约", "回退校验失败:已放弃该福袋,仅丢弃当前项", qsize=len(reservations))
_write_reservations_state("drop_back_seek_failed")
continue
# 校验通过:给该直播间一个“强制停留窗口”,避免立刻上划走掉
reservation_focus_until_ts = time.time() + 90
reservation_after_action_pending = True
# 若之前因为“切换多次无福袋”而挂起了“回到列表第一个直播间”的动作:
# 等预约队列处理完(清空)后再执行,避免破坏预约位置计数。
if reset_to_list_after_reservations and (not reservations):
reset_to_list_after_reservations = False
print("[预约] 预约已处理完:回到直播列表并重新进入第一个直播间")
_clear_reservations("预约处理完/回到列表")
try:
self.back_to_zhibo_list()
self.into_zhibo_from_list()
except Exception:
pass
swipe_times = 0
room_pos = 0
_write_reservations_state("after_reservations_reset_to_list")
continue
# 回访优先级介于“预约参与”和“普通找福袋”之间
try:
_maybe_revisit_high_value_room()
except Exception:
pass
self.deal_battery_level()
opened_fudai_detail = False
current_hour = self.operation.get_current_hour()
# 定时禁抢:2点-7点仅养号,不做任何福袋识别/参与
if self.fudai_quiet_hours_enabled and self._in_quiet_hours(current_hour):
_clear_reservations("处于禁抢时段")
secs = self._yanghao_get_recommend_seconds()
print("[定时] 当前{}点处于禁抢时段({}-{}点):关闭抢福袋,仅持续养号 {} 秒".format(
current_hour, int(self.fudai_quiet_start_hour), int(self.fudai_quiet_end_hour), secs
))
self._yanghao_wait(secs)
continue
x = 0
detail = None
# 若刚完成预约回退校验:复用已打开的详情,避免重复找福袋/误切
if forced_detail is not None and forced_fudai_x:
x = int(forced_fudai_x)
detail = forced_detail
forced_detail = None
forced_fudai_x = None
else:
if revisit_forced_x is not None:
x = int(revisit_forced_x)
revisit_forced_x = None
wait_times = 0
self.click(x + 45, 430)
print("[回访] 发现福袋:点击打开福袋详情")
self.operation.delay(2.2)
opened_fudai_detail = True
self.operation.delay(1.2)
detail = _read_fudai_detail_with_retries(x)
if not detail:
continue
else:
# 先截图做一次“是否已在详情页”的兜底判断(避免起始就在详情页时误点导致详情关闭/福袋消失)
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
if self.check_in_fudai_detail():
self._log_kv("流程", "检测到已在福袋详情页:跳过找福袋,直接读取详情")
opened_fudai_detail = True
# 进入详情时可能无法可靠获取小福袋 x,使用一个占位值即可(关闭动作优先 tap_close_icon)
x = 455
detail = _read_fudai_detail_with_retries(x)
if not detail:
continue
else:
# 复用刚才的截图,避免重复截图
x = self.check_have_fudai_with_ready_screenshot(True)
# 无福袋看门狗:默认关闭;开启后才会触发“回到列表重进”
if bool(getattr(self, "no_fudai_watchdog_enabled", False)) and self.check_no_fudai_time() > 1800: # 如果30分钟都没有福袋
self.operation.save_reward_pic(self.device_id)
_clear_reservations("30分钟无福袋,重进直播列表")
self.back_to_zhibo_list()
self.into_zhibo_from_list()
continue
if x and swipe_times < 17:
wait_times = 0
self.click(x + 45, 430) # 点击默认小福袋的位置
print("点击打开福袋详情")
self.operation.delay(3)
opened_fudai_detail = True
elif (not needswitch) and (swipe_times == 0):
# 默认不切换的场景也避免卡死在第一个直播间:
# 若刚进入的第一个直播间无福袋,尝试一次上划到下一个直播间。
swipe_up_switch("首个直播间无福袋:试切到下一个")
continue
elif needswitch: # 如果福袋不存在,且需要切换直播间
# 如果刚回退到预约直播间:在 focus 窗口内不允许上划离开
if reservation_focus_until_ts > 0 and time.time() < reservation_focus_until_ts:
if reservations and self.high_value_fudai_enabled:
# 检查是否已到参与窗口:如果是,快速继续触发回退参与
try:
ahead = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead = 120
_sorted_reservations()
future_ts = float(reservations[0].get("future_ts") or 0.0)
remain = int(max(0, future_ts - time.time() - ahead))
if remain <= 0:
print("[预约] 当前处于预约直播间等待窗口,未检测到福袋但已到参与窗口:快速重试")
self.operation.delay(1)
else:
print("[预约] 当前处于预约直播间等待窗口,未检测到福袋:短暂停留后重试")
self.operation.delay(2)
else:
print("[预约] 当前处于预约直播间停留窗口,未检测到福袋:等待2秒后重试")
self.operation.delay(2)
continue
if bool(getattr(self, "reset_after_swipes_enabled", False)):
max_swipes = max(1, int(self.reset_after_swipes or 0))
else:
max_swipes = 999999
if swipe_times < max_swipes:
swipe_up_switch("直播间无福袋,上划切换直播间")
else:
# 达到切换阈值:若存在预约,则优先回到预约位置等待预约处理完;否则才回到列表第一个直播间。
if reservations and self.high_value_fudai_enabled:
_sorted_reservations()
try:
ahead = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead = 120
target = reservations[0]
back_times = int(room_pos - int(target.get("pos_seen") or 0))
if back_times < 0:
back_times = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
if max_back > 0:
back_times = min(back_times, max_back)
print("[预约] 直播间已切换{}次仍无福袋:存在预约,先回到最早预约直播间等待".format(swipe_times))
if back_times > 0:
swipe_down_back(back_times, "[预约] 无福袋切换达阈值:回退到最早预约直播间(回退{}次)".format(back_times))
else:
print("[预约] 无福袋切换达阈值:当前已在最早预约直播间")
try:
join_window_ts = float(target.get("future_ts") or 0.0) - float(ahead)
except Exception:
join_window_ts = time.time() + 60
reservation_focus_until_ts = max(time.time() + 10, join_window_ts + 5)
reset_to_list_after_reservations = True
_write_reservations_state("no_fudai_threshold_back_to_reservation")
self.operation.delay(2)
else:
print("直播间已切换{}次仍无福袋,回到列表并重新进入第一个直播间".format(swipe_times))
_clear_reservations("切换过多/回到列表")
self.back_to_zhibo_list()
self.into_zhibo_from_list()
swipe_times = 0
self.operation.delay(post_switch_delay_s)
continue
elif self.check_zhibo_is_closed(): # 如果不切换直播间但直播间已经关闭了
_clear_reservations("直播间关闭,回到列表")
self.back_to_zhibo_list()
self.into_zhibo_from_list()
swipe_times = 0
self.operation.delay(post_switch_delay_s)
continue
elif self.check_in_zhibo_list(): # 如果已经退出到直播间列表
_clear_reservations("已在直播列表,重新进入")
self.into_zhibo_from_list()
swipe_times = 0 # 滑动次数归0
continue
elif wait_times >= 4: # 如果福袋不存在,且不需要切换直播间,但等待了很久
self._log_kv("切换", "无福袋等待次数达到阈值,准备切换直播间", wait_times=wait_times, swipe_times=swipe_times)
if swipe_times < 15: # 上划次数不到15次,就继续上划
swipe_up_switch("直播间等待{}次无福袋,上划切换直播间".format(wait_times))
wait_times = 0 # 切换后重置等待次数
self.operation.delay(post_switch_delay_s)
continue
else:
print("直播间等待{}次无福袋且已切换{}次,退出返回直播列表".format(wait_times, swipe_times))
_clear_reservations("等待过久/回到列表")
self.back_to_zhibo_list()
self.into_zhibo_from_list()
swipe_times = 0 # 滑动次数归0
wait_times = 0
self.operation.delay(post_switch_delay_s)
continue
else: # 如果福袋不存在,且不需要切换直播间,且等待轮数不够
wait_times += 1 # 增加等待次数,累计4次后触发切换
self._log_kv("等待", "直播间无福袋,等待计数", wait_times=wait_times, max_wait=4)
secs = int(self._yanghao_get_recommend_seconds() or 60)
if reservations and self.high_value_fudai_enabled:
# 检查是否已到参与窗口
try:
ahead = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead = 120
_sorted_reservations()
future_ts = float(reservations[0].get("future_ts") or 0.0)
remain = int(max(0, future_ts - time.time() - ahead))
if remain <= 0:
print("直播间暂无福袋:存在预约且已到参与窗口,快速继续(触发回退参与)")
self.operation.delay(1)
else:
print("直播间暂无福袋:存在预约但未到参与窗口,短暂停留后继续")
self.operation.delay(2)
else:
if not bool(getattr(self, "yanghao_enabled", True)):
print("直播间暂无福袋:养号已关闭,快速继续")
else:
print("直播间暂无福袋:执行推荐页养号/等待 {} 秒".format(secs))
self._yanghao_wait(secs)
continue
if opened_fudai_detail:
# 刚打开详情时 UI 可能仍在动画/加载,稍等再截图更稳定
self.operation.delay(1.2)
detail = _read_fudai_detail_with_retries(x)
if not detail:
# 异常兜底已处理:当作无福袋,回到主循环
continue
fudai_content_text, time_text, participants, copies, prize_value_yuan, cd = detail
# 记录:仅在已成功读取详情且不被识别为“观看任务”时,记录进入直播间到识别到正确福袋内容的耗时
try:
# 先检测是否为观看任务(下文会重复检测并跳过),只有在非观看任务场景才记录时间。
fc_str_tmp = str(fudai_content_text or "")
chinese_num_chars = "零一二三四五六七八九十百千两"
m_watch_tmp = re.search(r"(?:观看|看)(?:直播)?\s*(?:\d+|[" + chinese_num_chars + r"]+)\s*分钟", fc_str_tmp)
if getattr(self, "_enter_live_ts", 0.0) and (not getattr(self, "_enter_live_fudai_logged", False)) and (not m_watch_tmp):
try:
enter_ts = float(getattr(self, "_enter_live_ts", 0.0) or 0.0)
except Exception:
enter_ts = 0.0
try:
dt = float(time.time() - enter_ts)
except Exception:
dt = -1.0
if enter_ts > 0 and dt >= 0:
try:
reason0 = str(getattr(self, "_enter_live_reason", "") or "")
except Exception:
reason0 = ""
self._enter_live_fudai_logged = True
try:
self._log_kv("性能", "进入直播间到识别福袋内容耗时", seconds=round(dt, 2), enter_reason=reason0)
except Exception:
pass
try:
self._log_kv("性能", "进入直播间后识别到正确福袋内容耗时", seconds=round(dt, 2), enter_reason=reason0)
except Exception:
pass
except Exception:
pass
# 如果福袋内容中包含“观看直播X分钟”或“观看X分钟”(支持阿拉伯数字与常见中文数字),则跳过该福袋
try:
fc_str = str(fudai_content_text or "")
# 支持形式:观看直播10分钟 / 观看10分钟 / 看直播十分钟 等
chinese_num_chars = "零一二三四五六七八九十百千两"
m_watch = re.search(r"(?:观看|看)(?:直播)?\s*(?:\d+|[" + chinese_num_chars + r"]+)\s*分钟", fc_str)
if m_watch:
print("[跳过] 识别到观看任务:{},跳过该福袋".format(m_watch.group(0)))
_close_fudai_detail(x, reason="任务/观看分钟跳过")
self.operation.delay(1)
if needswitch:
swipe_up_switch("检测到观看任务,跳过并上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
except Exception:
pass
# 参与人数筛选(0 表示不启用)
if participants:
if self.min_participants and participants < self.min_participants:
_close_fudai_detail(x, reason="参与人数过低")
print("参与人数{} < 阈值{},不参与,关闭福袋详情".format(participants, self.min_participants))
self.operation.delay(1)
if needswitch:
swipe_up_switch("参与人数过低,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
if self.max_participants and participants > self.max_participants:
_close_fudai_detail(x, reason="参与人数过高")
self._log_kv("过滤", "参与人数超过阈值,跳过", participants=participants, max_participants=self.max_participants)
self.operation.delay(1)
if needswitch:
swipe_up_switch("参与人数过高,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
if self.min_prize_value_yuan and prize_value_yuan and prize_value_yuan < self.min_prize_value_yuan:
_close_fudai_detail(x, reason="奖品价值过低")
self._log_kv("过滤", "奖品价值低于阈值,跳过", value_yuan=prize_value_yuan, min_value_yuan=self.min_prize_value_yuan)
self.operation.delay(1)
if needswitch:
swipe_up_switch("直播间奖品价值过低,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
if self.check_contain(fudai_content_text): # 如果福袋内容是不想要的 and needswitch
_close_fudai_detail(x, reason="福袋内容不理想")
print("点击小福袋位置,关闭福袋详情")
self.operation.delay(1)
swipe_up_switch("直播间福袋内容不理想,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
if cd:
fudai_not_open_times = 0
lastsecond, future_timestamp = cd
else:
# 理论上不会触发(异常兜底会 continue),这里保底
fudai_not_open_times += 1
_close_fudai_detail(x, reason="倒计时解析为空")
print("第{}次打开福袋异常(倒计时解析为空),关闭福袋详情".format(fudai_not_open_times))
self.operation.delay(1)
continue
if needswitch and lastsecond < int(self.skip_if_countdown_lt_seconds or 15): # 倒计时太短就不点了
_close_fudai_detail(x, reason="倒计时过短")
print("点击小福袋位置,关闭福袋详情")
self.operation.delay(1)
if needswitch:
swipe_up_switch("抽奖倒计时时间小于{}秒,不参与,上划切换直播间".format(int(self.skip_if_countdown_lt_seconds or 15)))
self.operation.delay(post_switch_delay_s)
continue
# 高价值福袋预约(队列):价值 >= 阈值 且倒计时较长时,记录下来并继续切换
if needswitch and self.high_value_fudai_enabled:
try:
threshold = float(self.high_value_fudai_threshold_yuan or 1000.0)
except Exception:
threshold = 1000.0
try:
ahead = int(self.high_value_fudai_join_ahead_seconds or 120)
except Exception:
ahead = 120
pv = float(prize_value_yuan or 0.0)
if pv >= threshold and lastsecond > max(ahead + 5, 30):
try:
dt_str = datetime.fromtimestamp(float(future_timestamp)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_str = str(future_timestamp)
# 在记录预约前检查是否为需观看任务(例如“观看直播10分钟”),若是则跳过记录
try:
fc_chk = str(fudai_content_text or "")
# 先对用户指定的小区域直接截图并 OCR
task_texts = []
try:
# 使用用户提供的矩形区域 (50,1675)-(1029,1920)
self.operation.cut_pic((50, 1675), (1029, 1920), '', 'task_user_area_pre')
pic_name = 'task_user_area_pre.png'
p1 = os.path.join(os.getcwd(), 'pic', pic_name)
p2 = os.path.join(os.path.dirname(__file__), 'pic', pic_name)
used_path = None
if os.path.exists(p1):
used_path = p1
elif os.path.exists(p2):
used_path = p2
if not used_path:
print(f"[OCR调试] pre task_user_area 文件未找到: checked {p1} and {p2}")
t_area = ""
else:
t_area = str(self.operation.analyse_pic_word('task_user_area_pre', 0) or "").strip()
print(f"[OCR调试] pre task_user_area file={used_path} text={t_area}")
if t_area:
task_texts.append(t_area)
except Exception:
pass
# 备选区域兜底
candidate_boxes = [
(360, 920, 1020, 1120),
(360, 980, 1020, 1240),
(360, 1000, 1020, 1280),
]
for idx_box, box in enumerate(candidate_boxes, 1):
try:
x1, y1, x2, y2 = box
self.cut_pic(x1, y1, x2, y2, '', f'fudai_tasks_{idx_box}', self.y_pianyi)
txt = str(self.operation.analyse_pic_word(f'fudai_tasks_{idx_box}', 0) or "").strip()
if txt:
task_texts.append(txt)
except Exception:
continue
task_text = " ".join(task_texts)
full_check = fc_chk + " " + task_text
chinese_num_chars = "零一二三四五六七八九十百千两"
patt_watch = rf"(?:需?看|观看|看)(?:直播)?\s*(?:\d+|[{chinese_num_chars}]+)\s*分钟"
if re.search(patt_watch, full_check):
print("[预约跳过] 检测到需观看任务,跳过记录预约:{} / {}".format(fc_chk, task_text))
# 诊断日志:输出 OCR 候选区域文本,便于后续调整坐标
try:
print("[预约跳过] 任务区域 OCR 候选文本:", task_texts)
except Exception:
pass
try:
self._inc("fudai_skip_watch_required")
except Exception:
pass
try:
self._record_event("reservation_drop_watch_task", {"content": full_check})
except Exception:
pass
_close_fudai_detail(x, reason="watch_task_skip_before_reservation")
self.operation.delay(1)
if needswitch:
swipe_up_switch("检测到观看任务,跳过并上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
except Exception:
pass
item = _add_reservation(float(future_timestamp), pv, fudai_content_text or "")
print("[预约] 记录高价值福袋:{}元,预计开奖时间:{}(队列共{}个),将于开奖前{}秒回退参与".format(
pv, dt_str, len(reservations), ahead
))
# 当预约队列达到上限:回到“开奖最近(时间最短)”的预约直播间等待,避免继续上划导致位置漂移
try:
cap = int(self.high_value_fudai_max_reservations or 5)
except Exception:
cap = 5
if cap < 1:
cap = 1
_sorted_reservations()
if len(reservations) >= cap and reservations:
target = reservations[0]
try:
target_dt = datetime.fromtimestamp(float(target.get("future_ts") or 0.0)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
target_dt = str(target.get("future_ts"))
try:
target_value_yuan = float(target.get("prize_value_yuan") or 0.0)
except Exception:
target_value_yuan = 0.0
target_content = str(target.get("content") or "").replace("\r", " ").replace("\n", " ").strip()
if len(target_content) > 60:
target_content = target_content[:60] + "..."
# 队列摘要:最多展示前 6 个(按开奖时间排序)
queue_brief_parts = []
try:
_sorted_reservations()
for idx, r in enumerate(reservations[:6], 1):
try:
tts = float(r.get("future_ts") or 0.0)
tshort = datetime.fromtimestamp(tts).strftime('%H:%M:%S') if tts > 0 else "-"
except Exception:
tshort = "-"
try:
vshort = float(r.get("prize_value_yuan") or 0.0)
except Exception:
vshort = 0.0
cshort = str(r.get("content") or "").replace("\r", " ").replace("\n", " ").strip()
if len(cshort) > 16:
cshort = cshort[:16] + "..."
# 格式:序号.价值元(开奖时间)[内容]
queue_brief_parts.append("{}:{}元({})[{}]".format(idx, vshort, tshort, cshort))
except Exception:
queue_brief_parts = []
queue_brief = " | ".join(queue_brief_parts)
back_times = int(room_pos - int(target.get("pos_seen") or 0))
if back_times < 0:
back_times = 0
try:
max_back = int(self.high_value_fudai_max_swipe_back)
except Exception:
max_back = 60
# 约定:max_back=0 表示不限制回退次数
if max_back > 0:
back_times = min(back_times, max_back)
# 先关闭详情,再回退
_close_fudai_detail(x, reason="队列已满")
print("[预约] 队列已满:关闭福袋详情,回到开奖最近的预约直播间等待")
self.operation.delay(1)
if back_times > 0:
swipe_down_back(back_times, "[预约] 队列已满,回退到最早开奖预约直播间(回退{}次)".format(back_times))
else:
print("[预约] 队列已满:当前已在最早开奖预约直播间")
# 已经回到目标直播间:同步更新该预约的 pos_seen,保证到参与窗口时 back_times=0
try:
target["pos_seen"] = int(room_pos)
except Exception:
pass
# 锁定等待窗口直到进入参与窗口,期间不再上划切换
try:
join_window_ts = float(target.get("future_ts") or 0.0) - float(ahead)
except Exception:
join_window_ts = time.time() + 60
reservation_focus_until_ts = max(time.time() + 10, join_window_ts + 5)
self._log_kv(
"预约",
"预约队列已满:回到最早开奖项等待",
cap=cap,
qsize=len(reservations),
target_future=target_dt,
target_value_yuan=target_value_yuan,
target_content=target_content,
queue_brief=queue_brief,
back_times=back_times,
)
_write_reservations_state("queue_full_back")
self.operation.delay(2)
continue
# 关闭详情并继续切换直播间;同时开始记录 swipes_since
self.click(500, 470)
print("[预约] 已记录预约,关闭福袋详情")
self.operation.delay(1)
swipe_up_switch("[预约] 继续切换直播间(等待预约参与窗口)")
self.operation.delay(post_switch_delay_s)
continue
if needswitch and lastsecond >= 60 * wait_minutes: # 如果需要切换且倒计时时间大于设定的分钟
self.click(x + 45, 430) # 点击刚才打开小福袋的位置
print("点击小福袋位置,关闭福袋详情")
self.operation.delay(1)
swipe_up_switch("抽奖倒计时时间大于{}分钟,暂不参与,上划切换直播间".format(wait_minutes))
self.operation.delay(post_switch_delay_s)
continue
if not self.attend_choujiang(): # 如果参与抽奖失败
if self.last_attend_fail_reason == "fansclub_required" and self.fansclub_fail_action == "stay":
print("粉丝团门槛未解决:不切换直播间,等待10秒后重试")
self.operation.delay(10)
continue
swipe_up_switch("参与抽奖失败,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
# 等待开奖结果:可中断(预约窗口到达时立刻抢占)
total_wait_s = max(0.0, float(lastsecond) + 5.0)
waited_s = 0.0
step_s = 1.5
preempted_by_reservation = False
# 记录参与点击时间,用于诊断参与->开奖识别耗时
t_participate = time.time()
detect_attempts = 0
first_detect_ts = None
# 在正式开始轮询结果前,先静默等待直到预计开奖前 poll_before_open_seconds 秒
try:
poll_advance = int(getattr(self, 'poll_before_open_seconds', 10) or 10)
except Exception:
poll_advance = 10
try:
start_poll_ts = float(future_timestamp) - float(poll_advance)
except Exception:
start_poll_ts = 0.0
# 标志:若在正式轮询前已即时检测到结果,则可跳过低频等待
skip_wait_due_to_initial_result = False
# 若开奖时间已到且已参与,则先做一次立即检测,避免继续等待丢失弹窗
initial_check_result = None
try:
if time.time() >= float(future_timestamp):
try:
self._shot_and_diagnose("等待开奖-立即检测", "参与后立即检测开奖", self.device_id, diagnose=False)
except Exception:
pass
try:
r0 = self.check_lucky_draw_result()
if r0 is not False:
detect_attempts += 1
first_detect_ts = time.time()
try:
self._log_kv("开奖识别耗时", elapsed_s=round(first_detect_ts - t_participate, 3), attempts=detect_attempts)
except Exception:
pass
initial_check_result = r0
# 标记:已即时检测到结果,跳过后续低频等待,直接进入结果处理
skip_wait_due_to_initial_result = True
except Exception:
pass
except Exception:
initial_check_result = None
# 若当前时间早于开始轮询时间,则先进入低频等待(可被预约抢占)
skip_wait_due_to_initial_result = False
if start_poll_ts > time.time():
try:
dt_to_start = int(max(0, start_poll_ts - time.time()))
except Exception:
dt_to_start = 0
try:
dt_strf = datetime.fromtimestamp(float(future_timestamp)).strftime('%Y-%m-%d %H:%M:%S')
except Exception:
dt_strf = str(future_timestamp)
self._log_kv("等待开奖", "预轮询等待", target_future=dt_strf, remain_to_join_window_s=dt_to_start)
# 以小片段睡眠,期间允许预约抢占
try:
while time.time() < start_poll_ts:
if (not reservation_after_action_pending) and _reservation_should_preempt():
preempted_by_reservation = True
self._log_kv("等待开奖被预约抢占", remain_wait_s=round(total_wait_s - waited_s, 1))
break
# 若之前已在 start_poll 前立即检测到结果,则跳过后续等待,进入处理
if skip_wait_due_to_initial_result:
break
to_sleep = min(1.0, start_poll_ts - time.time())
if to_sleep <= 0:
break
self.operation.delay(to_sleep)
except Exception:
pass
if not skip_wait_due_to_initial_result:
while waited_s < total_wait_s:
# 当当前正在处理预约(reservation_after_action_pending=True)时,
# 不允许其它预约抢占等待(避免在参与后判定延迟时被打断造成重复回退)。
if (not reservation_after_action_pending) and _reservation_should_preempt():
remain_wait_s = round(total_wait_s - waited_s, 1)
self._log_kv("等待开奖被预约抢占", remain_wait_s=remain_wait_s)
preempted_by_reservation = True
break
chunk = min(step_s, total_wait_s - waited_s)
if chunk <= 0:
break
# 等待一小段时间后立刻检查是否出现结果弹窗,减少遗漏
self.operation.delay(chunk)
waited_s += chunk
try:
# 快速截图诊断(不开启重 OCR),避免频繁 OCR 导致延迟
self._shot_and_diagnose("等待开奖-轮询", "轮询是否已弹出结果", self.device_id, diagnose=False)
except Exception:
pass
try:
check_result = self.check_lucky_draw_result()
if check_result is not False:
# 记录首次检测到的时间
detect_attempts += 1
if first_detect_ts is None:
first_detect_ts = time.time()
try:
self._log_kv("开奖识别耗时", elapsed_s=round(first_detect_ts - t_participate, 3), attempts=detect_attempts)
except Exception:
pass
# 跳出等待循环,进入处理结果流程
break
except Exception:
pass
else:
# 跳过等待:已在开始轮询前通过即时检测拿到结果,后续使用 initial_check_result 处理
pass
if preempted_by_reservation:
# 预约优先:不等待弹窗/结果,回主循环立刻执行回退参与
continue
# 如果之前做过立即检测且有结果,或常规轮询检测到结果,统一在下面的循环里处理。
have_clicked_no_award = False
first_iter = True
while True:
detect_attempts += 1
t_iter = time.time()
try:
if first_iter and (initial_check_result is not None):
check_result = initial_check_result
else:
check_result = self.check_lucky_draw_result()
except Exception:
check_result = False
first_iter = False
if check_result is not False and first_detect_ts is None:
first_detect_ts = time.time()
elapsed = first_detect_ts - t_participate
try:
self._log_kv("开奖识别耗时", elapsed_s=round(elapsed, 3), attempts=detect_attempts)
except Exception:
pass
try:
print(f"[开奖诊断] 参与后首次检测到结果: elapsed={elapsed:.3f}s attempts={detect_attempts}")
except Exception:
pass
if check_result is False: # 没有弹窗需要处理
break
elif check_result in (1, 2, 3): # 未中奖流程
try:
self.click(540, 1270)
print("没有抽中,点击:我知道了,关闭弹窗")
self.operation.delay(3)
except Exception:
pass
have_clicked_no_award = True
if check_result == 2: # 处理特殊状态(领取并使用)
try:
print("未中奖点击了优惠券‘领取并使用’按钮,点击外部关闭商品浏览弹窗")
self.click(x, 380) # 点击刚才打开福袋的上方位置
self.operation.delay(2)
except Exception:
pass
else: # 中奖流程(返回y坐标)
try:
print("检测到中奖结果,执行领奖流程")
self.get_reward(check_result)
except Exception:
pass
continue
if have_clicked_no_award: # 如果点击了没有中奖
# 若处于“回退到预约直播间后的停留窗口”,不进入养号;短暂停留即可
if reservation_focus_until_ts > 0 and time.time() < reservation_focus_until_ts:
self.operation.delay(2)
else:
# 只保留推荐页养号:未中奖后固定执行一次推荐页养号
secs = self._yanghao_get_recommend_seconds()
print("[养号] 未中奖后执行推荐页养号 {} 秒".format(secs))
self._yanghao_wait(secs)
# 若刚执行过“预约回退参与”,按配置决定完成后的动作
skip_switch_after = False
if reservation_after_action_pending:
reservation_after_action_pending = False
if self.high_value_fudai_after_action == "stay":
s = int(self.high_value_fudai_after_stay_seconds or 0)
if s > 0:
reservation_focus_until_ts = time.time() + s
print("[预约] 完成预约福袋后:停留当前直播间 {} 秒(期间不自动切换直播间)".format(s))
else:
reservation_focus_until_ts = time.time() + 60
print("[预约] 完成预约福袋后:停留当前直播间(默认60秒)")
skip_switch_after = True
else:
reservation_focus_until_ts = 0.0
if not needswitch:
continue
if skip_switch_after:
self.operation.delay(2)
continue
swipe_up_switch("结束抽奖,上划切换直播间")
self.operation.delay(post_switch_delay_s)
continue
elif self.check_zhibo_is_closed(): # 如果是直播间关闭了
print("直播间已关闭,上划切换直播间")
_clear_reservations("直播间关闭(抽奖后)")
swipe_up_switch("直播间已关闭,上划切换直播间")
self.operation.delay(10)
continue
elif self.check_in_zhibo_list(): # 如果已经退出到直播间列表
_clear_reservations("已在直播列表(抽奖后)")
self.into_zhibo_from_list()
swipe_times = 0 # 滑动次数归0
continue
if __name__ == '__main__':
try:
from version import print_version_banner
print_version_banner("douyin_fudai")
except Exception:
pass
douyin = fudai_analyse()
# 常由 Web GUI 以子进程方式启动;跨进程状态通过文件/日志传递