from __future__ import annotations import re import time from typing import Tuple, Any from douyin_utils import normalize_countdown_text, extract_prize_value_yuan import douyin_reservation_logic def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, float]: """获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。""" 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:秒(第三段通常包含“后开奖”) analyser.cut_pic(x1, y1, x1 + seg, y2, "", "福袋倒计时_分钟", analyser.y_pianyi) analyser.cut_pic(x1 + seg, y1, x1 + 2 * seg, y2, "", "福袋倒计时_秒", analyser.y_pianyi) mm_raw = analyser.operation.analyse_pic_word("福袋倒计时_分钟", 0) ss_raw = analyser.operation.analyse_pic_word("福袋倒计时_秒", 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),减少右侧干扰,确保内容完整 analyser.cut_pic(390, 1240, 980, 1470, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情 # 优化:稍微扩大高度(1220->1230),确保包含完整的"后开奖"文字 countdown_box = (390, 1110, 690, 1230) analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时 # 优化:增加高度(1560->1580),确保包含"元"等单位文字 analyser.cut_pic(390, 1460, 1000, 1580, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格 elif renwu == 1: # 如果是1个任务的 # 优化:稍微缩小宽度,增加高度,减少干扰 analyser.cut_pic(390, 1300, 980, 1530, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情 # 优化:稍微扩大高度,确保完整 countdown_box = (390, 1180, 690, 1300) analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时 # 优化:增加高度,包含单位 analyser.cut_pic(390, 1520, 1000, 1630, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格 elif renwu == 3: # 如果是3个任务的 # 优化:稍微缩小宽度,增加高度 analyser.cut_pic(390, 1160, 980, 1390, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情 # 优化:稍微扩大高度 countdown_box = (390, 1010, 690, 1130) analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时 # 优化:增加高度 analyser.cut_pic(390, 1380, 1000, 1490, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格 else: # 优化:稍微缩小宽度,增加高度 analyser.cut_pic(390, 1600, 980, 1830, "", "福袋内容", analyser.y_pianyi) # 福袋内容详情 # 优化:稍微扩大高度 countdown_box = (390, 1460, 690, 1580) analyser.cut_pic(*countdown_box, "", "福袋倒计时", analyser.y_pianyi) # 完整福袋详情倒计时 # 优化:增加高度 analyser.cut_pic(390, 1820, 1000, 1930, "", "福袋价值", analyser.y_pianyi) # 奖品价值/价格 fudai_content_raw = analyser.operation.analyse_pic_word("福袋内容", 0) participants, copies, fudai_content_text = _extract_participants_and_clean(fudai_content_raw) analyser._log_kv("福袋", "识别福袋内容", level="INFO", content=fudai_content_text[:60] if fudai_content_text else "未识别到") # 记录进入直播间到识别到福袋的耗时(仅记录一次) try: if getattr(analyser, "_enter_live_ts", 0.0) and not getattr(analyser, "_enter_live_fudai_logged", False): try: secs = float(time.time() - float(analyser._enter_live_ts or 0.0)) except Exception: secs = -1.0 reason = str(getattr(analyser, "_enter_live_reason", "") or "") analyser._log_kv("性能", "进入直播间到识别福袋耗时", seconds=round(secs, 2), enter_reason=reason) try: analyser._enter_live_fudai_logged = True except Exception: pass if copies: analyser._log_kv("福袋", "识别福袋信息", copies=copies, participants=participants if participants else 0) except Exception: pass # 倒计时:优先用完整OCR(更快,只需1次),失败再用分割OCR time_text = "" time_raw = analyser.operation.analyse_pic_word("福袋倒计时", 0) time_text = normalize_countdown_text(time_raw) if not time_text or not _parse_mm_ss(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 analyser._log_kv("福袋", "识别倒计时", countdown=time_text if time_text else "未识别到") value_raw = analyser.operation.analyse_pic_word("福袋价值", 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 analyser._log_kv("福袋", "识别奖品价值", value_yuan=show_value) return fudai_content_text, time_text, participants, copies, prize_value_yuan def check_contain(analyser, contains: str = "") -> bool: """检查福袋内容是否命中“黑名单”关键词(只保留黑名单逻辑,不再使用白名单)。 返回值语义(调整后): - True : “建议丢弃”(内容命中黑名单 contains_not_want) - False : “可以保留”(未命中黑名单,或凌晨时段不做内容过滤) """ try: hour = int(analyser.operation.get_current_hour()) except Exception: hour = -1 # 凌晨:不对内容做要求(不过滤) if 0 < hour < 7: try: analyser._log_kv("筛选", "凌晨不过滤福袋内容", hour=hour, contains=contains[:50] if contains else "") except Exception: pass return False try: for contain in getattr(analyser, "contains_not_want", []) or []: if contain and contain in (contains or ""): try: analyser._log_kv("筛选", "福袋内容命中黑名单,将丢弃", keyword=contain, contains=contains[:80] if contains else "") except Exception: pass return True try: analyser._log_kv("筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "") except Exception: pass return False except Exception: # 容错:异常时不过滤 try: analyser._log_kv("筛选", "check_contain 异常,默认保留", contains=contains[:80] if contains else "") except Exception: pass return False def attend_choujiang(analyser) -> bool: """点击参与抽奖。""" analyser.last_attend_fail_reason = "" click_times = 0 while click_times < 2: analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") # 参与福袋抽奖的文字 # 优化:尝试多种OCR模式提高精准度(优先保证精准) attend_button_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") if not attend_button_text or not any( k in attend_button_text for k in ("参与成功", "还需看播", "评论", "参与抽奖", "开始观看", "参与") ): attend_button_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "") analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖 analyser._log_kv("参与", "已参与,等待开奖", result="已参与") analyser.click(500, 470) # 点击刚才打开福袋的旁边位置 analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return True elif ("活动已结束" in attend_button_text) or ("活动己结束" in attend_button_text): # 活动结束:按一次返回键退出详情 analyser.last_attend_fail_reason = "activity_ended" try: analyser._log_kv("参与", "活动已结束:按返回键退出详情", result="activity_ended") except Exception: pass try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(0.5) except Exception: try: analyser.click(500, 470) except Exception: pass return False elif "还需看播" in attend_button_text: # 如果识别到需要看播 analyser.last_attend_fail_reason = "watch_required" analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛") analyser.click(500, 470) analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return False elif "无法参与" in attend_button_text: analyser._log_kv("参与", "无法参与(条件不满足)", result="无法参与") analyser.click(500, 470) analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return False elif "时长不足" in attend_button_text: analyser._log_kv("参与", "无法参与(看播时长不足)", result="时长不足") analyser.click(500, 470) analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return False elif "评论" in attend_button_text: analyser.click(500, 2060) analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="评论") return True elif "参与抽奖" in attend_button_text: analyser.click(500, 2060) analyser._log_kv("参与", "点击参与抽奖", action="点击参与", mode="普通") return True elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text: # 需要粉丝团门槛:先点击尝试进入加入/点亮流程 analyser.last_attend_fail_reason = "fansclub_required" analyser.click(500, 2060) analyser._log_kv("参与", "粉丝团门槛:已点击加入按钮", result="需要粉丝团") analyser.operation.delay(2) if not analyser.auto_join_fansclub: analyser._log_kv("参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15) analyser.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: analyser._shot_and_diagnose("粉丝团", "粉丝团后定位福袋详情({}/{})".format(i + 1, max_steps), analyser.device_id) except Exception: pass try: st, seen = analyser._diagnose_stage_from_current_screen() except Exception: st, seen = "", "" if st == "FUDai_DETAIL": return True if st == "FANSCLUB_JOIN": # 在加入页点击底部“加入粉丝团”按钮(与详情页按钮同位置) analyser._log_kv("参与", "粉丝团加入页:点击加入粉丝团", stage=st, seen=seen, attempt=i + 1) try: analyser.click(500, 2060) except Exception: pass analyser.operation.delay(2) # 尝试返回到详情 try: analyser.operation.click_back(analyser.device_id) analyser.operation.delay(1) except Exception: pass continue # 已经回到直播间/列表时:不要继续按返回键,避免退出直播 if st in ("IN_LIVE_ROOM", "FOLLOW_LIST", "LIVE_LIST"): analyser._log_kv("参与", "已离开福袋详情:停止继续返回", stage=st, seen=seen) return False # 其它未知弹窗:尝试一次返回 analyser._log_kv("参与", "粉丝团流程:尝试返回", stage=st, seen=seen) try: analyser.operation.click_back(analyser.device_id) except Exception: pass analyser.operation.delay(1) return False ok = _recover_to_fudai_detail_after_fansclub() if ok: analyser._log_kv("参与", "粉丝团流程结束:已回到福袋详情", result="回到详情") return attend_choujiang(analyser) analyser._log_kv("参与", "粉丝团流程失败:未回到福袋详情", result="粉丝团门槛仍未解决") analyser.operation.delay(1.2) try: analyser.operation.get_screenshot(analyser.device_id) except Exception: pass if analyser.check_in_fudai_detail(): analyser._log_kv("参与", "粉丝团流程失败:仍在详情页,执行关闭", stage="FUDai_DETAIL") try: analyser.click(500, 470) except Exception: pass analyser.operation.delay(0.8) else: analyser._log_kv("参与", "粉丝团流程失败:已不在详情页,视为已退出", stage="UNKNOWN") try: analyser._log_kv("参与", "粉丝团门槛仍未解决", result="粉丝团门槛仍未解决") except Exception: pass return False else: # 未识别到任何可用文案:再尝试一次 analyser._log_kv("参与", "未识别到可用参与按钮文案", text=attend_button_text or "") click_times += 1 analyser.operation.delay(1) continue analyser._log_kv("参与", "参与抽奖多次点击失败", result="多次失败") return False def check_lucky_draw_result(analyser): """判定福袋抽奖的结果。""" # 速度优化:只在需要时截图(如果有最近截图且缓存有效,可跳过) cache_key = ("lucky_draw_result", 0) now = time.time() need_screenshot = True # 检查缓存是否有效 if cache_key in analyser._ocr_cache: cached_ts, cached_result = analyser._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: analyser._shot_and_diagnose("开奖结果", "识别是否中奖/未中奖", analyser.device_id) # 优化:扩大区域(300-800, 600-800),确保包含完整的开奖结果文字"没有抽中福袋" analyser.cut_pic(300, 600, 800, 800, "", "抽奖结果") # 没有抽中福袋位置 # 诊断开始时间 t0 = time.time() # 检查缓存 if cache_key in analyser._ocr_cache: cached_ts, cached_result = analyser._ocr_cache[cache_key] if (now - cached_ts) < analyser._ocr_cache_ttl: lucky_draw_result = cached_result else: lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 0) or "") if not lucky_draw_result or ("没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result): lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 1) or "") analyser._ocr_cache[cache_key] = (now, lucky_draw_result) else: lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 0) or "") if not lucky_draw_result or ("没有抽中" not in lucky_draw_result and "抽中福袋" not in lucky_draw_result): lucky_draw_result = str(analyser.operation.analyse_pic_word("抽奖结果", 1) or "") analyser._ocr_cache[cache_key] = (now, lucky_draw_result) dur = time.time() - t0 try: brief = (lucky_draw_result or "").replace("\n", " ")[:140] except Exception: brief = "" try: analyser._log_kv( "开奖诊断", "lucky_draw_result", brief=brief, ocr_dur=round(dur, 2), ) except Exception: pass if "没有抽中" in (lucky_draw_result or ""): # 速度优化:使用缓存避免重复OCR cache_key2 = ("no_award_confirm", 0) dur2 = 0.0 # Initialize dur2 to avoid unbound variable if cache_key2 in analyser._ocr_cache: cached_ts2, cached_result2 = analyser._ocr_cache[cache_key2] if (now - cached_ts2) < analyser._ocr_cache_ttl: no_award_confirm = cached_result2 else: t1 = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) dur2 = time.time() - t1 else: t1 = time.time() analyser.cut_pic(181, 1261, 890, 1389, "", "无奖励确认") no_award_confirm = analyser.operation.analyse_pic_word("无奖励确认") analyser._ocr_cache[cache_key2] = (time.time(), no_award_confirm) dur2 = time.time() - t1 try: brief2 = (no_award_confirm or "").replace("\n", " ")[:140] except Exception: brief2 = "" try: analyser._log_kv( "开奖诊断", "no_award_confirm", brief=brief2, ocr_dur=round(dur2, 2), ) except Exception: pass if "我知道了" in (no_award_confirm or ""): return 1 elif "领取并使用" in (no_award_confirm or ""): return 2 return 3 elif "抽中福袋" in (lucky_draw_result or ""): try: analyser._log_kv("开奖诊断", "恭喜中奖了", result_text=brief) except Exception: pass # 速度优化:优先检测第一个常见位置,命中即返回 y_value = [1438, 1490] for y in y_value: cache_key3 = (f"have_read_user_agreement_{y}", 0) have_read_user_agreement = None dur3 = 0.0 if cache_key3 in analyser._ocr_cache: cached_ts3, cached_result3 = analyser._ocr_cache[cache_key3] if (now - cached_ts3) < analyser._ocr_cache_ttl: have_read_user_agreement = cached_result3 if not have_read_user_agreement: t2 = time.time() analyser.cut_pic(280, y - 35, 670, y + 35, "", f"已阅读用户协议_{y}") have_read_user_agreement = analyser.operation.analyse_pic_word(f"已阅读用户协议_{y}") analyser._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 = "" try: analyser._log_kv( "开奖诊断", "have_read_user_agreement", brief=brief3, ocr_dur=round(dur3, 2), y=y, ) except Exception: pass if "已阅读" in (have_read_user_agreement or ""): return y return False def check_have_reward_notice_confirm(analyser) -> bool: """判断是否有领奖的二次确认提醒。""" analyser._shot_and_diagnose("领奖确认", "识别是否有我知道了", analyser.device_id) analyser.cut_pic(370, 1350, 680, 1440, "", "奖励通知确认") reward_notice_confirm = analyser.operation.analyse_pic_word("奖励通知确认", 1) if "我知道了" in (reward_notice_confirm or ""): try: analyser._log_kv( "开奖诊断", "存在奖品领取提醒", text=(reward_notice_confirm or "")[:80], ) except Exception: pass return True return False def check_in_order_confirm_page(analyser) -> bool: """判断是否在中奖下单后的购买成功的页面。""" analyser._shot_and_diagnose("下单结果", "识别是否购买成功页", analyser.device_id) analyser.cut_pic(370, 120, 700, 220, "", "订单确认") order_confirm = analyser.operation.analyse_pic_word("订单确认") if "购买成功" in (order_confirm or ""): try: analyser._log_kv( "开奖诊断", "订单确认页面:购买成功", text=(order_confirm or "")[:80], ) except Exception: pass return True return False def get_reward(analyser, reward_y: int = 0) -> None: """中奖后领奖然后返回。""" analyser.operation.save_reward_pic(analyser.device_id) try: analyser._log_kv("领奖", "保存中奖截图", step="save_reward_pic") except Exception: pass analyser.click(243, reward_y) # 勾选协议 analyser.operation.delay(1) analyser.click(540, reward_y - 140) # 点击领取 try: analyser._log_kv("领奖", "勾选协议并点击领取", reward_y=reward_y) except Exception: pass analyser.operation.delay(5) analyser.click(886, 2170) # 点击下单 try: analyser._log_kv("领奖", "点击下单") except Exception: pass analyser.operation.delay(10) # 循环检查下单结果,增加保护避免极端死循环 max_checks = 5 checks = 0 while checks < max_checks and check_in_order_confirm_page(analyser): checks += 1 analyser.operation.click_back(analyser.device_id) try: analyser._log_kv("领奖", "点击回退按钮", check_round=checks) except Exception: pass analyser.operation.delay(4) try: analyser._log_kv("领奖", "下完单返回到直播间", checks=checks) except Exception: pass analyser.operation.delay(4) if check_lucky_draw_result(analyser): try: analyser._log_kv("领奖", "领奖弹窗未关闭,准备关闭") except Exception: pass analyser.click(540, reward_y + 180) try: analyser._log_kv( "领奖", "点击关闭领奖弹窗", x=540, y=(reward_y + 180) * analyser.resolution_ratio_y // 2400, ) except Exception: pass analyser.operation.delay(2) analyser.operation.save_reward_pic(analyser.device_id) try: analyser._log_kv("领奖", "保存关闭领奖弹窗后的截图") except Exception: pass analyser.operation.click_back(analyser.device_id) analyser.operation.delay(2) if check_have_reward_notice_confirm(analyser): try: analyser._log_kv("领奖", "提醒领奖弹窗未关闭,点击我知道了") except Exception: pass analyser.click(540, 1400) analyser.operation.delay(2) try: analyser._log_kv("领奖", "关闭中奖提醒后等待", wait_seconds=30) except Exception: pass analyser.operation.delay(30) def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 返回: (skip, reason) 其中 reason 为简单文字原因,便于日志查看。 """ if not isinstance(detail, tuple) or len(detail) < 6: return False, "detail_tuple_invalid" content = str(detail[0] or "") time_text = str(detail[1] or "") try: participants = int(detail[2] or 0) except Exception: participants = 0 try: copies = int(detail[3] or 0) except Exception: copies = 0 try: prize_value_yuan = float(detail[4] or 0.0) except Exception: prize_value_yuan = 0.0 cd_start, cd_end = None, None if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2: cd_start, cd_end = detail[5][0], detail[5][1] now = time.time() remain_seconds = None try: if isinstance(cd_end, (int, float)) and cd_end > now: remain_seconds = float(cd_end - now) try: analyser._log_kv( "筛选", "倒计时计算成功", cd_end=cd_end, now=now, 剩余秒数=remain_seconds, ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时计算失败或已过期", cd_end=cd_end, now=now, cd_end类型=type(cd_end).__name__, cd_end大于now=bool(isinstance(cd_end, (int, float)) and cd_end > now) if isinstance(cd_end, (int, float)) else False, ) except Exception: pass except Exception as e: remain_seconds = None try: analyser._log_kv( "筛选", "倒计时计算异常", 异常=str(e), 异常类型=type(e).__name__, ) except Exception: pass # 读取配置阈值 try: min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0) except Exception: min_value = 0.0 try: min_participants = int(getattr(analyser, "min_participants", 0) or 0) except Exception: min_participants = 0 try: max_participants = int(getattr(analyser, "max_participants", 0) or 0) except Exception: max_participants = 0 skip_if_gt = 0 # Initialize before try block try: skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0) except Exception: skip_if_gt = 0 # 记录所有配置值和实际值,便于调试 try: analyser._log_kv( "筛选", "should_skip_fudai_by_config 开始检查", 配置_最小价值=min_value, 配置_最小参与人数=min_participants, 配置_最大参与人数=max_participants, 配置_倒计时大于秒数=skip_if_gt, 实际_价值=prize_value_yuan, 实际_参与人数=participants, 实际_份数=copies, 实际_剩余秒数=int(remain_seconds) if remain_seconds is not None else None, 实际_内容=content[:60] if content else "", ) except Exception: pass # 1) 价值过滤 if min_value > 0: if prize_value_yuan > 0: if prize_value_yuan < min_value: try: analyser._log_kv( "筛选", "价值过滤:丢弃", 原因=f"value_lt_{min_value}", 实际价值=prize_value_yuan, 配置最小价值=min_value, ) except Exception: pass return True, f"value_lt_{min_value}" else: try: analyser._log_kv( "筛选", "价值过滤:通过", 实际价值=prize_value_yuan, 配置最小价值=min_value, ) except Exception: pass else: try: analyser._log_kv( "筛选", "价值过滤:跳过(未识别到价值)", 实际价值=prize_value_yuan, ) except Exception: pass # 2) 参与人数过滤 if min_participants > 0: if participants > 0: if participants < min_participants: try: analyser._log_kv( "筛选", "参与人数过滤:丢弃(小于最小值)", 原因=f"participants_lt_{min_participants}", 实际参与人数=participants, 配置最小参与人数=min_participants, ) except Exception: pass return True, f"participants_lt_{min_participants}" else: try: analyser._log_kv( "筛选", "参与人数过滤:通过(最小值检查)", 实际参与人数=participants, 配置最小参与人数=min_participants, ) except Exception: pass else: try: analyser._log_kv( "筛选", "参与人数过滤:跳过(未识别到参与人数)", 实际参与人数=participants, ) except Exception: pass if max_participants > 0: if participants > 0: if participants > max_participants: try: analyser._log_kv( "筛选", "参与人数过滤:丢弃(大于最大值)", 原因=f"participants_gt_{max_participants}", 实际参与人数=participants, 配置最大参与人数=max_participants, ) except Exception: pass return True, f"participants_gt_{max_participants}" else: try: analyser._log_kv( "筛选", "参与人数过滤:通过(最大值检查)", 实际参与人数=participants, 配置最大参与人数=max_participants, ) except Exception: pass # 3) 倒计时过滤(如果倒计时大于阈值,就不参与;但如果价值达到高价值阈值,可以预约) # 注意:这个过滤在 basic_join_decision 中会被特殊处理,如果价值达到高价值阈值,即使倒计时大于阈值也会记录预约 if skip_if_gt > 0: try: analyser._log_kv( "筛选", "倒计时过滤:开始检查", 配置阈值秒数=skip_if_gt, 实际剩余秒数=int(remain_seconds) if remain_seconds is not None else None, 是否有倒计时数据=remain_seconds is not None, 说明="如果剩余秒数大于阈值,则不参与(但高价值福袋可预约)", ) except Exception: pass if remain_seconds is not None: # 如果剩余秒数 > 阈值,就丢弃(不参与) if remain_seconds > skip_if_gt: try: analyser._log_kv( "筛选", "倒计时过滤:丢弃(剩余秒数大于阈值,不参与)", 原因=f"countdown_gt_{skip_if_gt}", 实际剩余秒数=int(remain_seconds), 配置阈值秒数=skip_if_gt, 判断条件=f"{remain_seconds} > {skip_if_gt} = True", 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", ) except Exception: pass return True, f"countdown_gt_{skip_if_gt}" else: try: analyser._log_kv( "筛选", "倒计时过滤:通过(剩余秒数小于等于阈值,可以参与)", 实际剩余秒数=int(remain_seconds), 配置阈值秒数=skip_if_gt, 判断条件=f"{remain_seconds} > {skip_if_gt} = False", ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时过滤:跳过(未识别到倒计时或倒计时已过期)", 剩余秒数=remain_seconds, cd_start=cd_start, cd_end=cd_end, now=now, ) except Exception: pass else: try: analyser._log_kv( "筛选", "倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)", 配置阈值秒数=skip_if_gt, ) except Exception: pass # 4) 内容关键词过滤(复用 check_contain 逻辑) content_check_result = check_contain(analyser, content) if content_check_result: try: analyser._log_kv( "筛选", "内容关键词过滤:丢弃", 原因="content_not_wanted", 内容=content[:60] if content else "", ) except Exception: pass return True, "content_not_wanted" else: try: analyser._log_kv( "筛选", "内容关键词过滤:通过", 内容=content[:60] if content else "", ) except Exception: pass try: analyser._log_kv( "筛选", "should_skip_fudai_by_config 通过(所有检查项均通过)", content=content[:60] if content else "", participants=participants, copies=copies, value_yuan=prize_value_yuan, remain_seconds=int(remain_seconds) if remain_seconds is not None else None, ) except Exception: pass return False, "ok" def basic_join_decision(analyser: Any, detail: Tuple) -> bool: """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 返回: True 表示已经参与或已处理完成; False 表示未参与(例如被配置筛掉或参与失败)。 """ # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 content = "" prize_value_yuan = 0.0 countdown_tuple = None try: if isinstance(detail, tuple) and len(detail) >= 6: content = str(detail[0] or "") prize_value_yuan = float(detail[4] or 0.0) countdown_tuple = detail[5] except Exception: pass # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 try: last_status = getattr(analyser, "_last_fudai_detail_status", "") if last_status == "coupon_popup": try: analyser._log_kv( "参与", "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", ) except Exception: pass return False elif last_status == "validation_failed": try: analyser._log_kv( "参与", "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", ) except Exception: pass return False except Exception: pass # 额外验证:使用验证函数检查数据合理性 try: # 在函数开头导入,避免作用域问题 import douyin_fudai_detail as dfd_module is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser) if not is_valid: try: analyser._log_kv( "参与", "basic_join_decision:福袋详情数据验证失败,识别出错", validation_reason=reason, content=content[:50] if content else "", prize_value_yuan=prize_value_yuan, ) except Exception: pass return False except Exception: pass # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 if not content and prize_value_yuan == 0.0: try: analyser._log_kv( "参与", "basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", content=content, prize_value_yuan=prize_value_yuan, ) except Exception: pass return False # 检查是否启用高价值预约,以及价值是否达到阈值 try: high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False)) except Exception: high_value_enabled = False try: high_value_threshold = float( getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0 ) except Exception: high_value_threshold = 500.0 # 计算 future_timestamp(预计开奖时间戳) future_ts = 0.0 if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: try: future_ts = float(countdown_tuple[1] or 0.0) except Exception: future_ts = 0.0 # 检查价值是否达到高价值阈值 is_high_value = ( high_value_enabled and prize_value_yuan > 0 and prize_value_yuan >= high_value_threshold and future_ts > 0.0 ) # 执行筛选检查 skip, reason = should_skip_fudai_by_config(analyser, detail) # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值,则记录预约而不是丢弃 if skip and reason.startswith("countdown_gt_") and is_high_value: try: analyser._log_kv( "参与", "basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约", reason=reason, value_yuan=prize_value_yuan, threshold=high_value_threshold, ) except Exception: pass # 不关闭详情,继续走预约逻辑 skip = False reason = "high_value_reservation" if skip: try: analyser._log_kv( "参与", "basic_join_decision:按配置丢弃福袋", reason=reason, ) except Exception: pass # 丢弃时,尽量关闭详情,避免停留在详情页 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv("参与", "basic_join_decision:已关闭详情", action="close_detail") except Exception: pass # 如果允许切换直播间,则针对部分丢弃原因直接切房(黑名单/价值不达标/倒计时大于阈值) try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch and ( reason == "content_not_wanted" or reason.startswith("value_lt_") or reason.startswith("countdown_gt_") ): try: analyser._log_kv("参与", "basic_join_decision:丢弃后切换直播间", reason=reason) except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe(analyser.device_id, start_x, start_y, end_x, end_y, 300) except Exception: # 切房失败不影响主流程,直接返回 pass return False # 未被筛掉:根据配置决定“直接参与”或“记录为高价值预约” # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取 # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列 if is_high_value: # 价值达到高价值阈值:记录预约而不是立即参与 try: # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务) try: preempt_min = float( getattr(analyser, "reservation_preempt_min_value_yuan", 0.0) or 0.0 ) except Exception: preempt_min = 0.0 # 初始化预约队列容器 reservations = getattr(analyser, "reservations", None) if reservations is None: reservations = [] try: analyser.reservations = reservations # type: ignore[attr-defined] except Exception: pass # room_pos:当前直播间位置计数 try: room_pos = int(getattr(analyser, "room_pos", 0) or 0) except Exception: room_pos = 0 # 获取当前直播间标题(如果可用) room_title = "" room_title_raw = "" try: # 每次记录预约时,都重新读取直播间标题,不使用缓存 # 这样可以确保每个预约记录的是当时的真实直播间标题 try: # 在函数开头导入,避免作用域问题 import douyin_fudai_detail as dfd_module y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) room_title, room_title_raw = dfd_module.read_live_room_title_core( analyser, y_pianyi_val ) # 更新 analyser 的属性,用于状态文件显示当前直播间 try: analyser.current_room_title = room_title analyser.current_room_title_raw = room_title_raw except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "读取直播间标题失败,尝试使用缓存", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 如果读取失败,尝试使用缓存(作为兜底) room_title = str(getattr(analyser, "current_room_title", "") or "") room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "") except Exception: pass # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间) rl = douyin_reservation_logic # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致) def _write_reservation_state() -> None: try: import os import json from datetime import datetime state_path = getattr(analyser, "_reservations_state_path", None) if not state_path: # 使用与 douyin_fudai.py 相同的路径逻辑 state_path = os.path.join( os.path.dirname(__file__), "state", "reservations.json" ) # 确保目录存在 os.makedirs(os.path.dirname(state_path), exist_ok=True) # 格式化预约队列数据(与 douyin_reservation.py 格式一致) items = [] for r in reservations or []: try: ft = float(r.get("future_ts") or 0) except Exception: ft = 0.0 try: ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else "" except Exception: ft_str = str(r.get("future_str", "")) items.append({ "prize_value_yuan": float(r.get("prize_value_yuan") or 0), "content": str(r.get("content") or ""), "future_ts": ft, "future_str": ft_str, "pos_seen": int(r.get("pos_seen") or 0), "room_title": str(r.get("room_title") or ""), "room_title_raw": str(r.get("room_title_raw") or ""), "created_ts": float(r.get("created_ts") or 0), }) # 获取当前直播间标题(用于状态文件) current_title = str(getattr(analyser, "current_room_title", "") or room_title or "") current_title_raw = str(getattr(analyser, "current_room_title_raw", "") or room_title_raw or "") # 写入完整的状态数据 data = { "updated_ts": time.time(), "reason": "record_reservation", "room_pos": int(room_pos), "current_room_title": current_title, "current_room_title_raw": current_title_raw, "reservations": items, } with open(state_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) try: analyser._log_kv( "预约", "已写入预约队列状态文件", path=state_path, queue_len=len(reservations), ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "写入预约队列状态文件失败", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 记录高价值直播间(在记录预约之前) try: import douyin_high_value_room if hasattr(douyin_high_value_room, 'touch_high_value_room'): douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined] analyser=analyser, title_norm=room_title, title_raw=room_title_raw, prize_value_yuan=prize_value_yuan, reason="reservation", increment=True, content=content, pos_seen=room_pos, ) except Exception: pass # 记录预约,并检查队列是否已满 queue_full_flag = [False] def _add_reservation_with_flag(q, item): queue_full_flag[0] = rl.add_reservation_core_logic( # type: ignore[attr-defined] q, item, max_reservations=int( getattr(analyser, "high_value_fudai_max_reservations", 3) or 3 ), analyser=analyser, write_state_callback=_write_reservation_state, ) rl.record_high_value_reservation( # type: ignore[attr-defined] analyser=analyser, fudai_content_text=content, prize_value_yuan=prize_value_yuan, lastsecond=0, future_timestamp=future_ts, x=0, needswitch=True, wait_minutes=0, post_switch_delay_s=0.0, room_pos=room_pos, reservations=reservations, reservation_focus_until_ts_ref=[float(getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0)], close_detail_callback=lambda: None, swipe_up_switch_callback=lambda: None, swipe_down_back_callback=lambda: None, add_reservation_callback=_add_reservation_with_flag, sort_reservations_callback=lambda: rl._sort_reservations_inplace( # type: ignore[attr-defined] reservations ), write_state_callback=_write_reservation_state, room_title=room_title, room_title_raw=room_title_raw, ) # 如果队列已满,设置标志以便主循环处理 if queue_full_flag[0]: try: analyser.queue_full_waiting_at_earliest = False # 重置标志,让主循环处理 except Exception: pass try: analyser._log_kv( "预约", "basic_join_decision:命中高价值阈值,已记录为预约,不立即参与", value_yuan=prize_value_yuan, threshold=high_value_threshold, future_ts=int(future_ts), room_pos=room_pos, queue_len=len(reservations), preempt_min_value=preempt_min, ) except Exception: pass # 关闭当前详情,避免长时间停留 try: analyser.click(500, 470) except Exception: try: analyser.operation.click_back(analyser.device_id) except Exception: pass try: analyser._log_kv("参与", "basic_join_decision:已关闭详情", action="close_detail") except Exception: pass # 记录预约后,切换直播间继续找别的福袋 try: needswitch = bool(getattr(analyser, "needswitch", True)) except Exception: needswitch = True if needswitch: try: analyser._log_kv("参与", "basic_join_decision:记录预约后切换直播间", reason="high_value_reservation") except Exception: pass try: # 优先使用封装好的上滑切房方法 if hasattr(analyser, "swipe_up_to_next_live"): analyser.swipe_up_to_next_live() else: # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) try: rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: rx, ry = 1080, 2400 start_x = 540 * rx // 1080 start_y = 1700 * ry // 2400 end_x = 540 * rx // 1080 end_y = 700 * ry // 2400 analyser.operation.swipe(analyser.device_id, start_x, start_y, end_x, end_y, 300) except Exception: # 切房失败不影响主流程,直接返回 pass return True except Exception: # 若预约逻辑异常,退化为直接参与抽奖 try: analyser._log_kv( "预约", "basic_join_decision:记录预约时异常,退化为直接参与", ) except Exception: pass # 默认分支:未进入预约路径或预约失败,直接参与抽奖 try: analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") except Exception: pass return attend_choujiang(analyser)