fix: Clean up blank lines and enhance readability across multiple files

- Removed excessive blank lines from various markdown and Python files to improve readability and maintainability.
- Ensured consistent formatting across documentation and code files, enhancing overall project clarity.
- Updated logging mechanisms for better consistency and debugging support.
This commit is contained in:
Your Name committed 2025-12-26 13:00:07 +08:00
1 parent d0702c863f
commit f36f1a9593
34 files changed
+8657 -235

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -168,6 +168,8 @@ python cleanup_unused_files.py
+2
View File
@@ -179,6 +179,8 @@ except Exception as e:
+2
View File
@@ -382,6 +382,8 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
+2
View File
@@ -266,6 +266,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
+2
View File
@@ -237,6 +237,8 @@ python check_dependencies.py
+2
View File
@@ -216,6 +216,8 @@ douyin_guaji
+2
View File
@@ -157,6 +157,8 @@
+2
View File
@@ -369,6 +369,8 @@ douyin_fudai_finder.py
+2
View File
@@ -168,6 +168,8 @@ self.ocr = easyocr.Reader(
+126 -9
View File
@@ -1651,17 +1651,134 @@ class underlying_operations:
steps=200,
):
"""划动屏幕"""
os.system(
"{} -s {} shell input swipe {} {} {} {} {}".format(
self._adb(),
device_id,
left_up_x,
left_up_y,
right_down_x,
right_down_y,
steps,
import subprocess
adb_cmd = self._adb()
cmd = f"{adb_cmd} -s {device_id} shell input swipe {left_up_x} {left_up_y} {right_down_x} {right_down_y} {steps}"
try:
# 使用 subprocess 执行命令,捕获错误输出
result = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5.0,
text=True,
)
# 检查是否有权限错误
stderr_text = result.stderr if result.stderr else ""
has_permission_error = (
result.returncode != 0
and ("SecurityException" in stderr_text
or "INJECT_EVENTS" in stderr_text
or "Injecting to another application" in stderr_text)
)
if has_permission_error:
# 尝试使用 uiautomator(如果可用,某些设备可能支持)
try:
self._swipe_with_uiautomator(device_id, left_up_x, left_up_y, right_down_x, right_down_y)
return
except Exception:
pass
# 记录错误但不抛出异常,避免中断主流程
error_msg = stderr_text.strip() if stderr_text else "权限不足"
print(f"[警告] 滑动操作失败: {error_msg}")
print(f"[提示] 设备不允许 ADB 输入注入,可能的解决方案:")
print(f" 1. 在设备开发者选项中启用'USB调试(安全设置)'或'允许模拟点击'")
print(f" 2. 使用已 root 的设备")
print(f" 3. 某些设备需要在设置中手动授权 ADB 输入权限")
# 不抛出异常,让程序继续运行(可能只是滑动失败,其他功能仍可用)
except subprocess.TimeoutExpired:
print("[警告] 滑动操作超时")
except Exception as e:
# 降级到原来的 os.system 方法
try:
os.system(cmd)
except Exception:
print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
def _swipe_with_sendevent(self, device_id, x1, y1, x2, y2, steps):
"""使用 sendevent 方法滑动(需要 root 权限)"""
import subprocess
import time
# 获取触摸设备路径
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备")
# 简化实现:直接使用 input 命令的替代参数
# 注意:sendevent 需要 root 权限,这里只是尝试
raise Exception("sendevent 需要 root 权限,暂不支持")
def _swipe_with_uiautomator(self, device_id, x1, y1, x2, y2):
"""使用 uiautomator 滑动(如果可用)
注意:uiautomator 在某些设备上可能也需要权限,但可以尝试作为备选方案。
"""
import subprocess
# 使用 uiautomator swipe 命令
# 注意:uiautomator 命令格式可能因 Android 版本而异
# Android 5.0+: uiautomator swipe <x1> <y1> <x2> <y2> [steps]
cmd = f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
result = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5.0,
)
if result.returncode != 0:
raise Exception(f"uiautomator swipe 失败: {result.stderr.decode('utf-8', errors='ignore')}")
def _swipe_with_sendevent_improved(self, device_id, x1, y1, x2, y2, steps=50):
"""使用 sendevent 方法滑动(需要 root 权限)
这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。
优点:绕过部分权限检查
缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同
"""
import subprocess
import time
# 获取触摸设备路径(通常是 /dev/input/eventX)
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p 2>/dev/null | grep -A 10 ABS_MT",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=3.0,
)
# 解析设备路径(简化版,实际需要更复杂的解析)
# 这里只是示例,完整实现需要:
# 1. 解析 getevent -p 输出找到触摸设备
# 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max)
# 3. 将屏幕坐标转换为设备坐标
# 4. 发送 DOWN -> MOVE -> UP 事件序列
if "event" not in result.stdout.lower():
raise Exception("无法找到触摸设备(需要 root 权限)")
# 注意:完整的 sendevent 实现非常复杂,需要:
# - 设备特定的坐标转换
# - 正确的事件序列(SYN_REPORT 等)
# - 不同 Android 版本的事件格式可能不同
raise Exception("sendevent 需要 root 权限且实现复杂,暂不支持完整实现")
def click(self, device_id, x=500, y=500):
"""点击坐标位置"""
+2
View File
@@ -127,6 +127,8 @@ python 生成WPS流程图.py
+2
View File
@@ -141,6 +141,8 @@ else:
+5 -3
View File
@@ -29,7 +29,7 @@
"yanghao_fallback_enter_live_y": 1200,
"fudai_find_max_attempts": 99999,
"fudai_icon_retry_delay_seconds": 0.4,
"fudai_icon_max_wait_seconds": 6.0,
"fudai_icon_max_wait_seconds": 5.0,
"fudai_click_wait_seconds": 1.7,
"yanghao_recommend_duration_seconds": 206,
"yanghao_recommend_interval_seconds": 570,
@@ -44,7 +44,9 @@
"yanghao_fav_roi_offset_x": 40,
"yanghao_fav_roi_offset_y": 0,
"contains_want": [],
"contains_not_want": [],
"contains_not_want": [
"首饰盒"
],
"fudai_quiet_hours_enabled": true,
"fudai_quiet_start_hour": 2,
"fudai_quiet_end_hour": 9,
@@ -98,7 +100,7 @@
"auto_cleanup": true
},
"fudai_detail_template_threshold": 0.54,
"switch_room_wait_after_stage_diag_seconds": 10.0,
"switch_room_wait_after_stage_diag_seconds": 8.0,
"coupon_template_match_threshold": 0.4,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25,
+469 -167
View File
@@ -1787,8 +1787,8 @@ class fudai_analyse:
current_ts = time.time()
remain_seconds = max(0, future_ts - current_ts)
# 开奖时间 + 5秒缓冲后开始检测开奖结果
check_start_ts = future_ts + 5.0
# 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒)
check_start_ts = future_ts + 1.0
# 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭)
timeout_ts = future_ts + 10.0
@@ -1923,137 +1923,109 @@ class fudai_analyse:
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
try:
# 从状态文件加载预约数据,确保 self.reservations 始终包含最新数据
# 每次开始运行时丢弃旧的预约队列,不加载状态文件
try:
import json
# 如果是第一次运行,先清空预约队列,然后重新加载(刷新预约队列)
# 如果是第一次运行,清空预约队列,不加载状态文件
is_first_run = getattr(self, "_first_run_once_basic", True)
# 记录清空前的队列状态(用于调试)
old_reservations_count = 0
try:
old_reservations_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
except Exception:
pass
if is_first_run:
try:
self._log_kv(
"预约",
"[预约] 第一次运行:清空预约队列并重新加载",
"[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件",
old_reservations_count=old_reservations_count,
)
except Exception:
pass
# 清空预约队列
if hasattr(self, "reservations"):
# 清空预约队列(强制清空,确保每次启动时队列为空)
try:
# 先记录清空前的状态
before_clear = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
self.reservations = []
after_clear = len(self.reservations) if hasattr(self, "reservations") else 0
# 同时清空状态文件,确保外部查看时也是空的
try:
import os
state_path = getattr(self, "_reservations_state_path", None)
if state_path:
# 写入空队列到状态文件
from douyin_reservation import write_reservations_state
write_reservations_state(
state_path=state_path,
reservations=[],
room_pos=0,
current_room_title="",
current_room_title_raw="",
reason="startup_clear",
)
try:
self._log_kv(
"预约",
"[预约] 已清空预约队列并更新状态文件",
before_clear=before_clear,
after_clear=after_clear,
)
except Exception:
pass
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] 清空状态文件时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
except Exception as e:
# 如果清空失败,尝试直接设置
try:
if hasattr(self, "reservations"):
self.reservations = []
self._log_kv(
"预约",
"[预约] 清空预约队列时出错,已尝试直接设置",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 标记已运行过
try:
self._first_run_once_basic = False
except Exception:
pass
if os.path.exists(self._reservations_state_path):
try:
self._log_kv(
"预约",
"[预约] 开始从状态文件加载预约数据",
file_path=self._reservations_state_path,
is_first_run=is_first_run,
)
except Exception:
pass
with open(self._reservations_state_path, "r", encoding="utf-8") as f:
state_data = json.load(f)
reservations_from_file = state_data.get("reservations", [])
try:
self._log_kv(
"预约",
"[预约] 从状态文件读取到预约数据",
file_count=len(reservations_from_file),
)
except Exception:
pass
if reservations_from_file:
# 如果状态文件中有预约数据,更新 self.reservations
if not hasattr(self, "reservations") or self.reservations is None:
self.reservations = []
# 合并预约数据(避免重复)
# 使用 add_reservation_core_logic 函数处理去重,确保与记录预约时使用相同的去重策略
# 去重策略:(future_ts, content) 相同则视为同一条记录,保留价值更高的那条
try:
import douyin_reservation_logic
max_reservations = int(
getattr(self, "high_value_fudai_max_reservations", 3) or 3
)
before_count = len(self.reservations)
for r in reservations_from_file:
if not r.get("future_ts"):
continue
# 使用 add_reservation_core_logic 处理去重和队列管理
douyin_reservation_logic.add_reservation_core_logic( # type: ignore[attr-defined]
reservations=self.reservations,
item=dict(r),
max_reservations=max_reservations,
analyser=self,
write_state_callback=None, # 加载时不需要写回状态文件
)
after_count = len(self.reservations)
added_count = len(reservations_from_file)
# 记录加载统计
try:
# 输出加载后的预约详情
loaded_reservations_detail = []
for idx, r in enumerate(self.reservations[:3]): # 只显示前3个
try:
ft = float(r.get("future_ts") or 0)
from datetime import datetime
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
loaded_reservations_detail.append({
"index": idx,
"future_ts": int(ft) if ft > 0 else 0,
"future_str": ft_str,
"value": float(r.get("prize_value_yuan", 0)),
})
except Exception:
pass
self._log_kv(
"预约",
"[预约] 从状态文件加载预约数据完成",
file_count=added_count,
before_count=before_count,
after_count=after_count,
duplicates_removed=added_count - (after_count - before_count),
loaded_reservations_detail=loaded_reservations_detail,
)
except Exception:
pass
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] 从状态文件合并预约数据时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
else:
# 状态文件不存在
# 如果不是第一次运行,也记录日志(用于调试)
try:
current_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
self._log_kv(
"预约",
"[预约] 状态文件不存在,跳过加载",
file_path=self._reservations_state_path,
"[预约] 非第一次运行,保持当前预约队列",
reservations_count=current_count,
is_first_run=False,
)
except Exception:
pass
# 不再从状态文件加载预约数据,每次启动时都从空队列开始
# 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空
except Exception as e:
try:
self._log_kv(
"预约",
"[预约] 从状态文件加载预约数据失败",
"[预约] 初始化预约队列时出错",
error=str(e),
error_type=type(e).__name__,
file_path=self._reservations_state_path,
file_exists=os.path.exists(self._reservations_state_path) if hasattr(os, 'path') else False,
)
except Exception:
pass
@@ -2127,6 +2099,7 @@ class fudai_analyse:
# 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致)
try:
import json
import os
from datetime import datetime
os.makedirs(
@@ -2377,7 +2350,17 @@ class fudai_analyse:
)
if preempted:
# 已触发预约回退,本轮直接结束,等待下一轮在目标直播间执行详情逻辑
# 已触发预约回退,设置标志:下一轮直接参与,跳过详情识别
try:
self._reservation_back_direct_attend = True
self._log_kv(
"预约",
"[预约] 预约回退成功,设置直接参与标志(跳过详情识别)",
flag_set=True,
next_round_will_check="下一轮将检查此标志并直接参与",
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
@@ -2563,56 +2546,67 @@ class fudai_analyse:
)
return
elif stage == "FANSCLUB_JOIN":
# 粉丝团加入阶段:点击加入粉丝团按钮
# 粉丝团加入阶段:先点击参与按钮,再点击两次预设位置,最后关闭详情页
self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理")
try:
# 点击加入粉丝团按钮(基于截图优化坐标)
# OCR区域:(200, 1940, 880, 2140),尺寸680x200,按钮上部66%是红色区域(文字所在)
# 红色区域高度约132像素,中心Y = 1940 + 132/2 = 2006
# 点击位置:X=540(区域中心),Y=2006(红色区域中心,基于截图分析)
fansclub_x = int(540 * self.resolution_ratio_x // 1080)
fansclub_y = int(2006 * self.resolution_ratio_y // 2400)
# 第一次点击
self.operation.click(self.device_id, fansclub_x, fansclub_y)
# 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
attend_x = int(543 * self.resolution_ratio_x // 1080)
attend_y = int(2070 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, attend_x, attend_y)
self._log_kv(
"粉丝团处理",
"第一次点击加入粉丝团按钮(基于截图优化坐标)",
x=fansclub_x,
y=fansclub_y,
base_x=540,
base_y=2006,
region="(200,1940)-(880,2140)",
red_area_center_y=2006,
"先点击参与按钮",
x=attend_x,
y=attend_y,
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
self.operation.delay(0.5) # 等待参与按钮响应
# 第二步:点击两次预设位置(527, 567)
preset_x = int(527 * self.resolution_ratio_x // 1080)
preset_y = int(567 * self.resolution_ratio_y // 2400)
# 第一次点击预设位置
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"第一次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击(连续点击两次确保成功)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
# 第二次点击预设位置
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"第二次点击加入粉丝团按钮(基于截图优化坐标)",
x=fansclub_x,
y=fansclub_y,
base_x=540,
base_y=2006,
"第二次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(2.0)
# 加入粉丝团两次点击后,点击 (527, 567) 返回直播间
try:
return_x = int(527 * self.resolution_ratio_x // 1080)
return_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, return_x, return_y)
self._log_kv(
"粉丝团处理",
"两次点击后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
self.operation.delay(1.0) # 等待返回完成
except Exception as e:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
self.operation.delay(1.0) # 等待点击完成
# 第三步:关闭详情页(点击详情页旁边位置)
close_x = int(500 * self.resolution_ratio_x // 1080)
close_y = int(470 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, close_x, close_y)
self._log_kv(
"粉丝团处理",
"关闭详情页",
x=close_x,
y=close_y,
base_x=500,
base_y=470,
)
self.operation.delay(1.0) # 等待关闭完成
except Exception as e:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(e))
# 如果启用了自动加入,等待页面加载后再次点击(如果需要)
if getattr(self, "auto_join_fansclub", False):
@@ -2625,14 +2619,25 @@ class fudai_analyse:
)
if stage_after == "FANSCLUB_JOIN":
# 仍在粉丝团加入页,再次点击(连续点击两次)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
# 使用预设位置坐标(527, 567)
preset_x = int(527 * self.resolution_ratio_x // 1080)
preset_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理", "仍在粉丝团加入页,再次第一次点击"
"粉丝团处理", "仍在粉丝团加入页,再次第一次点击",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(0.5)
self.operation.click(self.device_id, fansclub_x, fansclub_y)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理", "仍在粉丝团加入页,再次第二次点击"
"粉丝团处理", "仍在粉丝团加入页,再次第二次点击",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(2.0)
@@ -2684,13 +2689,15 @@ class fudai_analyse:
# 延迟后返回,让主循环继续处理
self.operation.delay(0.5)
except Exception as e:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(e))
# 如果失败,根据配置决定是否切换直播间
fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay")
if fansclub_fail_action == "switch":
self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间")
self.swipe_up_to_next_live()
try:
self.swipe_up_to_next_live()
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
@@ -2699,15 +2706,127 @@ class fudai_analyse:
)
return
elif stage == "FUDai_DETAIL":
# 已经在详情页:直接读详情并决定是否参与
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理福袋详情)",
elapsed_seconds=round(elapsed, 2),
)
# 已经在详情页:检查是否是预约回退后的直接参与
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
try:
self._log_kv(
"预约",
"[预约] 检测到福袋详情页,检查预约回退直接参与标志",
stage=stage,
reservation_direct_attend=reservation_direct_attend,
)
except Exception:
pass
if reservation_direct_attend:
# 预约回退后直接参与:跳过详情识别,直接参与
try:
self._reservation_back_direct_attend = False # 清除标志
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:跳过详情识别,直接参与",
flag_cleared=True,
)
except Exception:
pass
# 直接参与,跳过详情识别
self._handle_reservation_direct_attend()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
elapsed_seconds=round(elapsed, 2),
)
else:
# 正常流程:读详情并决定是否参与
try:
self._log_kv(
"预约",
"[预约] 预约回退直接参与标志为False,执行正常流程",
reservation_direct_attend=reservation_direct_attend,
)
except Exception:
pass
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理福袋详情)",
elapsed_seconds=round(elapsed, 2),
)
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
# 在直播间:检查是否是预约回退后的直接参与
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
try:
self._log_kv(
"预约",
"[预约] 检测到直播间,检查预约回退直接参与标志",
stage=stage,
reservation_direct_attend=reservation_direct_attend,
)
except Exception:
pass
if reservation_direct_attend:
# 预约回退后直接参与:查找福袋并打开详情页,然后直接参与
try:
self._reservation_back_direct_attend = False # 清除标志
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:查找福袋并打开详情页",
flag_cleared=True,
stage=stage,
)
except Exception:
pass
# 查找福袋并打开详情页
import douyin_flow_control
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
try:
self._log_kv(
"预约",
"[预约] 开始查找福袋并打开详情页",
room_pos=room_pos_ref[0],
)
except Exception:
pass
found = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
try:
self._log_kv(
"预约",
"[预约] 查找福袋结果",
found=found,
room_pos=room_pos_ref[0],
)
except Exception:
pass
if found:
# 成功打开详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 成功打开详情页,开始直接参与",
)
except Exception:
pass
self._handle_reservation_direct_attend()
else:
# 查找福袋失败,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = True # 恢复标志
self._log_kv(
"预约",
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
flag_restored=True,
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
elapsed_seconds=round(elapsed, 2),
)
return
# 在直播间:如果刚刚切换了直播间,等待福袋加载
just_switched = getattr(self, "_just_switched_room", False)
if just_switched:
@@ -3010,7 +3129,33 @@ class fudai_analyse:
# ========== 基础动作封装 ==========
def swipe_up_to_next_live(self) -> None:
"""上滑切换直播间(简单版封装)。"""
"""上滑切换直播间(简单版封装)。
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
则不允许上划离开预约直播间,直接返回。
"""
# 检查是否在预约锁定期内
try:
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
now_ts = time.time()
if focus_until > 0 and now_ts < focus_until:
# 在锁定期内,不允许上划离开预约直播间
remain_seconds = int(focus_until - now_ts)
try:
self._log_kv(
"预约",
"[预约] 锁定期内不允许上划离开预约直播间",
focus_until=int(focus_until),
remain_seconds=remain_seconds,
queue_full_waiting=getattr(self, "queue_full_waiting_at_earliest", False),
)
except Exception:
pass
return # 直接返回,不执行上划操作
except Exception:
# 如果检查锁定期时出错,继续执行上划(避免因异常导致无法切换)
pass
start_time = time.time()
douyin_swipe_ops.swipe_up_switch_live(self)
# 记录直播间位置:上滑 +1
@@ -3310,8 +3455,11 @@ class fudai_analyse:
# 计算需要切换的次数和方向
# room_pos 越大表示越靠下,越小表示越靠上
# 如果 target_pos < cur_pos,说明目标在上方,需要向上回退(使用 swipe_down_back_from_live)
# 如果 target_pos > cur_pos,说明目标在下方,需要向下切换(使用 swipe_up_to_next_live)
# 如果 target_pos < cur_pos,说明目标在上方,需要向上回退(使用 swipe_down_back_from_live,room_pos 减少)
# 如果 target_pos > cur_pos,说明目标在下方,需要向下切换(使用 swipe_up_to_next_live,room_pos 增加)
# 注意:pos_diff = target_pos - cur_pos
# - 如果 pos_diff < 0,说明 target_pos < cur_pos,目标在上方,需要向上回退(减少 room_pos)
# - 如果 pos_diff > 0,说明 target_pos > cur_pos,目标在下方,需要向下切换(增加 room_pos)
pos_diff = target_pos - cur_pos
try:
@@ -3331,6 +3479,7 @@ class fudai_analyse:
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
direction="向上回退" if pos_diff < 0 else "向下切换" if pos_diff > 0 else "已在目标位置",
)
except Exception:
pass
@@ -3339,13 +3488,17 @@ class fudai_analyse:
# 已在目标位置,但仍需校验
pass
elif pos_diff < 0:
# 目标在上方,需要向上回退
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
# 使用 swipe_down_back_from_live(),它会执行 room_pos -= 1
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 向上回退",
"[预约] _seek_reservation_room 向上回退(目标在上方)",
back_times=back_times,
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
)
except Exception:
pass
@@ -3357,13 +3510,17 @@ class fudai_analyse:
except Exception:
time.sleep(delay_s)
else:
# 目标在下方,需要向下切换
# 目标在下方(target_pos > cur_pos),需要向下切换(增加 room_pos)
# 使用 swipe_up_to_next_live(),它会执行 room_pos += 1
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
try:
self._log_kv(
"预约",
"[预约] _seek_reservation_room 向下切换",
"[预约] _seek_reservation_room 向下切换(目标在下方)",
forward_times=forward_times,
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
)
except Exception:
pass
@@ -3380,6 +3537,151 @@ class fudai_analyse:
return True
# ========== 福袋相关 ==========
def _handle_reservation_direct_attend(self) -> None:
"""预约回退后直接参与:跳过详情识别,直接参与。"""
start_time = time.time()
try:
self._log_kv(
"预约",
"[预约] 预约回退后直接参与:跳过详情识别,直接参与",
)
except Exception:
pass
# 只检测参与按钮,不重新识别内容
try:
self.operation.get_screenshot(self.device_id)
self.cut_pic(306, 2030, 780, 2110, "", "参与按钮")
# OCR识别参与按钮
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 0) or ""
)
if not attend_button_text or not any(
k in attend_button_text
for k in (
"参与成功",
"还需看播",
"评论",
"参与抽奖",
"开始观看",
"参与",
)
):
attend_button_text = str(
self.operation.analyse_pic_word("参与按钮", 1) or ""
)
self._log_kv(
"参与", "预约回退后直接参与:只验证参与按钮", text=attend_button_text
)
# 如果已参与,设置等待开奖标志并返回
if (
"参与成功" in attend_button_text
or "还需看播" in attend_button_text
or "等待开奖" in attend_button_text
):
self._log_kv(
"参与", "预约回退后直接参与:已参与,无需再次点击", result="已参与"
)
# 从预约队列中获取倒计时信息,设置等待开奖标志
try:
if self.reservations and len(self.reservations) > 0:
first_reservation = self.reservations[0]
future_ts = float(first_reservation.get("future_ts") or 0.0)
if future_ts > 0:
current_time = time.time()
remain_seconds = int(future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间
# 提前13秒,修正倒计时误差
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = future_ts - 13.0
self._log_kv(
"参与",
"预约回退后直接参与:已参与,设置等待开奖标志",
remain_seconds=remain_seconds,
future_ts=int(future_ts),
)
except Exception as e:
self._log_kv(
"参与",
"预约回退后直接参与:设置等待开奖标志时出错",
error=str(e),
)
# 关闭详情页
self.click(500, 470)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_reservation_direct_attend完成(已参与)",
elapsed_seconds=round(elapsed, 2),
)
return
# 如果还需要参与,直接调用参与函数
# 构造一个简化的 detail tuple,只包含必要信息用于参与决策
# detail tuple 格式: (content, time_text, participants, copies, prize_value_yuan, (countdown_start, countdown_end))
try:
# 从预约队列中获取信息
if self.reservations and len(self.reservations) > 0:
first_reservation = self.reservations[0]
future_ts = float(first_reservation.get("future_ts") or 0.0)
prize_value_yuan = float(first_reservation.get("prize_value_yuan") or 0.0)
content = str(first_reservation.get("content") or "")
# 构造简化的 detail tuple
now_ts = time.time()
countdown_start = now_ts
countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0)
detail = (
content, # content
"", # time_text (不需要)
0, # participants (不需要)
0, # copies (不需要)
prize_value_yuan, # prize_value_yuan
(countdown_start, countdown_end), # countdown tuple
)
# 直接调用参与决策
import douyin_fudai_core
join_result = douyin_fudai_core.basic_join_decision(self, detail)
if join_result:
self._log_kv(
"参与",
"预约回退后直接参与:参与成功",
)
else:
self._log_kv(
"参与",
"预约回退后直接参与:参与失败或已跳过",
)
else:
self._log_kv(
"参与",
"预约回退后直接参与:预约队列为空,无法获取详情信息",
)
except Exception as e:
self._log_kv(
"参与",
"预约回退后直接参与:参与时出错",
error=str(e),
)
except Exception as e:
self._log_kv("参与", "预约回退后直接参与:验证参与按钮异常", error=str(e))
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_reservation_direct_attend完成",
elapsed_seconds=round(elapsed, 2),
)
def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
start_time = time.time()
+35 -27
View File
@@ -836,48 +836,56 @@ def attend_choujiang(analyser) -> bool:
analyser._log_kv("参与", "点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测")
return True
elif "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text:
# 需要粉丝团门槛:先点击尝试进入加入/点亮流程
# 需要粉丝团门槛:先点击参与按钮,再点击两次预设位置,最后关闭详情页
analyser.last_attend_fail_reason = "fansclub_required"
# 基于截图优化坐标:OCR区域(200,1940)-(880,2140),红色区域中心Y=2006
# 点击红色文字区域中心(540, 2006)而不是按钮中心(500, 2060)
analyser.click(540, 2006)
# 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
analyser.click(543, 2070)
analyser._log_kv(
"参与",
"粉丝团门槛:第一次点击加入按钮(优化坐标)",
"粉丝团门槛:先点击参与按钮",
result="需要粉丝团",
base_x=540,
base_y=2006,
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
analyser.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击(连续点击两次确保成功)
analyser.click(540, 2006)
analyser._log_kv(
"参与",
"粉丝团门槛:第二次点击加入按钮(优化坐标)",
result="需要粉丝团",
base_x=540,
base_y=2006,
)
analyser.operation.delay(2)
analyser.operation.delay(0.5) # 等待参与按钮响应
# 加入粉丝团两次点击后,点击 (527, 567) 返回直播间
# 第二步:点击两次预设位置(527, 567)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
return_x = int(527 * rx // 1080)
return_y = int(567 * ry // 2400)
analyser.operation.click(analyser.device_id, return_x, return_y)
preset_x = int(527 * rx // 1080)
preset_y = int(567 * ry // 2400)
# 第一次点击预设位置
analyser.operation.click(analyser.device_id, preset_x, preset_y)
analyser._log_kv(
"参与",
"两次点击后,点击返回直播间",
x=return_x,
y=return_y,
"粉丝团门槛:第一次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待返回完成
analyser.operation.delay(0.5) # 短暂等待后立即第二次点击
# 第二次点击预设位置
analyser.operation.click(analyser.device_id, preset_x, preset_y)
analyser._log_kv(
"参与",
"粉丝团门槛:第二次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
analyser.operation.delay(1.0) # 等待点击完成
except Exception as e:
analyser._log_kv("参与", "点击返回直播间失败", error=str(e))
analyser._log_kv("参与", "点击预设位置失败", error=str(e))
# 第三步:关闭详情页
analyser.click(500, 470) # 点击详情页旁边位置关闭详情页
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
if not analyser.auto_join_fansclub:
analyser._log_kv(
+55 -6
View File
@@ -16,6 +16,7 @@ from __future__ import annotations
from typing import Any, Dict, List, Callable, Optional
import time
import re
ReservationItem = Dict[str, Any]
@@ -24,6 +25,28 @@ def _now_ts() -> float:
return time.time()
def _normalize_room_title_for_matching(title: str) -> str:
"""规范化直播间标题用于匹配比较。
去除数字、特殊字符等,只保留核心名称部分。
例如:"王媛媛" 和 "王媛媛2" 会被规范化为相同的字符串。
"""
if not title:
return ""
# 去除空格和换行
s = str(title).replace("\r", " ").replace("\n", " ").strip()
s = re.sub(r"\s+", "", s)
# 去除常见无关词
for w in ("点赞", "赞", "关注", "粉丝", "直播中", "正在直播", "进入直播间", "推荐", "在线", "人在线"):
s = s.replace(w, "")
# 去除数字和特殊字符,只保留中文、英文、数字(但去除末尾的数字)
# 先去除末尾的数字(如 "王媛媛2" -> "王媛媛")
s = re.sub(r"\d+$", "", s)
# 去除所有特殊字符,只保留中文、英文
s = re.sub(r"[^A-Za-z\u4e00-\u9fff]", "", s)
return s
def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None:
"""按 future_ts 升序,其次 prize_value_yuan 降序,其次 created_ts 升序排序。"""
@@ -48,6 +71,7 @@ def add_reservation_core_logic(
去重策略:
- key = (future_ts, content) 相同则视为同一条记录,保留价值更高的那条。
- 如果直播间名字相同(规范化后),且 (future_ts, content) 相同,也视为同一条记录。
返回:
bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。
@@ -55,16 +79,41 @@ def add_reservation_core_logic(
ft = float(item.get("future_ts") or 0.0)
content = str(item.get("content") or "")
prize_value = float(item.get("prize_value_yuan") or 0.0)
room_title = str(item.get("room_title") or "")
room_title_normalized = _normalize_room_title_for_matching(room_title)
same_idx: Optional[int] = None
for idx, r in enumerate(reservations):
try:
if (
float(r.get("future_ts") or 0.0) == ft
and str(r.get("content") or "") == content
):
same_idx = idx
break
r_ft = float(r.get("future_ts") or 0.0)
r_content = str(r.get("content") or "")
r_room_title = str(r.get("room_title") or "")
r_room_title_normalized = _normalize_room_title_for_matching(r_room_title)
# 判断是否为同一个预约:
# 1. (future_ts, content) 相同,且直播间名字相同(规范化后)
# 2. 或者 (future_ts, content) 相同(兼容旧数据,没有直播间名字的情况)
is_same_future_and_content = (r_ft == ft and r_content == content)
is_same_room_title = (
room_title_normalized
and r_room_title_normalized
and room_title_normalized == r_room_title_normalized
)
if is_same_future_and_content:
# 如果 (future_ts, content) 相同
if is_same_room_title:
# 直播间名字也相同(规范化后),确定是同一个预约
same_idx = idx
break
elif not room_title_normalized and not r_room_title_normalized:
# 都没有直播间名字,视为同一个预约(兼容旧数据)
same_idx = idx
break
# 如果只有一个有直播间名字,也视为同一个预约(兼容旧数据)
elif (room_title_normalized and not r_room_title_normalized) or (not room_title_normalized and r_room_title_normalized):
same_idx = idx
break
except Exception:
continue
+2
View File
@@ -141,6 +141,8 @@ def extract_participants_count(text: Optional[str]) -> int:
+2
View File
@@ -98,6 +98,8 @@ paddlepaddle>=2.5.0,<3.0.0
+2
View File
@@ -75,6 +75,8 @@ types-requests>=2.31.0
+2
View File
@@ -114,6 +114,8 @@ ttkbootstrap>=1.10.0
+2
View File
@@ -151,6 +151,8 @@ if __name__ == "__main__":
+13 -23
View File
@@ -1,29 +1,19 @@
{
"updated_ts": 1766719664.092457,
"reason": "process_reservation",
"room_pos": 5,
"current_room_title": "香香生活号",
"current_room_title_raw": "香香生活号",
"updated_ts": 1766724849.1728284,
"reason": "record_reservation",
"room_pos": 0,
"current_room_title": "小宝珠宝2",
"current_room_title_raw": "小宝珠宝2..",
"reservations": [
{
"prize_value_yuan": 799.0,
"content": "25后开奖03便携式迷你小型宿舍手持电熨斗挂烫机熨烫机衣服家。400人巳参与",
"future_ts": 1766719657.646924,
"future_str": "2025-12-26 11:27:37",
"pos_seen": 5,
"room_title": "香香生活号",
"room_title_raw": "香香生活号",
"created_ts": 1766719455.111098
},
{
"prize_value_yuan": 199.0,
"content": "44后开奖11KAZO0凝时奢润冻干眼膜套盒HD2A",
"future_ts": 1766720121.385851,
"future_str": "2025-12-26 11:35:21",
"pos_seen": 4,
"room_title": "王媛媛",
"room_title_raw": "王媛媛(",
"created_ts": 1766719420.0087907
"prize_value_yuan": 9999.0,
"content": "03后开奖05首饰盒1箱(小宝珠宝1木质首饰盒/箱首饰盒-发1个",
"future_ts": 1766725149.202263,
"future_str": "2025-12-26 12:59:09",
"pos_seen": 0,
"room_title": "小宝珠宝2",
"room_title_raw": "小宝珠宝2..",
"created_ts": 1766724849.1696897
}
]
}
+2
View File
@@ -74,6 +74,8 @@ if os.path.exists(log_file):
+2
View File
@@ -87,6 +87,8 @@ if os.path.exists(log_file):
+2
View File
@@ -220,6 +220,8 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb
+2
View File
@@ -57,6 +57,8 @@ __version__ = "1.0.0"
+2
View File
@@ -46,6 +46,8 @@
+2
View File
@@ -46,6 +46,8 @@
+2
View File
@@ -136,6 +136,8 @@ python check_gpu_available.py
+2
View File
@@ -142,6 +142,8 @@
+2
View File
@@ -214,6 +214,8 @@ if __name__ == "__main__":
+2
View File
@@ -145,3 +145,5 @@