fix: Enhance logging and clean up blank lines across multiple files

- Improved logging for reservation handling and participation decisions to provide better traceability.
- Cleaned up excessive blank lines in various markdown and Python files to enhance readability and maintainability.
- Ensured consistent formatting across documentation and code files, contributing to overall project clarity.
This commit is contained in:
Your Name committed 2025-12-27 10:35:15 +08:00
1 parent 5c0fd75674
commit 7849b62d44
38 files changed
+42957 -213

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
@@ -0,0 +1,441 @@
<!-- Generated by SpecStory, Markdown v2.1.0 -->
<!-- cursor Session a16d621e-0772-4be6-93fc-2ab3b73e1e68 (2025-12-27 02:26Z) -->
# 直播间进入流程 (2025-12-27 02:26Z)
_**User (2025-12-27 02:24Z)**_
识别到推荐栏的位置就直接点击718,169进入直播页,再点击两次103,382进入直播间
---
_**Agent (model default, mode Agent)**_
---
查看当前代码,了解推荐栏识别逻辑,以便添加点击操作。
---
<tool-use data-tool-type="read" data-tool-name="read_file">
<details><summary>Tool use: **read_file** • Read file: douyin_fudai_core.py</summary>
</details>
</tool-use>
---
---
搜索与"推荐栏"相关的代码:
---
<tool-use data-tool-type="search" data-tool-name="grep">
<details>
<summary>Tool use: **grep** • Grep for "推荐栏" in "douyin_fudai_core.py" • 0 matches</summary>
Output mode: content
_No matches found_
</details>
</tool-use>
---
---
搜索与"推荐"或"直播"相关的代码:
---
<tool-use data-tool-type="search" data-tool-name="grep">
<details>
<summary>Tool use: **grep** • Grep for "推荐|直播" in "douyin_fudai_core.py" • 46 matches</summary>
Output mode: content
| File | Content | Line |
|------|------|------|
| `douyin_fudai_core.py` | `# 记录进入直播间到识别到福袋的耗时(仅记录一次)` | L688 |
| `douyin_fudai_core.py` | `"进入直播间到识别福袋耗时",` | L700 |
| `douyin_fudai_core.py` | `# 注意:点击参与按钮后会自动关闭详情页,返回直播间` | L1027 |
| `douyin_fudai_core.py` | `# 设置等待开奖标志,避免参与后立即切换直播间` | L1033 |
| `douyin_fudai_core.py` | `# 两次点击后,立即点击 (527, 567) 返回直播间` | L1185 |
| `douyin_fudai_core.py` | `"恢复流程:两次点击后,点击返回直播间",` | L1203 |
| `douyin_fudai_core.py` | `"参与", "恢复流程:点击返回直播间失败", error=str(e)` | L1212 |
| `douyin_fudai_core.py` | `# 两次点击后,立即点击 (527, 567) 返回直播间` | L1341 |
| `douyin_fudai_core.py` | `"恢复流程:再次两次点击后,点击返回直播间",` | L1351 |
| `douyin_fudai_core.py` | `"恢复流程:再次点击返回直播间失败",` | L1363 |
| `douyin_fudai_core.py` | `# 两次点击后,立即点击 (527, 567) 返回直播间` | L1375 |
| `douyin_fudai_core.py` | `"恢复流程:回退逻辑两次点击后,点击返回直播间",` | L1403 |
| `douyin_fudai_core.py` | `"恢复流程:回退逻辑点击返回直播间失败",` | L1415 |
| `douyin_fudai_core.py` | `# 如果之前是在粉丝团加入页,现在显示在直播间,可能是误判` | L1449 |
| `douyin_fudai_core.py` | `"点击加入粉丝团后显示在直播间(可能误判),尝试点击返回键",` | L1453 |
| `douyin_fudai_core.py` | `"点击返回后确实回到直播间,停止继续返回",` | L1486 |
| `douyin_fudai_core.py` | `# 已经回到直播间/列表时:尝试重新打开福袋详情页` | L1518 |
| `douyin_fudai_core.py` | `analyser._log_kv("领奖", "下完单返回到直播间", checks=checks)` | L1860 |
| `douyin_fudai_core.py` | `# 匹配模式1:观看/看 + (可选"直播") + 数字或中文数字 + 分钟` | L1926 |
| `douyin_fudai_core.py` | `patt1 = rf"(?:观看\|看)(?:直播)?(?:.*?)?(?:\d+\|[\{chinese_num_chars\}]+)\s*分钟"` | L1927 |
| `douyin_fudai_core.py` | `# 如果允许切换直播间,切换直播间` | L2565 |
| `douyin_fudai_core.py` | `"basic_join_decision:观看任务后切换直播间",` | L2574 |
| `douyin_fudai_core.py` | `# 如果允许切换直播间,切换直播间` | L2719 |
| `douyin_fudai_core.py` | `"basic_join_decision:观看任务后切换直播间",` | L2728 |
| `douyin_fudai_core.py` | `# 如果允许切换直播间,筛选不通过直接切换直播间` | L2820 |
| `douyin_fudai_core.py` | `"参与", "basic_join_decision:丢弃后切换直播间", reason=reason` | L2828 |
| `douyin_fudai_core.py` | `# 如果允许切换直播间,切换直播间` | L2963 |
| `douyin_fudai_core.py` | `"basic_join_decision:观看任务后切换直播间",` | L2972 |
| `douyin_fudai_core.py` | `# 如果允许切换直播间,切换直播间` | L3061 |
| `douyin_fudai_core.py` | `"basic_join_decision:命中黑名单后切换直播间",` | L3070 |
| `douyin_fudai_core.py` | `# room_pos:当前直播间位置计数` | L3160 |
| `douyin_fudai_core.py` | `# 获取当前直播间标题(如果可用)` | L3166 |
| `douyin_fudai_core.py` | `# 每次记录预约时,都重新读取直播间标题,不使用缓存` | L3170 |
| `douyin_fudai_core.py` | `# 这样可以确保每个预约记录的是当时的真实直播间标题` | L3171 |
| `douyin_fudai_core.py` | `# 更新 analyser 的属性,用于状态文件显示当前直播间` | L3182 |
| `douyin_fudai_core.py` | `"读取直播间标题失败,尝试使用缓存",` | L3192 |
| `douyin_fudai_core.py` | `# 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间)` | L3208 |
| `douyin_fudai_core.py` | `# 获取当前直播间标题(用于状态文件)` | L3269 |
| `douyin_fudai_core.py` | `# 记录高价值直播间(在记录预约之前)` | L3313 |
| `douyin_fudai_core.py` | `# 记录预约后,切换直播间继续找别的福袋` | L3525 |
| `douyin_fudai_core.py` | `# 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间` | L3526 |
| `douyin_fudai_core.py` | `"[预约] 记录预约后:在锁定期内,不切换直播间",` | L3544 |
| `douyin_fudai_core.py` | `"basic_join_decision:记录预约后切换直播间",` | L3557 |
| `douyin_fudai_core.py` | `# 在锁定期内,不切换直播间,但记录日志说明原因` | L3595 |
| `douyin_fudai_core.py` | `"basic_join_decision:记录预约后不切换直播间(锁定期内)",` | L3599 |
| `douyin_fudai_core.py` | `# 获取当前直播间标题` | L3741 |
</details>
</tool-use>
---
---
搜索识别位置或点击坐标相关的代码:
---
<tool-use data-tool-type="search" data-tool-name="codebase_search">
<details>
<summary>Tool use: **codebase_search** • Searched codebase "识别推荐栏位置后点击进入直播" • **8** results</summary>
| File | Lines |
|------|-------|
| `douyin_fudai.py` | L35-5016 |
| `douyin_yanghao.py` | L396-487 |
| `douyin_yanghao.py` | L347-455 |
| `douyin_stage.py` | L2-947 |
| `Underlying_Operations.py` | L199-2457 |
| `gui_app.py` | L25-3372 |
| `douyin_yanghao.py` | L340-396 |
| `douyin_yanghao.py` | L344-455 |
</details>
</tool-use>
---
<tool-use data-tool-type="search" data-tool-name="grep">
<details>
<summary>Tool use: **grep** • Grep for "click|点击|坐标|position" in "douyin_fudai_core.py" • 49 matches</summary>
Output mode: content
| File | Content | Line |
|------|------|------|
| `douyin_fudai_core.py` | `coords: OCR区域坐标 (x1, y1, x2, y2) - 基准坐标(1080x2400)` | L23 |
| `douyin_fudai_core.py` | `# 缩放坐标到实际分辨率` | L38 |
| `douyin_fudai_core.py` | `"""点击参与抽奖。"""` | L864 |
| `douyin_fudai_core.py` | `click_times = 0` | L866 |
| `douyin_fudai_core.py` | `while click_times < 2:` | L867 |
| `douyin_fudai_core.py` | `# 设置标志:已经关闭了详情,避免后续再次点击返回键` | L953 |
| `douyin_fudai_core.py` | `analyser.click(500, 470) # 点击刚才打开福袋的旁边位置` | L959 |
| `douyin_fudai_core.py` | `analyser.operation.click_back(analyser.device_id)` | L974 |
| `douyin_fudai_core.py` | `analyser.click(500, 470)` | L978 |
| `douyin_fudai_core.py` | `analyser.click(500, 470)` | L985 |
| `douyin_fudai_core.py` | `analyser.click(500, 470)` | L990 |
| `douyin_fudai_core.py` | `analyser.click(500, 470)` | L995 |
| `douyin_fudai_core.py` | `# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80` | L999 |
| `douyin_fudai_core.py` | `analyser.click(543, 2070)` | L1001 |
| `douyin_fudai_core.py` | `"点击参与抽奖(基于截图优化坐标)",` | L1004 |
| `douyin_fudai_core.py` | `action="点击参与",` | L1005 |
| `douyin_fudai_core.py` | `# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80` | L1013 |
| `douyin_fudai_core.py` | `analyser.click(543, 2070)` | L1015 |
| `douyin_fudai_core.py` | `"点击参与抽奖(基于截图优化坐标)",` | L1018 |
| `douyin_fudai_core.py` | `action="点击参与",` | L1019 |
| `douyin_fudai_core.py` | `# 设置标志:点击参与抽奖后直接查找福袋,跳过阶段检测` | L1026 |
| `douyin_fudai_core.py` | `# 注意:点击参与按钮后会自动关闭详情页,返回直播间` | L1027 |
| `douyin_fudai_core.py` | `"点击参与抽奖后,设置等待开奖标志",` | L1047 |
| `douyin_fudai_core.py` | `"点击参与抽奖后,设置等待开奖标志时出错",` | L1058 |
| `douyin_fudai_core.py` | `"点击参与按钮完成,详情页将自动关闭,下次循环直接查找福袋,跳过阶段检测",` | L1066 |
| `douyin_fudai_core.py` | `# 需要粉丝团门槛:先点击参与按钮,再点击一次预设位置,最后关闭详情页` | L1070 |
| `douyin_fudai_core.py` | `# 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))` | L1072 |
| `douyin_fudai_core.py` | `analyser.click(543, 2070)` | L1073 |
| `douyin_fudai_core.py` | `"粉丝团门槛:先点击参与按钮",` | L1076 |
| `douyin_fudai_core.py` | `# 第二步:点击一次预设位置(527, 567)` | L1084 |
| `douyin_fudai_core.py` | `# 点击预设位置` | L1091 |
| `douyin_fudai_core.py` | `analyser.operation.click(analyser.device_id, preset_x, preset_y)` | L1092 |
| `douyin_fudai_core.py` | `"粉丝团门槛:点击预设位置",` | L1095 |
| `douyin_fudai_core.py` | `analyser.operation.delay(1.2) # 等待点击完成(适当延长)` | L1101 |
| `douyin_fudai_core.py` | `analyser._log_kv("参与", "点击预设位置失败", error=str(e))` | L1103 |
| `douyin_fudai_core.py` | `analyser.click(500, 470) # 点击详情页旁边位置关闭详情页` | L1106 |
| `douyin_fudai_core.py` | `# 点击粉丝团按钮后,可能进入“加入粉丝团”独立页面:需要在该页再次点击“加入粉丝团”才能成功。` | L1115 |
| `douyin_fudai_core.py` | `# 在加入页点击底部"加入粉丝团"按钮(与详情页按钮同位置)` | L1135 |
| `douyin_fudai_core.py` | `"粉丝团加入页:点击加入粉丝团",` | L1138 |
| `douyin_fudai_core.py` | `# 点击加入粉丝团按钮` | L1144 |
| `douyin_fudai_core.py` | `# 点击红色文字区域的中心(基于截图分析优化)` | L1155 |
| `douyin_fudai_core.py` | `click_x = int(540 * rx // 1080) # 区域中心X` | L1156 |
| `douyin_fudai_core.py` | `click_y = int(` | L1157 |
| `douyin_fudai_core.py` | `# 第一次点击` | L1160 |
| `douyin_fudai_core.py` | `analyser.operation.click(` | L1161 |
| `douyin_fudai_core.py` | `analyser.device_id, click_x, click_y` | L1162 |
| `douyin_fudai_core.py` | `"恢复流程:第一次点击加入粉丝团按钮(基于截图优化坐标)",` | L1166 |
| `douyin_fudai_core.py` | `x=click_x,` | L1167 |
| `douyin_fudai_core.py` | `y=click_y,` | L1168 |
</details>
</tool-use>
---
---
查看处理推荐页面的代码:
---
<tool-use data-tool-type="read" data-tool-name="read_file">
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
</details>
</tool-use>
---
---
修改代码:识别到推荐栏后,直接点击 (718, 169) 进入直播页,然后点击两次 (103, 382) 进入直播间。
---
<tool-use data-tool-type="write" data-tool-name="search_replace">
<details><summary>Tool use: **search_replace** • Edit file: douyin_fudai.py</summary>
**Chunk 1**
Lines added: 7, lines removed: 7
```diff
@@ -3141,14 +3141,14 @@
)
try:
- # 点击关注标签 (709, 169) - 基于1080x2400分辨率
- follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
- follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
- self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
- self._log_kv("流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
+ # 直接点击 (718, 169) 进入直播页 - 基于1080x2400分辨率
+ live_tab_x = int(718 * self.resolution_ratio_x // 1080)
+ live_tab_y = int(169 * self.resolution_ratio_y // 2400)
+ self.operation.click(self.device_id, live_tab_x, live_tab_y)
+ self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y)
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
- # 点击进入直播间的位置 (103, 385),连点两次
+ # 点击进入直播间的位置 (103, 382),连点两次
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
- enter_live_y = int(385 * self.resolution_ratio_y // 2400)
+ enter_live_y = int(382 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, enter_live_x, enter_live_y)
self.operation.delay(self.ENTER_LIVE_CLICK_DELAY)
```
</details>
</tool-use>
---
---
检查是否有语法错误:
---
<tool-use data-tool-type="generic" data-tool-name="read_lints">
<details>
<summary>Tool use: **read_lints** • Read lints for 1 file</summary>
Lint paths:
- `douyin_fudai.py`
Lint results
Lint errors for `douyin_fudai.py`
| Message | Range | Severity |
|-------|-------|----------|
| "douyin_lottery" 导入项未使用 | 27:8-27:22 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_robot" 导入项未使用 | 29:8-29:20 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_text_utils" 导入项未使用 | 31:8-31:25 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_utils" 导入项未使用 | 32:8-32:20 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_yanghao" 导入项未使用 | 33:8-33:22 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_reservation_logic" 导入项未使用 | 35:8-35:32 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_reservation_verify" 导入项未使用 | 36:8-36:33 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_high_value_room" 导入项未使用 | 37:8-37:30 | DIAGNOSTIC_SEVERITY_HINT |
| "np" 导入项未使用 | 931:29-931:31 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "max_loc" 未使用 | 1114:46-1114:53 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "e" 未使用 | 1629:29-1629:30 | DIAGNOSTIC_SEVERITY_HINT |
| "json" 导入项未使用 | 2002:24-2002:28 | DIAGNOSTIC_SEVERITY_HINT |
| "os" 导入项未使用 | 2031:36-2031:38 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "reason" 未使用 | 2334:36-2334:42 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "reason" 未使用 | 2336:36-2336:42 | DIAGNOSTIC_SEVERITY_HINT |
| "douyin_flow_control" 未绑定 | 2377:37-2377:56 | DIAGNOSTIC_SEVERITY_ERROR |
| 无法访问 "Unbound" 类的 "find_and_open_fudai_detail" 属性 | 2377:57-2377:83 | DIAGNOSTIC_SEVERITY_ERROR |
| 变量 "seen_after" 未使用 | 2849:38-2849:48 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "start_time" 未使用 | 3617:9-3617:19 | DIAGNOSTIC_SEVERITY_HINT |
| 变量 "time_window_end_ts" 未使用 | 4940:29-4940:47 | DIAGNOSTIC_SEVERITY_HINT |
</details>
</tool-use>
---
---
这些错误是之前就存在的,与本次修改无关。验证修改后的代码:
---
<tool-use data-tool-type="read" data-tool-name="read_file">
<details><summary>Tool use: **read_file** • Read file: douyin_fudai.py</summary>
</details>
</tool-use>
---
---
更新注释,使其与代码逻辑一致:
---
<tool-use data-tool-type="write" data-tool-name="search_replace">
<details><summary>Tool use: **search_replace** • Edit file: douyin_fudai.py</summary>
**Chunk 1**
Lines added: 1, lines removed: 1
```diff
@@ -3133,5 +3133,5 @@
# 处理推荐/关注/直播列表页:回到直播间或切换
if stage == "RECOMMEND_PAGE":
- # 识别到推荐页面:点击关注标签,然后点击进入直播间
+ # 识别到推荐页面:直接点击进入直播页,然后点击进入直播间
self._log_kv(
"流程",
```
</details>
</tool-use>
---
---
更新日志信息,使其更准确:
---
<tool-use data-tool-type="write" data-tool-name="search_replace">
<details><summary>Tool use: **search_replace** • Edit file: douyin_fudai.py</summary>
**Chunk 1**
Lines added: 1, lines removed: 1
```diff
@@ -3136,5 +3136,5 @@
self._log_kv(
"流程",
- "检测到推荐页面,点击关注标签并进入直播间",
+ "检测到推荐页面,点击进入直播页并进入直播间",
stage=stage,
seen=seen,
```
</details>
</tool-use>
---
---
已修改代码。识别到推荐栏位置后:
1. **直接点击 (718, 169)** 进入直播页(替换了之前点击关注标签的逻辑)
2. **点击两次 (103, 382)** 进入直播间(坐标从 385 调整为 382)
代码会根据设备分辨率自动缩放坐标。修改位置在 `douyin_fudai.py` 文件的第 3143-3163 行。
修改已完成,可以测试运行。
---
+6
View File
@@ -175,6 +175,12 @@ python cleanup_unused_files.py
+6
View File
@@ -186,6 +186,12 @@ except Exception as e:
+6
View File
@@ -389,6 +389,12 @@ self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标
+6
View File
@@ -273,6 +273,12 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
+6
View File
@@ -244,6 +244,12 @@ python check_dependencies.py
+6
View File
@@ -223,6 +223,12 @@ douyin_guaji
+6
View File
@@ -164,6 +164,12 @@
+6
View File
@@ -376,6 +376,12 @@ douyin_fudai_finder.py
+6
View File
@@ -175,6 +175,12 @@ self.ocr = easyocr.Reader(
+6
View File
@@ -134,6 +134,12 @@ python 生成WPS流程图.py
+6
View File
@@ -148,6 +148,12 @@ else:
+2 -2
View File
@@ -14,7 +14,7 @@
"high_value_fudai_threshold_yuan": 500.0,
"high_value_fudai_join_ahead_seconds": 120,
"high_value_fudai_max_swipe_back": 50,
"high_value_fudai_max_reservations": 3,
"high_value_fudai_max_reservations": 9999,
"high_value_fudai_after_action": "continue",
"high_value_room_revisit_enabled": true,
"high_value_room_revisit_only_current_run": true,
@@ -95,7 +95,7 @@
}
},
"debug_captures": {
"enabled": false,
"enabled": true,
"keep_days": 3,
"max_files": 2000,
"auto_cleanup": true
+379 -54
View File
@@ -1782,10 +1782,10 @@ class fudai_analyse:
pass
else:
# 没有预约抢占,继续等待开奖
# 直接用预计开奖时间减去当前时间计算剩余秒数
# 直接用预计开奖时间减去当前时间计算剩余秒数,加上6秒延迟修正
future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0
current_ts = time.time()
remain_seconds = max(0, future_ts - current_ts)
remain_seconds = max(0, future_ts - current_ts + 6.0) # 加上6秒延迟,修正倒计时误差
# 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒)
check_start_ts = future_ts + 1.0
@@ -1795,55 +1795,129 @@ class fudai_analyse:
if current_ts >= timeout_ts:
# 超过超时时间,清除等待标志,避免卡死
self._waiting_for_lottery_result = False
timeout_seconds = int(current_ts - future_ts)
self._log_kv(
"参与",
"等待开奖超时(超过开奖时间10秒),清除等待标志,继续执行其他操作",
超时秒数=int(current_ts - future_ts),
f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作",
超时秒数=timeout_seconds,
)
# 继续执行后续逻辑,不返回
elif current_ts >= check_start_ts:
# 已经超过开奖时间+缓冲时间,开始检测开奖结果
# 直接OCR识别开奖结果按钮区域,不需要阶段诊断
self.operation.get_screenshot(self.device_id)
result = self._check_lottery_result_by_ocr()
if result:
# 检测到开奖结果,清除等待标志,处理结果
self._waiting_for_lottery_result = False
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
# 处理开奖结果(根据OCR结果执行不同操作)
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
return
else:
# 还未开奖,继续等待(每2秒检测一次)
self._log_kv(
"参与",
"等待开奖中,OCR未识别到结果",
剩余秒数=int(remain_seconds),
)
self.operation.delay(2.0)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return # 返回,不执行其他操作
# 已经超过开奖时间+缓冲时间,直接点击"我知道了"按钮(多次点击,确保关闭弹窗)
# 计算已过开奖时间的秒数
passed_seconds = int(current_ts - future_ts)
self._log_kv(
"参与",
f"等待开奖结果中,OCR未识别到结果(已过开奖时间{passed_seconds}秒),开始直接点击",
已过开奖时间秒数=passed_seconds,
)
# 按钮位置基于1080x2400:532, 1322
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
btn_x = int(532 * rx // 1080)
btn_y = int(1322 * ry // 2400)
# 直接点击"我知道了"按钮,最多点击10次,每次间隔1秒
clicked_count = 0
max_clicks = 10
for i in range(max_clicks):
try:
self.operation.get_screenshot(self.device_id)
# 检查是否还在开奖结果弹窗(通过阶段诊断)
import douyin_stage
stage_result = douyin_stage.diagnose_stage_from_current_screen(self)
if stage_result is None:
current_stage = "UNKNOWN"
else:
current_stage, _ = stage_result
# 如果不在开奖结果弹窗,说明已经关闭,停止点击
if current_stage != "FUDai_RESULT":
self._log_kv(
"参与",
"等待开奖期间:直接点击后弹窗已关闭",
clicked_count=i + 1,
stage=current_stage,
)
break
# 点击"我知道了"按钮
self.operation.click(self.device_id, btn_x, btn_y)
clicked_count += 1
self._log_kv(
"参与",
"等待开奖期间:直接点击我知道了按钮",
click_count=clicked_count,
x=btn_x,
y=btn_y,
)
self.operation.delay(1.0)
except Exception as e:
self._log_kv(
"参与",
"等待开奖期间:直接点击时出错",
error=str(e),
click_count=clicked_count,
)
break
# 如果直接点击失败,回退到OCR识别方式
if clicked_count == 0:
self._log_kv("参与", "等待开奖期间:直接点击失败,回退到OCR识别")
self.operation.get_screenshot(self.device_id)
result = self._check_lottery_result_by_ocr()
if result:
self._waiting_for_lottery_result = False
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
return
# 清除等待标志,切换直播间
self._waiting_for_lottery_result = False
self._log_kv(
"参与",
"等待开奖期间:已直接点击我知道了按钮",
clicked_count=clicked_count,
)
# 切换下一个直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋")
self.swipe_up_to_next_live()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
return
else:
# 还未到开奖时间,短暂等待后继续检测
wait_s = min(2.0, remain_seconds)
self._log_kv("参与", "等待开奖中", 剩余秒数=int(remain_seconds))
remain_seconds_int = int(remain_seconds)
# 在日志消息中显示倒计时
self._log_kv(
"参与",
f"等待开奖中,剩余{remain_seconds_int}秒",
剩余秒数=remain_seconds_int,
)
self.operation.delay(wait_s)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(等待开奖中)",
f"run_once_basic完成(等待开奖中,剩余{remain_seconds_int}秒)",
elapsed_seconds=round(elapsed, 2),
)
return # 返回,不执行其他操作
@@ -2224,21 +2298,134 @@ class fudai_analyse:
)
return
# 如果已经在队列满等待状态,且设置了直接参与标志,跳过后续的预约回退检查
# 让流程继续执行,在阶段诊断后检查直接参与标志
if self.queue_full_waiting_at_earliest:
# 如果正在等待开奖,跳过预约回退检查
if getattr(self, "_waiting_for_lottery_result", False):
try:
self._log_kv(
"预约",
"[预约] 正在等待开奖,跳过预约回退检查",
waiting_for_lottery=True,
)
except Exception:
pass
# 跳过预约回退检查,让流程继续执行到阶段诊断后检查开奖结果
# 不在这里 return,让流程继续
# 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查
elif self.queue_full_waiting_at_earliest:
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
if reservation_direct_attend:
try:
self._log_kv(
"预约",
"[预约] 队列满等待状态,已设置直接参与标志,跳过预约回退检查",
"[预约] 队列满等待状态,已设置直接参与标志,立即执行参与(不再循环检查)",
reservation_direct_attend=reservation_direct_attend,
)
except Exception:
pass
# 跳过预约回退检查,让流程继续执行到阶段诊断后检查直接参与标志
# 不在这里 return,让流程继续
# 立即执行参与,不再循环检查预约回退
# 先进行阶段诊断,然后根据阶段执行参与
try:
self.operation.get_screenshot(self.device_id)
except Exception:
pass
import douyin_stage
result = douyin_stage.diagnose_stage_from_current_screen(self)
if result is None:
stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
else:
stage, reason = result
if stage == "FUDai_DETAIL":
# 在福袋详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 检测到福袋详情页,立即执行直接参与",
stage=stage,
)
except Exception:
pass
self._reservation_back_direct_attend = False # 清除标志
self._force_attend_after_reservation_back = True # 设置强制参与标志
self._handle_reservation_direct_attend()
elif stage == "IN_LIVE_ROOM":
# 在直播间,查找福袋并打开详情页
try:
self._log_kv(
"预约",
"[预约] 检测到直播间,查找福袋并打开详情页后执行直接参与",
stage=stage,
)
except Exception:
pass
# 查找福袋并打开详情页
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
original_max_wait = getattr(self, "fudai_icon_max_wait_seconds", None)
try:
wait_seconds_for_find = float(
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0
)
self.fudai_icon_max_wait_seconds = wait_seconds_for_find
self._log_kv(
"预约",
"[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)",
room_pos=room_pos_ref[0],
max_wait_seconds=wait_seconds_for_find,
)
except Exception:
pass
found = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
# 恢复原始配置
try:
if original_max_wait is not None:
self.fudai_icon_max_wait_seconds = original_max_wait
elif hasattr(self, "fudai_icon_max_wait_seconds"):
delattr(self, "fudai_icon_max_wait_seconds")
except Exception:
pass
if found:
# 成功打开详情页,直接参与
try:
self._log_kv(
"预约",
"[预约] 成功打开详情页,立即执行直接参与",
)
except Exception:
pass
self._reservation_back_direct_attend = False # 清除标志
self._force_attend_after_reservation_back = True # 设置强制参与标志
self._handle_reservation_direct_attend()
else:
# 查找福袋失败,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = True # 恢复标志
self._log_kv(
"预约",
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
flag_restored=True,
)
except Exception:
pass
else:
# 其他阶段,保留标志,下一轮继续尝试
try:
self._reservation_back_direct_attend = True # 恢复标志
self._log_kv(
"预约",
"[预约] 检测到其他阶段,保留直接参与标志,下一轮继续尝试",
stage=stage,
flag_restored=True,
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(预约回退直接参与)",
elapsed_seconds=round(elapsed, 2),
)
return
# 检查是否所有预约已完成,需要重置到第一个直播间
if self.queue_full_waiting_at_earliest and not self.reservations:
@@ -2945,24 +3132,24 @@ class fudai_analyse:
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
# 处理推荐/关注/直播列表页:回到直播间或切换
if stage == "RECOMMEND_PAGE":
# 识别到推荐页面:点击关注标签,然后点击进入直播间
# 识别到推荐页面:直接点击进入直播页,然后点击进入直播间
self._log_kv(
"流程",
"检测到推荐页面,点击关注标签并进入直播间",
"检测到推荐页面,点击进入直播页并进入直播间",
stage=stage,
seen=seen,
)
try:
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
self._log_kv("流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
# 直接点击 (718, 169) 进入直播页 - 基于1080x2400分辨率
live_tab_x = int(718 * self.resolution_ratio_x // 1080)
live_tab_y = int(169 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, live_tab_x, live_tab_y)
self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y)
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
# 点击进入直播间的位置 (103, 385),连点两次
# 点击进入直播间的位置 (103, 382),连点两次
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
enter_live_y = int(385 * self.resolution_ratio_y // 2400)
enter_live_y = int(382 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, enter_live_x, enter_live_y)
self.operation.delay(self.ENTER_LIVE_CLICK_DELAY)
self.operation.click(self.device_id, enter_live_x, enter_live_y)
@@ -3711,10 +3898,148 @@ class fudai_analyse:
self._last_fudai_detail_tuple = detail
self._fudai_detail_first_read = True
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
self._current_fudai_future_ts = future_ts
# 直接调用参与决策,跳过详情识别
import douyin_fudai_core
join_result = douyin_fudai_core.basic_join_decision(self, detail)
# 如果参与成功,设置开奖等待状态并从预约队列中移除
if join_result and future_ts > 0:
try:
# 设置开奖等待状态
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = future_ts - 13.0
self._log_kv(
"预约",
"[预约] 预约回退后参与成功,设置开奖等待状态",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(self._lottery_result_expected_ts),
)
# 设置锁定期,防止过早切换直播间
poll_before = float(getattr(self, "high_value_fudai_poll_before_seconds", 10.0) or 10.0)
self.reservation_focus_until_ts = future_ts + max(0.0, poll_before)
# 从预约队列中移除已参与的预约
if self.reservations and len(self.reservations) > 0:
remaining_reservations = []
for res in self.reservations:
try:
res_future_ts = float(res.get("future_ts") or 0.0)
if res_future_ts > 0 and abs(res_future_ts - future_ts) <= 5.0:
# 匹配的预约,移除
self._log_kv(
"预约",
"[预约] 预约回退后参与成功,从预约队列中移除该预约",
future_ts=int(res_future_ts),
value_yuan=res.get("prize_value_yuan", 0),
content=(res.get("content", "")[:50] if res.get("content") else ""),
)
else:
# 保留不匹配的预约
remaining_reservations.append(res)
except Exception:
# 如果解析预约项时出错,保留该项(容错处理)
remaining_reservations.append(res)
if len(remaining_reservations) < len(self.reservations):
self.reservations = remaining_reservations
# 写入预约状态
try:
import douyin_reservation_logic
if hasattr(douyin_reservation_logic, "_write_reservation_state"):
# 如果有写入函数,调用它
pass
else:
# 否则使用内联写入逻辑
import os
import json
from datetime import datetime
state_path = getattr(self, "_reservations_state_path", None)
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 remaining_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),
"task_count": int(r.get("task_count") or 2),
"time_text": str(r.get("time_text") or ""),
"participants": int(r.get("participants") or 0),
"copies": int(r.get("copies") or 0),
})
current_title = str(getattr(self, "current_room_title", "") or "")
current_title_raw = str(getattr(self, "current_room_title_raw", "") or "")
data = {
"updated_ts": time.time(),
"reason": "remove_reservation_after_attend",
"room_pos": 0,
"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)
self._log_kv(
"预约",
"[预约] 已写入预约队列状态文件(移除预约后)",
path=state_path,
queue_len=len(remaining_reservations),
)
except Exception as e:
self._log_kv(
"预约",
"[预约] 写入预约状态失败",
error=str(e),
error_type=type(e).__name__,
)
# 清除预约回退直接参与标志
self._reservation_back_direct_attend = False
self.reservation_after_action_pending = False
except Exception as e:
self._log_kv(
"预约",
"[预约] 预约回退后参与成功,设置状态时出错",
error=str(e),
error_type=type(e).__name__,
)
elapsed = time.time() - start_time
try:
self._log_kv(
+538 -34
View File
@@ -896,6 +896,7 @@ def attend_choujiang(analyser) -> bool:
pass
# 记录已参与的福袋(通过 future_ts 标识),避免重复参与
future_ts = 0.0
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
@@ -916,6 +917,39 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
# 设置开奖等待状态(如果 future_ts 可用)
if future_ts > 0:
try:
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
# 设置等待开奖标志和预期开奖时间(提前13秒,修正倒计时误差)
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts - 13.0
analyser._log_kv(
"参与",
"参与成功,设置等待开奖标志",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
)
else:
analyser._log_kv(
"参与",
"参与成功,但倒计时已过期,不设置等待标志",
future_ts=int(future_ts),
remain_seconds=int(remain_seconds),
)
except Exception as e:
analyser._log_kv(
"参与",
"设置开奖等待状态时出错",
error=str(e),
error_type=type(e).__name__,
)
# 设置标志:已经关闭了详情,避免后续再次点击返回键
try:
analyser._detail_closed_by_attend = True
@@ -2353,32 +2387,44 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
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
elapsed = time.time() - start_time
# 检查是否是预约回退后强制参与(跳过验证)
force_attend = getattr(analyser, "_force_attend_after_reservation_back", False)
if force_attend:
try:
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
"basic_join_decision:检测到强制参与标志(预约回退),跳过验证,直接参与",
)
return False
except Exception:
pass
except Exception:
pass
# 跳过验证,直接进入参与逻辑
else:
# 额外验证:使用验证函数检查数据合理性
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
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
if not content and prize_value_yuan == 0.0:
@@ -2482,7 +2528,98 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
# 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
# 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected)
if skip and reason.startswith("countdown_gt_") and is_high_value:
# 再次检查是否是观看任务(双重保险)
is_watch_task = False
try:
is_watch_task = is_watch_task_fudai(content)
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"预约",
"[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
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="watch_task",
)
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
# 直接返回 False,不参与抽奖
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(观看任务,已丢弃)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 计算剩余秒数
remain_seconds = None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
@@ -2533,13 +2670,110 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
if not force_attend
else "reservation_back_force_attend"
)
# 清除强制参与标志
# 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约)
# 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋
if force_attend:
try:
analyser._force_attend_after_reservation_back = False
# 设置 is_high_value = False,跳过后续的高价值处理逻辑
is_high_value = False
analyser._log_kv(
"参与",
"basic_join_decision:强制参与模式,跳过后续高价值处理逻辑,直接参与",
force_attend=force_attend,
)
except Exception:
pass
else:
# 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务
is_watch_task_check = False
try:
is_watch_task_check = is_watch_task_fudai(content)
if is_watch_task_check:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"预约",
"[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
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="watch_task",
)
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
# 直接返回 False,不参与抽奖
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(观看任务,已丢弃)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
# 如果检查观看任务时出错,记录日志但继续后续处理(容错处理)
pass
# 剩余秒数大于"预约参与阈值",记录预约
try:
analyser._log_kv(
@@ -2645,21 +2879,37 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
except Exception:
join_ahead_seconds = 120
# 如果剩余秒数在"预约参与阈值"内(<= 阈值),立即参与而不是记录预约
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
# 检查是否是回退后强制参与(预约回退后必须立即参与,不记录预约)
force_attend_check = getattr(
analyser, "_force_attend_after_reservation_back", False
)
# 如果剩余秒数在"预约参与阈值"内(<= 阈值),或者如果是回退后强制参与,立即参与而不是记录预约
if force_attend_check or (
remain_seconds is not None and remain_seconds <= join_ahead_seconds
):
try:
analyser._log_kv(
"参与",
"basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与",
"basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内或回退后强制参与,立即参与",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=int(remain_seconds),
remain_seconds=(
int(remain_seconds) if remain_seconds is not None else None
),
join_ahead_threshold=join_ahead_seconds,
force_attend=force_attend_check,
)
except Exception:
pass
# 不记录预约,继续执行后续的立即参与逻辑
is_high_value = False
# 如果是强制参与,清除标志(避免影响后续逻辑)
if force_attend_check:
try:
analyser._force_attend_after_reservation_back = False
except Exception:
pass
else:
# 剩余秒数大于"预约参与阈值",记录预约
try:
@@ -2678,6 +2928,104 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
if is_high_value:
# 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与
# 在记录预约之前,先检查是否是观看任务
is_watch_task = False
try:
is_watch_task = is_watch_task_fudai(content)
if is_watch_task:
# 是观看任务,不记录预约,直接关闭详情页并返回
try:
analyser._log_kv(
"预约",
"[预约] 检测到'观看X分钟'类任务,不记录预约,直接丢弃",
content=content[:80] if content else "",
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
)
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="watch_task",
)
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
# 直接返回 False,不参与抽奖
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
"basic_join_decision完成(观看任务,已丢弃)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
# 如果检查观看任务时出错,记录日志但继续后续检查(容错处理)
try:
analyser._log_kv(
"预约",
"[预约] 检查观看任务时出错,继续后续检查",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 在记录预约之前,先检查福袋内容是否在黑名单中
try:
# 检查内容是否命中黑名单
@@ -2858,8 +3206,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
pass
# 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间)
rl = douyin_reservation_logic
# 使用全局导入的模块(已在文件顶部导入)
# 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致)
def _write_reservation_state() -> None:
try:
@@ -2985,7 +3332,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
queue_full_flag = [False]
def _add_reservation_with_flag(q, item):
queue_full_flag[0] = rl.add_reservation_core_logic( # type: ignore[attr-defined]
queue_full_flag[0] = douyin_reservation_logic.add_reservation_core_logic( # type: ignore[attr-defined]
q,
item,
max_reservations=int(
@@ -3101,7 +3448,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
except Exception:
task_count = 2
rl.record_high_value_reservation( # type: ignore[attr-defined]
douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined]
analyser=analyser,
fudai_content_text=content,
prize_value_yuan=prize_value_yuan,
@@ -3123,7 +3470,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
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]
sort_reservations_callback=lambda: douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined]
reservations
),
write_state_callback=_write_reservation_state,
@@ -3277,7 +3624,164 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖")
except Exception:
pass
# 获取当前福袋的 future_ts(用于参与成功后从预约队列中移除)
current_future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
result = attend_choujiang(analyser)
# 如果参与成功,清除强制参与标志(避免影响后续福袋)
if result:
try:
if getattr(analyser, "_force_attend_after_reservation_back", False):
analyser._force_attend_after_reservation_back = False
analyser._log_kv(
"参与",
"basic_join_decision:参与成功,清除强制参与标志",
)
except Exception:
pass
# 如果参与成功,从预约队列中移除该预约(如果存在)
if result and current_future_ts > 0:
try:
reservations = getattr(analyser, "reservations", None)
if (
reservations
and isinstance(reservations, list)
and len(reservations) > 0
):
# 查找并移除匹配的预约(通过 future_ts 匹配,允许5秒误差)
removed_count = 0
remaining_reservations = []
for res in reservations:
try:
res_future_ts = float(res.get("future_ts") or 0.0)
if (
res_future_ts > 0
and abs(res_future_ts - current_future_ts) <= 5.0
):
# 匹配的预约,移除
removed_count += 1
analyser._log_kv(
"预约",
"[预约] 参与成功,从预约队列中移除该预约",
future_ts=int(res_future_ts),
value_yuan=res.get("prize_value_yuan", 0),
content=(
res.get("content", "")[:50]
if res.get("content")
else ""
),
)
else:
# 保留不匹配的预约
remaining_reservations.append(res)
except Exception:
# 如果解析预约项时出错,保留该项(容错处理)
remaining_reservations.append(res)
if removed_count > 0:
analyser.reservations = remaining_reservations
# 写入预约状态(供 GUI/Web 端查看)
# 使用内联的写入逻辑(与 _write_reservation_state 类似,但需要适配当前作用域)
try:
import os
import json
from datetime import datetime
state_path = getattr(analyser, "_reservations_state_path", None)
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 remaining_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),
"task_count": int(r.get("task_count") or 2),
"time_text": str(r.get("time_text") or ""),
"participants": int(r.get("participants") or 0),
"copies": int(r.get("copies") or 0),
}
)
# 获取当前直播间标题
current_title = str(
getattr(analyser, "current_room_title", "") or ""
)
current_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
)
# 写入完整的状态数据
data = {
"updated_ts": time.time(),
"reason": "remove_reservation_after_attend",
"room_pos": 0,
"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(remaining_reservations),
)
except Exception:
pass
except Exception as e:
analyser._log_kv(
"预约",
"[预约] 写入预约状态失败",
error=str(e),
error_type=type(e).__name__,
)
except Exception as e:
analyser._log_kv(
"预约",
"[预约] 从预约队列中移除预约时出错",
error=str(e),
error_type=type(e).__name__,
)
elapsed = time.time() - start_time
analyser._log_kv(
"参与",
+86 -26
View File
@@ -724,9 +724,10 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
remain_seconds = int(countdown_end - time.time())
# 输出完整的识别结果到运行日志
content_preview = (content or "")[:60] if content else "未识别到"
analyser._log_kv(
"福袋详情",
"read_fudai_detail_once 完整识别结果",
f"read_fudai_detail_once 完整识别结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
status="ok",
room_title=room_title,
room_title_raw=room_title_raw,
@@ -746,9 +747,10 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
)
# 输出到行为日志(使用更详细的格式)
content_preview = (content or "")[:60] if content else "未识别到"
analyser._log_kv(
"行为",
"识别福袋详情完成",
f"识别福袋详情完成:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
action="识别福袋详情",
result="成功",
detail={
@@ -998,6 +1000,26 @@ def read_fudai_detail_with_retries(
is_coupon_popup = (last_status == "coupon_popup")
is_watch_task = (last_status == "watch_task")
# 获取直播间名字(所有情况都需要,用于日志输出)
room_title = ""
room_title_raw = ""
try:
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip()
except Exception:
pass
# 格式化时间信息(所有情况都需要,用于日志输出)
cd_end_str = ""
remain_seconds = 0
try:
from datetime import datetime
if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0:
cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S")
remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0
except Exception:
pass
if is_coupon_popup:
try:
analyser._log_kv(
@@ -1008,6 +1030,29 @@ def read_fudai_detail_with_retries(
)
except Exception:
pass
# 输出到行为日志
try:
analyser._log_kv(
"行为",
"识别福袋详情完成(最终结果)",
action="识别福袋详情",
result="优惠券弹窗",
detail={
"直播间": room_title if room_title else room_title_raw,
"直播间原始": room_title_raw,
"福袋内容": content or "",
"倒计时文本": time_text or "",
"参与人数": int(participants or 0),
"福袋份数": int(copies or 0),
"奖品价值": float(prize_value_yuan or 0.0),
"倒计时开始时间": str(cd_start) if cd_start else "",
"倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "",
"剩余秒数": remain_seconds,
"状态": last_status,
},
)
except Exception:
pass
elif is_watch_task:
try:
analyser._log_kv(
@@ -1018,6 +1063,29 @@ def read_fudai_detail_with_retries(
)
except Exception:
pass
# 输出到行为日志
try:
analyser._log_kv(
"行为",
"识别福袋详情完成(最终结果)",
action="识别福袋详情",
result="观看任务",
detail={
"直播间": room_title if room_title else room_title_raw,
"直播间原始": room_title_raw,
"福袋内容": content or "",
"倒计时文本": time_text or "",
"参与人数": int(participants or 0),
"福袋份数": int(copies or 0),
"奖品价值": float(prize_value_yuan or 0.0),
"倒计时开始时间": str(cd_start) if cd_start else "",
"倒计时结束时间": cd_end_str if cd_end_str else str(cd_end) if cd_end else "",
"剩余秒数": remain_seconds,
"状态": last_status,
},
)
except Exception:
pass
# 关闭详情页
try:
close_detail_callback(analyser)
@@ -1056,31 +1124,13 @@ def read_fudai_detail_with_retries(
except Exception:
pass
else:
# 获取直播间名字
room_title = ""
room_title_raw = ""
try:
room_title = str(getattr(analyser, "current_room_title", "") or "").strip()
room_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "").strip()
except Exception:
pass
# 格式化时间信息
cd_end_str = ""
remain_seconds = 0
try:
from datetime import datetime
if cd_end and isinstance(cd_end, (int, float)) and cd_end > 0:
cd_end_str = datetime.fromtimestamp(cd_end).strftime("%Y-%m-%d %H:%M:%S")
remain_seconds = int(cd_end - time.time()) if cd_end > time.time() else 0
except Exception:
pass
# 正常情况(成功或错误):输出到运行日志和行为日志
try:
# 运行日志:完整的福袋详情
content_preview = (content or "")[:60] if content else "未识别到"
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果",
f"read_fudai_detail_with_retries 最终结果:内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
status=last_status,
room_title=room_title,
room_title_raw=room_title_raw,
@@ -1099,7 +1149,7 @@ def read_fudai_detail_with_retries(
# 行为日志:完整的福袋详情
analyser._log_kv(
"行为",
"识别福袋详情完成(最终结果)",
f"识别福袋详情完成(最终结果):内容={content_preview},价值={float(prize_value_yuan or 0.0)}元,倒计时={time_text or '未识别'},剩余{remain_seconds}秒",
action="识别福袋详情",
result="成功" if last_status == "ok" else last_status,
detail={
@@ -1116,8 +1166,18 @@ def read_fudai_detail_with_retries(
"状态": last_status,
},
)
except Exception:
pass
except Exception as e:
# 如果日志输出失败,至少尝试输出简化版本
try:
analyser._log_kv(
"福袋详情",
"read_fudai_detail_with_retries 最终结果(简化)",
status=last_status,
content=content or "",
error=str(e),
)
except Exception:
pass
# 将状态信息存储在 analyser 中,供调用方检查
try:
+346 -31
View File
@@ -127,11 +127,31 @@ def add_reservation_core_logic(
返回:
bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。
"""
start_time = time.time()
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)
# 添加函数入口日志
try:
from datetime import datetime
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
analyser._log_kv(
"预约",
"[预约] add_reservation_core_logic 函数入口",
future_ts=int(ft) if ft > 0 else 0,
future_str=ft_str,
prize_value_yuan=prize_value,
room_title=room_title[:50] if room_title else "",
content=content[:50] if content else "",
queue_len_before=len(reservations),
max_reservations=max_reservations,
)
except Exception:
pass
same_idx: Optional[int] = None
for idx, r in enumerate(reservations):
@@ -229,8 +249,41 @@ def add_reservation_core_logic(
except Exception:
old_val = 0.0
if prize_value > old_val:
try:
analyser._log_kv(
"预约",
"[预约] 检测到重复预约,更新为更高价值",
same_idx=same_idx,
old_value_yuan=old_val,
new_value_yuan=prize_value,
future_ts=int(ft) if ft > 0 else 0,
)
except Exception:
pass
reservations[same_idx].update(dict(item))
else:
try:
analyser._log_kv(
"预约",
"[预约] 检测到重复预约,但新价值不高于旧值,保留旧记录",
same_idx=same_idx,
old_value_yuan=old_val,
new_value_yuan=prize_value,
future_ts=int(ft) if ft > 0 else 0,
)
except Exception:
pass
else:
try:
analyser._log_kv(
"预约",
"[预约] 添加新预约到队列",
future_ts=int(ft) if ft > 0 else 0,
prize_value_yuan=prize_value,
queue_len_before=len(reservations),
)
except Exception:
pass
reservations.append(dict(item))
# 排序 + 按上限裁剪
@@ -278,6 +331,17 @@ def add_reservation_core_logic(
# 按当前排序规则,队尾是"优先级最低"的记录
del reservations[max_reservations:]
queue_full = True
try:
analyser._log_kv(
"预约",
"[预约] 预约队列已满,已裁剪到上限",
max_reservations=max_reservations,
queue_len_after=len(reservations),
dropped_count=len(dropped_items),
)
except Exception:
pass
# 如果队列已满,写入状态文件
if write_state_callback:
@@ -285,6 +349,19 @@ def add_reservation_core_logic(
write_state_callback()
except Exception:
pass
# 添加函数完成日志
try:
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] add_reservation_core_logic 完成",
queue_len_after=len(reservations),
queue_full=queue_full,
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return queue_full
@@ -314,9 +391,26 @@ def cleanup_expired_reservations(
write_state_callback: Optional[Callable[[], None]] = None,
) -> None:
"""清理已过开奖时间的预约,并视情况写入状态文件。"""
start_time = time.time()
try:
now_ts_drop = _now_ts()
before = len(reservations)
# 记录被清理的预约详情
dropped_items_detail = []
for r in reservations:
try:
r_ft = float(r.get("future_ts") or 0.0)
if r_ft <= now_ts_drop:
dropped_items_detail.append({
"future_ts": int(r_ft),
"prize_value_yuan": float(r.get("prize_value_yuan", 0)),
"content": str(r.get("content", ""))[:50],
"room_title": str(r.get("room_title", ""))[:30],
})
except Exception:
pass
reservations[:] = [
r for r in reservations if float(r.get("future_ts") or 0.0) > now_ts_drop
]
@@ -324,11 +418,16 @@ def cleanup_expired_reservations(
if dropped:
try:
from datetime import datetime
now_str = datetime.fromtimestamp(now_ts_drop).strftime("%Y-%m-%d %H:%M:%S")
analyser._log_kv(
"预约",
"[预约] cleanup_expired_reservations",
dropped=dropped,
remain=len(reservations),
"[预约] cleanup_expired_reservations:清理过期预约",
dropped_count=dropped,
remain_count=len(reservations),
now_ts=int(now_ts_drop),
now_str=now_str,
dropped_items=dropped_items_detail[:5], # 只记录前5个,避免日志过长
)
except Exception:
pass
@@ -338,8 +437,36 @@ def cleanup_expired_reservations(
write_state_callback()
except Exception:
pass
except Exception:
else:
try:
analyser._log_kv(
"预约",
"[预约] cleanup_expired_reservations:无需清理",
queue_len=len(reservations),
now_ts=int(now_ts_drop),
)
except Exception:
pass
except Exception as e:
# Best-effort cleanup only; never crash主循环
try:
analyser._log_kv(
"预约",
"[预约] cleanup_expired_reservations 异常",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] cleanup_expired_reservations 完成",
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
@@ -359,7 +486,26 @@ def handle_queue_full_wait_at_earliest(
返回:
bool: 如果已回退到最早开奖的预约直播间,返回 True;否则返回 False。
"""
start_time = time.time()
try:
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest 函数入口",
queue_len=len(reservations) if reservations else 0,
room_pos=room_pos,
)
except Exception:
pass
if not reservations:
try:
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest:预约队列为空,跳过",
)
except Exception:
pass
return False
# 排序确保取到最早开奖的
@@ -373,6 +519,14 @@ def handle_queue_full_wait_at_earliest(
ft = 0.0
if ft <= 0:
try:
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest:最早预约 future_ts 无效,跳过",
future_ts=ft,
)
except Exception:
pass
return False
now_ts = _now_ts()
@@ -382,6 +536,18 @@ def handle_queue_full_wait_at_earliest(
# 如果已经在锁定期内,不需要重复回退
if focus_until > 0 and now_ts < focus_until:
try:
from datetime import datetime
focus_until_str = datetime.fromtimestamp(focus_until).strftime("%Y-%m-%d %H:%M:%S")
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest:已在锁定期内,跳过回退",
focus_until=int(focus_until),
focus_until_str=focus_until_str,
lock_period_remain_seconds=int(focus_until - now_ts),
)
except Exception:
pass
return False
try:
@@ -510,36 +676,39 @@ def handle_queue_full_wait_at_earliest(
time.sleep(1.5)
# 队列满后回退到最早直播间,直接设置参与标志,不管时间窗口是否到达
# 立即参与,不等待开奖窗口
try:
analyser._reservation_back_direct_attend = True
analyser._log_kv(
"预约",
"[预约] 队列满回退后,直接设置参与标志(不等待时间窗口)",
"[预约] 队列满回退后,直接设置参与标志(立即参与,不等待开奖窗口)",
earliest_future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
)
except Exception:
pass
# 设置锁定期:直到最早开奖时间 + 轮询时间
try:
poll_before = float(
getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0
)
except Exception:
poll_before = 10.0
focus_until_new = ft + max(0.0, poll_before)
# 队列满后立即参与,不设置锁定期(设置为0),使用标志控制
# 这样不会影响切换直播间的逻辑,同时后续的 process_reservation_attend_window 不会因为锁定期而跳过
focus_until_new = 0.0 # 设置为0,表示不设置锁定期,使用标志控制
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
try:
from datetime import datetime
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
analyser._log_kv(
"预约",
"[预约] 已回退到最早开奖的预约直播间,直接参与",
"[预约] 已回退到最早开奖的预约直播间,立即参与(不等待开奖窗口)",
earliest_future_ts=int(ft),
earliest_future_str=ft_str,
now_ts=int(now_ts),
focus_until=int(focus_until_new),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
immediate_attend=True,
)
except Exception:
pass
@@ -548,8 +717,28 @@ def handle_queue_full_wait_at_earliest(
write_state_callback()
except Exception:
pass
try:
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest 完成(已回退)",
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return True
try:
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] handle_queue_full_wait_at_earliest 完成(回退失败)",
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return False
@@ -572,6 +761,8 @@ def process_reservation_attend_window(
bool: 若为 True,表示已经触发了回退/跳转,本轮主循环应尽快结束,
让上层逻辑继续后续处理(例如识别详情并参与)。
"""
start_time = time.time()
# 添加函数入口日志
try:
analyser._log_kv(
@@ -608,6 +799,36 @@ def process_reservation_attend_window(
except Exception:
ft = 0.0
# 检查是否已经参与过该预约(通过 _participated_fudai_future_ts)
try:
participated_fudai_ts = getattr(analyser, "_participated_fudai_future_ts", set())
if not isinstance(participated_fudai_ts, set):
participated_fudai_ts = set()
# 检查是否已经参与过(允许5秒误差)
already_participated = False
for participated_ts in participated_fudai_ts:
if abs(ft - participated_ts) <= 5.0:
already_participated = True
break
if already_participated:
# 已经参与过,从预约队列中移除
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:检测到已参与过该预约,从队列中移除",
target_future_ts=int(ft) if ft > 0 else 0,
)
except Exception:
pass
reservations.pop(0)
try:
write_state_callback()
except Exception:
pass
return False
except Exception:
pass
# 添加目标预约的详细信息日志
try:
from datetime import datetime
@@ -717,7 +938,18 @@ def process_reservation_attend_window(
# 3. 如果锁定期还没结束,但预约时间已经到了,检查是否是同一个预约
# - 如果是同一个预约,允许回退(通常已经在目标直播间了)
# - 如果不是同一个预约,不允许回退(需要等待当前预约完成)
if focus_until > 0 and now_ts < focus_until:
# 4. 特殊情况:如果是队列满后立即参与模式(通过标志判断),允许检查时间窗口
# 先检查是否是队列满立即参与模式
is_queue_full_immediate_attend_check = False
try:
queue_full_waiting_check = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
reservation_direct_attend_check = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
if queue_full_waiting_check and reservation_direct_attend_check:
is_queue_full_immediate_attend_check = True
except Exception:
pass
if focus_until > 0 and now_ts < focus_until and abs(focus_until - now_ts) > 1.0 and not is_queue_full_immediate_attend_check:
# 锁定期还没结束,检查是否是同一个预约(允许5秒误差)
expected_focus_until = ft + max(0.0, poll_before)
if abs(focus_until - expected_focus_until) > 5.0:
@@ -751,14 +983,25 @@ def process_reservation_attend_window(
# 如果已经在目标位置(pos_diff == 0),说明已经在目标直播间,不需要再次回退
# 但是需要检查时间窗口是否到达,如果到达了,应该返回 True 表示需要参与
# 或者如果是队列满立即参与模式,直接返回 True
if pos_diff_check == 0:
# 检查时间窗口是否到达
if now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before):
# 时间窗口已到达,虽然已在目标位置,但需要参与,返回 True
# 检查是否是队列满立即参与模式
is_queue_full_immediate_attend_pos = False
try:
queue_full_waiting_pos = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
reservation_direct_attend_pos = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
if queue_full_waiting_pos and reservation_direct_attend_pos:
is_queue_full_immediate_attend_pos = True
except Exception:
pass
# 检查时间窗口是否到达,或者是队列满立即参与模式
if is_queue_full_immediate_attend_pos or (now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before)):
# 时间窗口已到达或队列满立即参与模式,虽然已在目标位置,但需要参与,返回 True
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,且已在目标位置,时间窗口已到达,需要参与",
"[预约] 锁定期未结束但是同一个预约,且已在目标位置,时间窗口已到达或队列满立即参与模式,需要参与",
focus_until=int(focus_until),
target_future_ts=int(ft),
current_room_pos=current_room_pos_check,
@@ -766,15 +1009,17 @@ def process_reservation_attend_window(
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
time_window_end=int(ft + max(0.0, poll_before)),
is_queue_full_immediate_attend=is_queue_full_immediate_attend_pos,
)
except Exception:
pass
# 更新锁定期和待处理标志
focus_until_new = ft + max(0.0, poll_before)
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
# 更新锁定期和待处理标志(如果不是队列满立即参与模式,才设置锁定期)
if not is_queue_full_immediate_attend_pos:
focus_until_new = ft + max(0.0, poll_before)
if reservation_focus_until_ts_ref:
reservation_focus_until_ts_ref[0] = focus_until_new
else:
reservation_focus_until_ts_ref.append(focus_until_new)
if reservation_after_action_pending_ref:
reservation_after_action_pending_ref[0] = True
@@ -819,15 +1064,43 @@ def process_reservation_attend_window(
except Exception:
pass
if now_ts < ft - dynamic_ahead:
# 还没到窗口
# 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期)
is_queue_full_immediate_attend = False
try:
# 检查队列满等待标志和直接参与标志
queue_full_waiting = bool(getattr(analyser, "queue_full_waiting_at_earliest", False) or False)
reservation_direct_attend = bool(getattr(analyser, "_reservation_back_direct_attend", False) or False)
if queue_full_waiting and reservation_direct_attend:
is_queue_full_immediate_attend = True
try:
analyser._log_kv(
"预约",
"[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与",
queue_full_waiting=queue_full_waiting,
reservation_direct_attend=reservation_direct_attend,
target_future_ts=int(ft),
)
except Exception:
pass
except Exception:
pass
if not is_queue_full_immediate_attend and now_ts < ft - dynamic_ahead:
# 还没到窗口(非队列满立即参与模式)
try:
from datetime import datetime
time_window_start_ts = ft - dynamic_ahead
time_window_start_str = datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_start_ts > 0 else "无效"
analyser._log_kv(
"预约",
"[预约] 时间窗口未到,跳过回退",
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
now_str=datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S"),
time_window_start=int(time_window_start_ts),
time_window_start_str=time_window_start_str,
remain_seconds=int((ft - dynamic_ahead) - now_ts),
target_future_ts=int(ft),
dynamic_ahead=dynamic_ahead,
)
except Exception:
pass
@@ -980,6 +1253,22 @@ def process_reservation_attend_window(
write_state_callback()
except Exception:
pass
# 添加函数完成日志
try:
from datetime import datetime
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 返回结果",
result="已触发回退",
future_ts=int(ft),
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return True
@@ -1001,6 +1290,22 @@ def process_reservation_attend_window(
write_state_callback()
except Exception:
pass
# 添加函数完成日志
try:
from datetime import datetime
elapsed = time.time() - start_time
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 返回结果",
result="未触发回退",
future_ts=int(ft) if ft > 0 else 0,
now_ts=int(now_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
elapsed_seconds=round(elapsed, 3),
)
except Exception:
pass
return False
@@ -1075,13 +1380,23 @@ def record_high_value_reservation(
pass
try:
from datetime import datetime
created_str = datetime.fromtimestamp(item["created_ts"]).strftime("%Y-%m-%d %H:%M:%S")
analyser._log_kv(
"预约",
"[预约] record_high_value_reservation:已记录高价值福袋",
value=item["prize_value_yuan"],
future_ts=item["future_ts"],
value_yuan=item["prize_value_yuan"],
future_ts=int(item["future_ts"]),
future_str=future_str,
room_title=room_title[:30] if room_title else "",
created_ts=int(item["created_ts"]),
created_str=created_str,
room_title=room_title[:50] if room_title else "",
room_title_raw=room_title_raw[:50] if room_title_raw else "",
content=fudai_content_text[:50] if fudai_content_text else "",
pos_seen=room_pos,
task_count=task_count,
participants=participants,
copies=copies,
queue_len=len(reservations),
)
except Exception:
+103
View File
@@ -2341,6 +2341,91 @@ def main():
("fudai_skip_countdown_long", "跳过-倒计时太长"),
("fudai_skip_watch_required", "跳过-需要看播"),
]
# 高价值预约统计
fudai_reserved_high_value = counters.get("fudai_reserved_high_value", 0)
if fudai_reserved_high_value > 0:
lines.append("=" * 60)
lines.append("高价值预约统计")
lines.append("=" * 60)
lines.append(f"倒计时大于阈值但价值达到高价值阈值,记录预约: {fudai_reserved_high_value}")
lines.append("")
# 等待开奖统计
fudai_waiting_lottery = counters.get("fudai_waiting_lottery", 0)
if fudai_waiting_lottery > 0:
lines.append("=" * 60)
lines.append("等待开奖统计")
lines.append("=" * 60)
lines.append(f"等待开奖次数: {fudai_waiting_lottery}")
lines.append("")
# 阶段诊断统计
stage_diagnosis_complete = counters.get("stage_diagnosis_complete", 0)
stage_diagnosis_failed = counters.get("stage_diagnosis_failed", 0)
if stage_diagnosis_complete > 0 or stage_diagnosis_failed > 0:
lines.append("=" * 60)
lines.append("阶段诊断统计")
lines.append("=" * 60)
lines.append(f"诊断完成: {stage_diagnosis_complete}")
lines.append(f"诊断失败: {stage_diagnosis_failed}")
if stage_diagnosis_complete > 0:
success_rate = (stage_diagnosis_complete / (stage_diagnosis_complete + stage_diagnosis_failed)) * 100
lines.append(f"成功率: {success_rate:.1f}%")
lines.append("")
# OCR识别统计
ocr_attempt = counters.get("ocr_attempt", 0)
ocr_success = counters.get("ocr_success", 0)
ocr_failed = counters.get("ocr_failed", 0)
if ocr_attempt > 0:
lines.append("=" * 60)
lines.append("OCR识别统计")
lines.append("=" * 60)
lines.append(f"OCR尝试次数: {ocr_attempt}")
lines.append(f"OCR成功次数: {ocr_success}")
lines.append(f"OCR失败次数: {ocr_failed}")
if ocr_attempt > 0:
ocr_rate = (ocr_success / ocr_attempt) * 100
lines.append(f"OCR成功率: {ocr_rate:.1f}%")
lines.append("")
# 详情识别统计
fudai_detail_read_attempt = counters.get("fudai_detail_read_attempt", 0)
fudai_detail_read_success = counters.get("fudai_detail_read_success", 0)
fudai_detail_read_failed = counters.get("fudai_detail_read_failed", 0)
if fudai_detail_read_attempt > 0:
lines.append("=" * 60)
lines.append("详情识别统计")
lines.append("=" * 60)
lines.append(f"详情识别尝试: {fudai_detail_read_attempt}")
lines.append(f"详情识别成功: {fudai_detail_read_success}")
lines.append(f"详情识别失败: {fudai_detail_read_failed}")
if fudai_detail_read_attempt > 0:
detail_rate = (fudai_detail_read_success / fudai_detail_read_attempt) * 100
lines.append(f"详情识别成功率: {detail_rate:.1f}%")
lines.append("")
# 福袋查找统计
fudai_find_success = counters.get("fudai_find_success", 0)
fudai_find_not_found = counters.get("fudai_find_not_found", 0)
fudai_find_timeout = counters.get("fudai_find_timeout", 0)
if fudai_find_success > 0 or fudai_find_not_found > 0 or fudai_find_timeout > 0:
lines.append("=" * 60)
lines.append("福袋查找统计")
lines.append("=" * 60)
lines.append(f"查找成功: {fudai_find_success}")
lines.append(f"未找到: {fudai_find_not_found}")
lines.append(f"等待超时: {fudai_find_timeout}")
lines.append("")
# 性能统计(慢操作)
slow_operation = counters.get("slow_operation", 0)
if slow_operation > 0:
lines.append("=" * 60)
lines.append("性能统计")
lines.append("=" * 60)
lines.append(f"慢操作(>5秒)次数: {slow_operation}")
lines.append("")
skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)
if skip_total > 0:
lines.append("=" * 60)
@@ -2419,6 +2504,10 @@ def main():
reservation_queue_full_wait = counters.get("reservation_queue_full_wait", 0)
reservation_drop_low_value = counters.get("reservation_drop_low_value", 0)
reservation_clear = counters.get("reservation_clear", 0)
reservation_back_direct_attend = counters.get("reservation_back_direct_attend", 0)
reservation_queue_full_back_attend = counters.get("reservation_queue_full_back_attend", 0)
reservation_duplicate_detected = counters.get("reservation_duplicate_detected", 0)
reservation_back_operation = counters.get("reservation_back_operation", 0)
reservation_total = (
reservation_recorded
@@ -2434,6 +2523,10 @@ def main():
+ reservation_queue_full_wait
+ reservation_drop_low_value
+ reservation_clear
+ reservation_back_direct_attend
+ reservation_queue_full_back_attend
+ reservation_duplicate_detected
+ reservation_back_operation
)
if reservation_total > 0 or reservation_recorded > 0:
@@ -2480,6 +2573,16 @@ def main():
lines.append(f"丢弃低价值预约: {reservation_drop_low_value}")
if reservation_clear > 0:
lines.append(f"清空预约队列: {reservation_clear}")
if reservation_duplicate_detected > 0:
lines.append(f"检测到重复预约: {reservation_duplicate_detected}")
# 回退后直接参与统计
if reservation_back_direct_attend > 0:
lines.append(f"回退后直接参与: {reservation_back_direct_attend}")
if reservation_queue_full_back_attend > 0:
lines.append(f"队列满回退后参与: {reservation_queue_full_back_attend}")
if reservation_back_operation > 0:
lines.append(f"回退操作次数: {reservation_back_operation}")
# 预约成功率
if reservation_recorded > 0 and reservation_back_success > 0:
+289 -31
View File
@@ -167,31 +167,60 @@ class Runner:
self._last_log_ts = time.time()
# --- 福袋:抽取"最近一次"识别到的信息 ---
# 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容="
content_extracted = False
if "福袋内容:" in s:
with self._lock:
self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip()
self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip().split()[0] # 只取第一个词,避免包含后续字段
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
else:
# 新格式:字段_内容= 或 内容=
m = re.search(r"(?:字段_)?内容[=:]\s*([^\s]+)", s)
if m:
with self._lock:
self._fudai_last["content"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
if content_extracted:
self._inc("fudai_seen")
self._record_event("fudai_seen", self._snapshot_fudai())
m = re.search(r"参与人数:\s*(\d+)", s)
# 参与人数:支持多种格式
m = re.search(r"(?:字段_)?参与人数[=:]?\s*(\d+)", s)
if not m:
m = re.search(r"参与人数:\s*(\d+)", s)
if m:
with self._lock:
self._fudai_last["participants"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"福袋份数:\s*(\d+)", s)
# 福袋份数:支持多种格式
m = re.search(r"(?:字段_)?份数[=:]?\s*(\d+)", s)
if not m:
m = re.search(r"福袋份数:\s*(\d+)", s)
if m:
with self._lock:
self._fudai_last["copies"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
# 倒计时:支持多种格式
if "倒计时时间:" in s:
with self._lock:
self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip()
self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip().split()[0]
self._fudai_last["updated_ts"] = time.time()
else:
m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s)
if m:
with self._lock:
self._fudai_last["countdown"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
# 奖品价值:支持多种格式
m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if not m:
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
if m:
try:
with self._lock:
@@ -201,45 +230,105 @@ class Runner:
pass
# --- 福袋:关键流程计数 ---
if "点击打开福袋详情" in s:
if "点击打开福袋详情" in s or ("[流程]" in s and "检测到福袋图标并点击" in s):
self._inc("fudai_open_detail")
self._record_event("fudai_open_detail", self._snapshot_fudai())
if "点击参与抽奖" in s or ("[参与]" in s and "动作=点击参与" in s):
if "点击参与抽奖" in s or ("[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s)):
self._inc("fudai_click_attend")
self._record_event("fudai_click_attend", self._snapshot_fudai())
# 参与成功/已参与
# 参与成功/已参与:支持更多格式
if (
"已经参与,等待开奖" in s
or "已经参与,等待看播时间凑齐开奖" in s
or "已参与成功(或看播中)" in s
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s))
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s))
or ("[参与]" in s and "已参与" in s and "等待开奖" in s)
or ("预约回退后直接参与" in s and "参与成功" in s)
):
self._inc("fudai_attend_ok")
self._record_event("fudai_attend_ok", self._snapshot_fudai())
if "参与抽奖失败" in s:
if "参与抽奖失败" in s or ("[参与]" in s and "结果=失败" in s):
self._inc("fudai_attend_fail")
self._record_event("fudai_attend_fail", self._snapshot_fudai())
# --- 福袋:跳过/过滤原因 ---
if "参与人数" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_low")
self._record_event("fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()})
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "participants_low", **meta})
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_high")
self._record_event("fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()})
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "participants_high", **meta})
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_value_low")
self._record_event("fudai_skip", {"reason": "value_low", **self._snapshot_fudai()})
if "福袋内容不理想" in s:
# 提取实际价值和阈值
meta = self._snapshot_fudai()
m = re.search(r"(?:奖品)?价值[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["threshold"] = float(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "value_low", **meta})
if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s):
self._inc("fudai_skip_content")
self._record_event("fudai_skip", {"reason": "content", **self._snapshot_fudai()})
if "抽奖倒计时时间小于" in s and "不参与" in s:
self._inc("fudai_skip_countdown_short")
self._record_event("fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()})
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "countdown_short", **meta})
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
self._inc("fudai_skip_countdown_long")
self._record_event("fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()})
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "countdown_long", **meta})
if (
"需要看播时长:默认不参与" in s
or "需要开始观看/看播门槛:默认不参与" in s
@@ -247,12 +336,30 @@ class Runner:
):
self._inc("fudai_skip_watch_required")
self._record_event("fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()})
if "打开福袋异常" in s:
if "打开福袋异常" in s or ("[流程]" in s and "打开福袋异常" in s):
self._inc("fudai_open_error")
self._record_event("fudai_open_error", self._snapshot_fudai())
if "超过10次点击福袋无法打开详情" in s:
self._inc("fudai_open_error_too_many")
self._record_event("fudai_open_error_too_many", self._snapshot_fudai())
# 倒计时大于阈值但价值达到高价值阈值,记录预约
if ("[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s):
self._inc("fudai_reserved_high_value")
# 提取价值和倒计时信息
meta = self._snapshot_fudai()
m = re.search(r"(?:价值|价值元)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_reserved_high_value", meta)
# --- 错误和异常统计 ---
if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s:
@@ -349,22 +456,51 @@ class Runner:
# --- 预约记录相关 ---
if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s:
self._inc("reservation_recorded")
# 提取预约价值
m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s)
# 提取预约价值:支持多种格式
value = None
m = re.search(r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", s)
if not m:
m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s)
if m:
try:
value = float(m.group(1))
self._record_event("reservation_recorded", {"prize_value_yuan": value, **self._snapshot_fudai()})
except Exception:
self._record_event("reservation_recorded", self._snapshot_fudai())
else:
self._record_event("reservation_recorded", self._snapshot_fudai())
pass
# 提取开奖时间
future_ts = None
m = re.search(r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)", s)
if m:
try:
future_ts = int(m.group(1))
except Exception:
pass
# 提取直播间名称
room_title = None
m = re.search(r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s)
if m:
room_title = m.group(1).strip()
meta = self._snapshot_fudai()
if value is not None:
meta["prize_value_yuan"] = value
if future_ts is not None:
meta["future_ts"] = future_ts
if room_title:
meta["room_title"] = room_title
self._record_event("reservation_recorded", meta)
if ("[预约]" in s and "进入预约参与窗口" in s) or "进入预约参与窗口,准备回退到目标直播间" in s:
self._inc("reservation_window_entered")
self._record_event("reservation_window_entered", {})
if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间,等待详情识别与参与" in s:
if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间" in s or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s):
self._inc("reservation_back_success")
self._record_event("reservation_back_success", {})
# 提取回退信息
meta = {}
m = re.search(r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_success", meta)
if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s:
self._inc("reservation_window_not_reached")
self._record_event("reservation_window_not_reached", {})
@@ -373,7 +509,7 @@ class Runner:
self._record_event("reservation_expired", {})
if ("[预约]" in s and "预约队列为空" in s) or "process_reservation_attend_window:预约队列为空" in s:
self._inc("reservation_queue_empty")
if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束且不是当前预约" in s:
if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s:
self._inc("reservation_locked")
self._record_event("reservation_locked", {})
if ("[预约]" in s and "已回退到第一个直播间" in s):
@@ -382,24 +518,53 @@ class Runner:
if ("[预约]" in s and "run_once_basic:检查预约回退触发条件" in s):
self._inc("reservation_check_triggered")
# 预约队列满时等待
if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s:
if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s):
self._inc("reservation_queue_full_wait")
self._record_event("reservation_queue_full_wait", {})
# 回退后直接参与
if ("[预约]" in s and "预约回退后直接参与" in s) or "预约回退后直接参与" in s:
self._inc("reservation_back_direct_attend")
self._record_event("reservation_back_direct_attend", {})
# 队列满回退后设置参与标志
if ("[预约]" in s and "队列满回退后,直接设置参与标志" in s):
self._inc("reservation_queue_full_back_attend")
self._record_event("reservation_queue_full_back_attend", {})
# 通过相似度匹配识别重复预约
if ("[预约]" in s and "通过相似度匹配识别为重复预约" in s):
self._inc("reservation_duplicate_detected")
self._record_event("reservation_duplicate_detected", {})
# --- 开奖结果 ---
if "没有抽中" in s and "关闭弹窗" in s:
self._inc("fudai_result_no_win")
self._record_event("fudai_result_no_win", self._snapshot_fudai())
if "恭喜中奖了" in s or "检测到中奖结果" in s:
if "恭喜中奖了" in s or "检测到中奖结果" in s or ("[开奖结果]" in s and "中奖" in s):
self._inc("fudai_result_win")
self._record_event("fudai_result_win", self._snapshot_fudai())
# 提取中奖信息
meta = self._snapshot_fudai()
m = re.search(r"(?:奖品|商品)[=:]?\s*([^\s]+)", s)
if m:
meta["prize"] = m.group(1).strip()
self._record_event("fudai_result_win", meta)
self._record_win()
if "福袋商品下单成功" in s:
if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s):
self._inc("fudai_order_success")
self._record_event("fudai_order_success", self._snapshot_fudai())
# 等待开奖
if ("[参与]" in s and "等待开奖" in s) or "等待开奖中" in s:
self._inc("fudai_waiting_lottery")
# 提取剩余秒数
meta = self._snapshot_fudai()
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_waiting_lottery", meta)
# --- 直播间切换(按原因粗分) ---
if "上划切换直播间" in s:
if "上划切换直播间" in s or ("[操作]" in s and "上滑切换直播间" in s):
self._inc("switch_room")
meta_reason = "unknown"
if "无福袋" in s:
@@ -420,7 +585,100 @@ class Runner:
elif "参与抽奖失败" in s:
self._inc("switch_room_attend_fail")
meta_reason = "attend_fail"
elif "记录预约后" in s:
self._inc("switch_room_after_reservation")
meta_reason = "after_reservation"
elif "锁定期内" in s:
self._inc("switch_room_locked")
meta_reason = "locked"
self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()})
# --- 阶段诊断统计 ---
if "[阶段诊断]" in s or "阶段诊断" in s:
if "阶段诊断完成" in s:
self._inc("stage_diagnosis_complete")
# 提取阶段和耗时
meta = {}
m = re.search(r"阶段[=:]?\s*(\w+)", s)
if m:
meta["stage"] = m.group(1)
m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s)
if m:
try:
meta["elapsed_seconds"] = float(m.group(1))
except Exception:
pass
m = re.search(r"分数[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["score"] = float(m.group(1))
except Exception:
pass
self._record_event("stage_diagnosis_complete", meta)
elif "阶段诊断失败" in s or "阶段诊断错误" in s:
self._inc("stage_diagnosis_failed")
self._record_event("stage_diagnosis_failed", {})
# --- OCR识别统计 ---
if "[福袋]" in s and "OCR识别" in s:
self._inc("ocr_attempt")
if "识别成功" in s or "识别完成" in s:
self._inc("ocr_success")
elif "识别失败" in s or "识别错误" in s:
self._inc("ocr_failed")
# --- 性能统计 ---
m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s)
if m:
try:
elapsed = float(m.group(1))
# 记录耗时较长的操作
if elapsed > 5.0:
self._inc("slow_operation")
self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]})
except Exception:
pass
# --- 详情识别统计 ---
if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s:
self._inc("fudai_detail_read_attempt")
if "识别成功" in s or "识别完成" in s or "read_fudai_detail_once完成(成功)" in s:
self._inc("fudai_detail_read_success")
# 提取任务数量
meta = {}
m = re.search(r"(?:任务数量|task_count)[=:]?\s*(\d+)", s)
if m:
try:
meta["task_count"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_detail_read_success", meta)
elif "识别失败" in s or "识别错误" in s:
self._inc("fudai_detail_read_failed")
self._record_event("fudai_detail_read_failed", {})
# --- 福袋查找统计 ---
if "[福袋查找]" in s or "查找福袋" in s:
if "检测完成" in s and "命中" in s:
self._inc("fudai_find_success")
elif "检测完成" in s and "未找到" in s:
self._inc("fudai_find_not_found")
elif "等待超时" in s:
self._inc("fudai_find_timeout")
# --- 回退操作统计 ---
if ("[预约]" in s and "回退" in s) or "回退到" in s:
if "回退完成" in s or "回退成功" in s:
self._inc("reservation_back_operation")
# 提取回退次数
meta = {}
m = re.search(r"(?:回退|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_operation", meta)
def get_stats(self) -> dict:
with self._lock:
+6
View File
@@ -105,6 +105,12 @@ paddlepaddle>=2.5.0,<3.0.0
+6
View File
@@ -82,6 +82,12 @@ types-requests>=2.31.0
+6
View File
@@ -121,6 +121,12 @@ ttkbootstrap>=1.10.0
+6
View File
@@ -158,6 +158,12 @@ if __name__ == "__main__":
+21 -6
View File
@@ -1,8 +1,23 @@
{
"updated_ts": 1766758218.9022133,
"reason": "startup_clear",
"updated_ts": 1766802683.092151,
"reason": "record_reservation",
"room_pos": 0,
"current_room_title": "",
"current_room_title_raw": "",
"reservations": []
}
"current_room_title": "罗2458万本场直",
"current_room_title_raw": "罗'245.8万本场直",
"reservations": [
{
"prize_value_yuan": 5999.0,
"content": "22后开奖10(瓜瓜专属]jhone17256GB颜色随机发货",
"future_ts": 1766803299.920004,
"future_str": "2025-12-27 10:41:39",
"pos_seen": 0,
"room_title": "罗2458万本场直",
"room_title_raw": "罗'245.8万本场直",
"created_ts": 1766802683.0830607,
"task_count": 2,
"time_text": "10:22",
"participants": 5057,
"copies": 1
}
]
}
+6
View File
@@ -81,6 +81,12 @@ if os.path.exists(log_file):
+6
View File
@@ -94,6 +94,12 @@ if os.path.exists(log_file):
+6
View File
@@ -227,6 +227,12 @@ pytest --pdb --pdbcls=IPython.terminal.debugger:Pdb
+6
View File
@@ -64,6 +64,12 @@ __version__ = "1.0.0"
+6
View File
@@ -53,6 +53,12 @@
+6
View File
@@ -53,6 +53,12 @@
+286 -29
View File
@@ -279,27 +279,54 @@ class ProcRunner:
self._mdc_context[key] = value
# --- 福袋:抽取"最近一次"识别到的信息 ---
# 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容="
content_extracted = False
if "福袋内容:" in s:
self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip()
self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip().split()[0] # 只取第一个词,避免包含后续字段
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
else:
# 新格式:字段_内容= 或 内容=
m = re.search(r"(?:字段_)?内容[=:]\s*([^\s]+)", s)
if m:
self._fudai_last["content"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
if content_extracted:
self._inc("fudai_seen")
self._record_event("fudai_seen", self._snapshot_fudai())
m = re.search(r"参与人数:\s*(\d+)", s)
# 参与人数:支持多种格式
m = re.search(r"(?:字段_)?参与人数[=:]?\s*(\d+)", s)
if not m:
m = re.search(r"参与人数:\s*(\d+)", s)
if m:
self._fudai_last["participants"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"福袋份数:\s*(\d+)", s)
# 福袋份数:支持多种格式
m = re.search(r"(?:字段_)?份数[=:]?\s*(\d+)", s)
if not m:
m = re.search(r"福袋份数:\s*(\d+)", s)
if m:
self._fudai_last["copies"] = int(m.group(1))
self._fudai_last["updated_ts"] = time.time()
# 倒计时:支持多种格式
if "倒计时时间:" in s:
self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip()
self._fudai_last["countdown"] = s.split("倒计时时间:", 1)[1].strip().split()[0]
self._fudai_last["updated_ts"] = time.time()
else:
m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s)
if m:
self._fudai_last["countdown"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
# 奖品价值:支持多种格式
m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if not m:
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
if m:
try:
self._fudai_last["prize_value_yuan"] = float(m.group(1))
@@ -308,11 +335,11 @@ class ProcRunner:
pass
# --- 福袋:关键流程计数 ---
if "点击打开福袋详情" in s:
if "点击打开福袋详情" in s or ("[流程]" in s and "检测到福袋图标并点击" in s):
self._inc("fudai_open_detail")
self._record_event("fudai_open_detail", self._snapshot_fudai())
# 兼容新结构化中文日志: [参与] 动作=点击参与
if "点击参与抽奖" in s or ("[参与]" in s and "动作=点击参与" in s):
if "点击参与抽奖" in s or ("[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s)):
self._inc("fudai_click_attend")
self._record_event("fudai_click_attend", self._snapshot_fudai())
@@ -321,44 +348,104 @@ class ProcRunner:
"已经参与,等待开奖" in s
or "已经参与,等待看播时间凑齐开奖" in s
or "已参与成功(或看播中)" in s
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s))
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s))
or ("[参与]" in s and "已参与" in s and "等待开奖" in s)
or ("预约回退后直接参与" in s and "参与成功" in s)
):
self._inc("fudai_attend_ok")
self._record_event("fudai_attend_ok", self._snapshot_fudai())
if "参与抽奖失败" in s:
if "参与抽奖失败" in s or ("[参与]" in s and "结果=失败" in s):
self._inc("fudai_attend_fail")
self._record_event("fudai_attend_fail", self._snapshot_fudai())
# --- 福袋:跳过/过滤原因 ---
if "参与人数" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_low")
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event(
"fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()}
"fudai_skip", {"reason": "participants_low", **meta}
)
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_high")
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event(
"fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()}
"fudai_skip", {"reason": "participants_high", **meta}
)
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_value_low")
# 提取实际价值和阈值
meta = self._snapshot_fudai()
m = re.search(r"(?:奖品)?价值[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["threshold"] = float(m.group(1))
except Exception:
pass
self._record_event(
"fudai_skip", {"reason": "value_low", **self._snapshot_fudai()}
"fudai_skip", {"reason": "value_low", **meta}
)
if "福袋内容不理想" in s:
if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s):
self._inc("fudai_skip_content")
self._record_event(
"fudai_skip", {"reason": "content", **self._snapshot_fudai()}
)
if "抽奖倒计时时间小于" in s and "不参与" in s:
self._inc("fudai_skip_countdown_short")
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event(
"fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()}
"fudai_skip", {"reason": "countdown_short", **meta}
)
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
self._inc("fudai_skip_countdown_long")
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event(
"fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()}
"fudai_skip", {"reason": "countdown_long", **meta}
)
# 看播门槛:默认不参与(新结构化日志)
if (
@@ -370,12 +457,30 @@ class ProcRunner:
self._record_event(
"fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()}
)
if "打开福袋异常" in s:
if "打开福袋异常" in s or ("[流程]" in s and "打开福袋异常" in s):
self._inc("fudai_open_error")
self._record_event("fudai_open_error", self._snapshot_fudai())
if "超过10次点击福袋无法打开详情" in s:
self._inc("fudai_open_error_too_many")
self._record_event("fudai_open_error_too_many", self._snapshot_fudai())
# 倒计时大于阈值但价值达到高价值阈值,记录预约
if ("[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s):
self._inc("fudai_reserved_high_value")
# 提取价值和倒计时信息
meta = self._snapshot_fudai()
m = re.search(r"(?:价值|价值元)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_reserved_high_value", meta)
# --- 错误和异常统计(与 gui_core.py 保持一致) ---
if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s:
@@ -464,21 +569,51 @@ class ProcRunner:
# --- 预约记录相关(与 gui_core.py 保持一致) ---
if ("[预约]" in s and "已记录高价值福袋" in s) or "record_high_value_reservation:已记录高价值福袋" in s:
self._inc("reservation_recorded")
m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s)
# 提取预约价值:支持多种格式
value = None
m = re.search(r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", s)
if not m:
m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s)
if m:
try:
value = float(m.group(1))
self._record_event("reservation_recorded", {"prize_value_yuan": value, **self._snapshot_fudai()})
except Exception:
self._record_event("reservation_recorded", self._snapshot_fudai())
else:
self._record_event("reservation_recorded", self._snapshot_fudai())
pass
# 提取开奖时间
future_ts = None
m = re.search(r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)", s)
if m:
try:
future_ts = int(m.group(1))
except Exception:
pass
# 提取直播间名称
room_title = None
m = re.search(r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s)
if m:
room_title = m.group(1).strip()
meta = self._snapshot_fudai()
if value is not None:
meta["prize_value_yuan"] = value
if future_ts is not None:
meta["future_ts"] = future_ts
if room_title:
meta["room_title"] = room_title
self._record_event("reservation_recorded", meta)
if ("[预约]" in s and "进入预约参与窗口" in s) or "进入预约参与窗口,准备回退到目标直播间" in s:
self._inc("reservation_window_entered")
self._record_event("reservation_window_entered", {})
if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间,等待详情识别与参与" in s:
if ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间" in s or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s):
self._inc("reservation_back_success")
self._record_event("reservation_back_success", {})
# 提取回退信息
meta = {}
m = re.search(r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_success", meta)
if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s:
self._inc("reservation_window_not_reached")
self._record_event("reservation_window_not_reached", {})
@@ -487,7 +622,7 @@ class ProcRunner:
self._record_event("reservation_expired", {})
if ("[预约]" in s and "预约队列为空" in s) or "process_reservation_attend_window:预约队列为空" in s:
self._inc("reservation_queue_empty")
if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束且不是当前预约" in s:
if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s:
self._inc("reservation_locked")
self._record_event("reservation_locked", {})
if ("[预约]" in s and "已回退到第一个直播间" in s):
@@ -495,24 +630,53 @@ class ProcRunner:
self._record_event("reservation_back_to_first", {})
if ("[预约]" in s and "run_once_basic:检查预约回退触发条件" in s):
self._inc("reservation_check_triggered")
if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s:
if ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s):
self._inc("reservation_queue_full_wait")
self._record_event("reservation_queue_full_wait", {})
# 回退后直接参与
if ("[预约]" in s and "预约回退后直接参与" in s) or "预约回退后直接参与" in s:
self._inc("reservation_back_direct_attend")
self._record_event("reservation_back_direct_attend", {})
# 队列满回退后设置参与标志
if ("[预约]" in s and "队列满回退后,直接设置参与标志" in s):
self._inc("reservation_queue_full_back_attend")
self._record_event("reservation_queue_full_back_attend", {})
# 通过相似度匹配识别重复预约
if ("[预约]" in s and "通过相似度匹配识别为重复预约" in s):
self._inc("reservation_duplicate_detected")
self._record_event("reservation_duplicate_detected", {})
# --- 开奖结果 ---
if "没有抽中" in s and "关闭弹窗" in s:
self._inc("fudai_result_no_win")
self._record_event("fudai_result_no_win", self._snapshot_fudai())
if "恭喜中奖了" in s or "检测到中奖结果" in s:
if "恭喜中奖了" in s or "检测到中奖结果" in s or ("[开奖结果]" in s and "中奖" in s):
self._inc("fudai_result_win")
self._record_event("fudai_result_win", self._snapshot_fudai())
# 提取中奖信息
meta = self._snapshot_fudai()
m = re.search(r"(?:奖品|商品)[=:]?\s*([^\s]+)", s)
if m:
meta["prize"] = m.group(1).strip()
self._record_event("fudai_result_win", meta)
self._record_win()
if "福袋商品下单成功" in s:
if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s):
self._inc("fudai_order_success")
self._record_event("fudai_order_success", self._snapshot_fudai())
# 等待开奖
if ("[参与]" in s and "等待开奖" in s) or "等待开奖中" in s:
self._inc("fudai_waiting_lottery")
# 提取剩余秒数
meta = self._snapshot_fudai()
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_waiting_lottery", meta)
# --- 直播间切换(按原因粗分) ---
if "上划切换直播间" in s:
if "上划切换直播间" in s or ("[操作]" in s and "上滑切换直播间" in s):
self._inc("switch_room")
meta_reason = "unknown"
if "无福袋" in s:
@@ -533,9 +697,102 @@ class ProcRunner:
elif "参与抽奖失败" in s:
self._inc("switch_room_attend_fail")
meta_reason = "attend_fail"
elif "记录预约后" in s:
self._inc("switch_room_after_reservation")
meta_reason = "after_reservation"
elif "锁定期内" in s:
self._inc("switch_room_locked")
meta_reason = "locked"
self._record_event(
"switch_room", {"reason": meta_reason, **self._snapshot_fudai()}
)
# --- 阶段诊断统计 ---
if "[阶段诊断]" in s or "阶段诊断" in s:
if "阶段诊断完成" in s:
self._inc("stage_diagnosis_complete")
# 提取阶段和耗时
meta = {}
m = re.search(r"阶段[=:]?\s*(\w+)", s)
if m:
meta["stage"] = m.group(1)
m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s)
if m:
try:
meta["elapsed_seconds"] = float(m.group(1))
except Exception:
pass
m = re.search(r"分数[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["score"] = float(m.group(1))
except Exception:
pass
self._record_event("stage_diagnosis_complete", meta)
elif "阶段诊断失败" in s or "阶段诊断错误" in s:
self._inc("stage_diagnosis_failed")
self._record_event("stage_diagnosis_failed", {})
# --- OCR识别统计 ---
if "[福袋]" in s and "OCR识别" in s:
self._inc("ocr_attempt")
if "识别成功" in s or "识别完成" in s:
self._inc("ocr_success")
elif "识别失败" in s or "识别错误" in s:
self._inc("ocr_failed")
# --- 性能统计 ---
m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s)
if m:
try:
elapsed = float(m.group(1))
# 记录耗时较长的操作
if elapsed > 5.0:
self._inc("slow_operation")
self._record_event("slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]})
except Exception:
pass
# --- 详情识别统计 ---
if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s:
self._inc("fudai_detail_read_attempt")
if "识别成功" in s or "识别完成" in s or "read_fudai_detail_once完成(成功)" in s:
self._inc("fudai_detail_read_success")
# 提取任务数量
meta = {}
m = re.search(r"(?:任务数量|task_count)[=:]?\s*(\d+)", s)
if m:
try:
meta["task_count"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_detail_read_success", meta)
elif "识别失败" in s or "识别错误" in s:
self._inc("fudai_detail_read_failed")
self._record_event("fudai_detail_read_failed", {})
# --- 福袋查找统计 ---
if "[福袋查找]" in s or "查找福袋" in s:
if "检测完成" in s and "命中" in s:
self._inc("fudai_find_success")
elif "检测完成" in s and "未找到" in s:
self._inc("fudai_find_not_found")
elif "等待超时" in s:
self._inc("fudai_find_timeout")
# --- 回退操作统计 ---
if ("[预约]" in s and "回退" in s) or "回退到" in s:
if "回退完成" in s or "回退成功" in s:
self._inc("reservation_back_operation")
# 提取回退次数
meta = {}
m = re.search(r"(?:回退|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_operation", meta)
# --- 性能:进入直播间到识别福袋耗时 ---
m = re.search(
+6
View File
@@ -143,6 +143,12 @@ python check_gpu_available.py
+6
View File
@@ -149,6 +149,12 @@
+6
View File
@@ -221,6 +221,12 @@ if __name__ == "__main__":
+6
View File
@@ -149,6 +149,12 @@
+365
View File
@@ -0,0 +1,365 @@
# 预约系统详细流程说明
## 一、预约记录流程
### 1.1 触发条件
当识别到高价值福袋时,会触发预约记录流程:
- **高价值判断**:福袋价值 >= `high_value_fudai_threshold_yuan`(默认配置)
- **倒计时检查**:倒计时大于阈值(`skip_if_countdown_gt_seconds`)
- **剩余秒数检查**:剩余秒数 > `high_value_fudai_join_ahead_seconds`(默认120秒)
### 1.2 记录前检查
在记录预约之前,会进行以下检查:
1. **观看任务检查**:
- 检查是否是"观看X分钟"类任务
- 如果是观看任务,不记录预约,直接关闭详情页并切换直播间
2. **黑名单检查**:
- 检查福袋内容是否命中黑名单
- 如果命中黑名单,不记录预约,直接关闭详情页并切换直播间
### 1.3 预约去重策略
`add_reservation_core_logic` 函数会检查是否已存在相同预约:
**去重判断条件(满足任一条件即视为重复):**
1. **完全匹配**:`(future_ts, content)` 相同,且直播间名字相同(规范化后)
2. **兼容匹配**:`(future_ts, content)` 相同(兼容旧数据,没有直播间名字的情况)
3. **相似度匹配**(处理OCR误差):
- 直播间名称相似(相似度 >= 0.6 或互为子串)
- 开奖时间相近(相差5秒内)
- 奖品价值相同(允许0.01的误差)
- 内容核心部分相似(相似度 >= 0.7)
**处理方式:**
- 如果检测到重复预约:
- 新价值 > 旧价值:更新为更高价值的记录
- 新价值 <= 旧价值:保留旧记录,丢弃新记录
### 1.4 预约排序规则
预约队列按以下规则排序(`_sort_reservations_inplace`):
1. **主排序键**:`future_ts`(预计开奖时间戳)升序 - 越早开奖越优先
2. **次排序键**:`prize_value_yuan`(奖品价值)降序 - 价值越高越优先
3. **第三排序键**:`created_ts`(创建时间)升序 - 创建越早越优先
### 1.5 队列裁剪
- **队列上限**:`high_value_fudai_max_reservations`(默认3个)
- **裁剪规则**:如果队列超过上限,按排序规则裁剪掉优先级最低的记录
- **裁剪日志**:记录被丢弃的预约详情(价值、开奖时间、内容等)
---
## 二、预约回退流程
### 2.1 主循环检查
在主循环 `run_once_basic` 中,每次都会检查预约队列:
1. **队列满检查**(优先处理):
- 如果队列已满(`len(reservations) >= max_reservations`)
- 且未在等待状态(`queue_full_waiting_at_earliest = False`)
- 调用 `handle_queue_full_wait_at_earliest` 回退到最早开奖的预约直播间
2. **队列满等待状态检查**:
- 如果已在等待状态(`queue_full_waiting_at_earliest = True`)
- 且设置了直接参与标志(`_reservation_back_direct_attend = True`)
- 跳过预约回退检查,直接进入阶段诊断
3. **预约回退窗口检查**:
- 如果队列未满,调用 `process_reservation_attend_window` 检查是否需要回退
### 2.2 队列满处理流程(`handle_queue_full_wait_at_earliest`)
**触发条件:**
- 队列长度 >= `high_value_fudai_max_reservations`
- 未在等待状态
**处理步骤:**
1. **排序队列**:确保取到最早开奖的预约
2. **检查锁定期**:如果已在锁定期内,跳过回退
3. **阶段诊断**:回退前先进行阶段诊断,处理弹窗等异常状态
4. **回退到最早直播间**:
- 计算位置差(`current_room_pos - target_pos`)
- 如果不在目标位置,先下滑一次确保在直播列表中
- 调用 `seek_reservation_room_callback` 回退到目标直播间
5. **设置立即参与标志**:
- 设置 `_reservation_back_direct_attend = True`
- 设置锁定期为当前时间(`focus_until = now_ts`),表示立即参与
6. **等待页面加载**:延迟1.5秒等待页面加载完成
**特点:**
- 队列满后立即参与,不等待开奖窗口
- 锁定期设置为当前时间,不阻塞后续流程
### 2.3 预约回退窗口处理流程(`process_reservation_attend_window`)
**触发条件:**
- 队列未满,或已在等待状态但需要检查时间窗口
- 多间模式(`needswitch = True`)
**处理步骤:**
#### 步骤1:获取目标预约
- 排序队列,取队头(最早需要处理的预约)
- 检查 `future_ts` 是否有效,无效则丢弃
#### 步骤2:计算时间窗口
- **基础提前量**:`high_value_fudai_join_ahead_seconds`(默认120秒)
- **动态提前量计算**:
```
dynamic_ahead = max(
基础提前量,
回退步数 * 回退延迟 + 18秒缓冲
)
```
- 回退步数 = `current_room_pos - target_pos`
- 回退延迟 = `reservation_back_swipe_delay_s`(默认0.6秒)
- **时间窗口**:
- 开始时间:`future_ts - dynamic_ahead`
- 结束时间:`future_ts + poll_before_open_seconds`(默认10秒)
#### 步骤3:锁定期检查
- **无锁定期**(`focus_until = 0`):直接允许检查时间窗口
- **锁定期已过期**(`now_ts >= focus_until`):允许检查时间窗口
- **锁定期未结束**:
- 检查是否是同一个预约(允许5秒误差)
- 如果是同一个预约,且已在目标位置,检查时间窗口是否到达
- 如果不是同一个预约,不允许回退(需要等待当前预约完成)
- **队列满立即参与**(`focus_until == now_ts`):跳过时间窗口检查,直接参与
#### 步骤4:时间窗口检查
- **未到时间窗口**(`now_ts < future_ts - dynamic_ahead`):
- 跳过回退,记录剩余秒数
- **已过时间窗口**(`now_ts > future_ts + poll_before`):
- 清理过期预约,跳过回退
- **在时间窗口内**(`future_ts - dynamic_ahead <= now_ts <= future_ts + poll_before`):
- 执行回退操作
#### 步骤5:执行回退
1. **计算位置差**:`pos_diff = current_room_pos - target_pos`
2. **位置调整**:
- 如果不在目标位置(`pos_diff != 0`),先下滑一次确保在直播列表中
3. **回退到目标直播间**:
- 调用 `seek_reservation_room_callback` 回退到目标直播间
- 通过直播间标题匹配找到目标直播间
4. **设置锁定期**:
- `focus_until = future_ts + poll_before_open_seconds`
- 在锁定期内不再切换直播间
5. **设置待处理标志**:
- `reservation_after_action_pending = True`
- 表示预约回退后需要处理
---
## 三、预约参与流程
### 3.1 预约回退后的参与
**场景1:队列满后立即参与**
- 设置 `_reservation_back_direct_attend = True`
- 锁定期设置为当前时间(立即参与)
- 在阶段诊断后检查直接参与标志
**场景2:时间窗口内回退**
- 回退到目标直播间后,设置锁定期和待处理标志
- 下一轮主循环中,阶段诊断检测到直播间或福袋详情页
- 检查直接参与标志,如果设置了则直接参与
### 3.2 直接参与标志处理
**在福袋详情页(`stage == "FUDai_DETAIL"`):**
1. 检查 `_reservation_back_direct_attend` 标志
2. 如果为 `True`:
- 清除直接参与标志
- 设置强制参与标志(`_force_attend_after_reservation_back = True`)
- 调用 `_handle_reservation_direct_attend()` 处理
**在直播间(`stage == "IN_LIVE_ROOM"`):**
1. 检查 `_reservation_back_direct_attend` 标志
2. 如果为 `True`:
- 清除直接参与标志
- 设置强制参与标志
- 查找福袋并打开详情页
- 然后直接参与
### 3.3 强制参与标志处理
在 `basic_join_decision` 中:
- 如果检测到 `_force_attend_after_reservation_back = True`:
- 跳过数据验证
- 跳过倒计时检查
- 直接进入参与逻辑
- 参与后清除强制参与标志
---
## 四、预约队列管理
### 4.1 队列清理
- **自动清理**:每次调用 `process_reservation_attend_window` 时,如果预约已过期,会自动清理
- **清理条件**:`future_ts <= now_ts`(已过开奖时间)
- **清理日志**:记录被清理的预约详情
### 4.2 状态文件
- **文件路径**:`state/reservations.json`
- **写入时机**:
- 添加预约时
- 队列裁剪时
- 预约回退时
- 清理过期预约时
- **文件内容**:
- 预约队列数据
- 当前直播间信息
- 更新时间戳
### 4.3 预约完成处理
- **所有预约完成**:如果 `queue_full_waiting_at_earliest = True` 且 `reservations` 为空
- **处理方式**:
- 重置到第一个直播间(回退 `room_pos` 次)
- 清除等待标志
- 清除锁定期
---
## 五、关键配置参数
### 5.1 预约相关配置
- `high_value_fudai_enabled`:是否启用高价值预约(默认:根据配置)
- `high_value_fudai_threshold_yuan`:高价值阈值(元)
- `high_value_fudai_max_reservations`:最大预约数量(默认:3)
- `high_value_fudai_join_ahead_seconds`:预约参与阈值(默认:120秒)
- `poll_before_open_seconds`:开奖前轮询时间(默认:10秒)
- `high_value_fudai_max_swipe_back`:最大回退次数(默认:60)
### 5.2 时间窗口计算
- **基础提前量**:`high_value_fudai_join_ahead_seconds`(默认120秒)
- **动态提前量**:`max(基础提前量, 回退步数 * 0.6 + 18)`
- **时间窗口开始**:`future_ts - dynamic_ahead`
- **时间窗口结束**:`future_ts + poll_before_open_seconds`
---
## 六、完整流程示例
### 示例1:正常预约流程
```
1. 识别到高价值福袋(价值100元,倒计时300秒)
↓
2. 检查:价值 >= 阈值 ✓
↓
3. 检查:剩余秒数 > 120秒 ✓
↓
4. 检查:不是观看任务 ✓
↓
5. 检查:未命中黑名单 ✓
↓
6. 检查:队列未满 ✓
↓
7. 添加到预约队列
↓
8. 排序队列(按开奖时间、价值、创建时间)
↓
9. 写入状态文件
↓
10. 继续寻找其他福袋
↓
11. 当时间窗口到达(开奖前120秒)
↓
12. 回退到目标直播间
↓
13. 设置锁定期(直到开奖后10秒)
↓
14. 识别福袋详情并参与
↓
15. 参与成功后,等待开奖
↓
16. 开奖后处理结果
```
### 示例2:队列满流程
```
1. 识别到高价值福袋
↓
2. 添加到预约队列
↓
3. 队列已满(>= 3个)
↓
4. 立即回退到最早开奖的预约直播间
↓
5. 设置直接参与标志(_reservation_back_direct_attend = True)
↓
6. 设置锁定期为当前时间(立即参与)
↓
7. 下一轮主循环:检测到直播间
↓
8. 检查直接参与标志:为 True
↓
9. 查找福袋并打开详情页
↓
10. 设置强制参与标志
↓
11. 直接参与(跳过倒计时检查)
↓
12. 参与成功后,等待开奖
```
### 示例3:预约去重流程
```
1. 识别到高价值福袋A(价值100元,开奖时间T1)
↓
2. 添加到预约队列
↓
3. 再次识别到相同福袋A(价值100元,开奖时间T1)
↓
4. 检查去重条件:
- future_ts 相同 ✓
- content 相同 ✓
- 直播间名字相同 ✓
↓
5. 判断为重复预约
↓
6. 新价值 <= 旧价值:保留旧记录,丢弃新记录
```
---
## 七、日志输出说明
### 7.1 预约记录日志
- `[预约] add_reservation_core_logic 函数入口`:记录预约信息
- `[预约] 添加新预约到队列`:新预约添加
- `[预约] 检测到重复预约,更新为更高价值`:重复预约更新
- `[预约] 预约队列已满,丢弃最低优先级记录`:队列裁剪
### 7.2 预约回退日志
- `[预约] process_reservation_attend_window 函数入口`:回退检查开始
- `[预约] process_reservation_attend_window 详细检查`:时间窗口和锁定期检查
- `[预约] 时间窗口未到,跳过回退`:未到时间窗口
- `[预约] 进入预约参与窗口,准备回退到目标直播间`:开始回退
- `[预约] 已回退到目标直播间,等待详情识别与参与`:回退成功
### 7.3 队列满处理日志
- `[预约] handle_queue_full_wait_at_earliest 函数入口`:队列满处理开始
- `[预约] 队列已满,回退到最早开奖的预约直播间等待`:开始回退
- `[预约] 队列满回退后,直接设置参与标志(立即参与,不等待开奖窗口)`:设置立即参与
- `[预约] 已回退到最早开奖的预约直播间,立即参与(不等待开奖窗口)`:回退成功
---
## 八、注意事项
1. **单间模式**:如果 `needswitch = False`,不启用预约回退逻辑,预约会在当前直播间自动识别和参与
2. **锁定期机制**:回退到预约直播间后,会设置锁定期,在锁定期内不再切换直播间,避免错过开奖
3. **时间窗口**:动态提前量会根据回退步数自动调整,确保有足够时间回退到目标直播间
4. **队列满处理**:队列满后立即回退到最早开奖的预约直播间,不等待开奖窗口,立即参与
5. **预约去重**:使用多种策略判断重复预约,包括完全匹配和相似度匹配,处理OCR误差
6. **状态持久化**:预约队列会写入状态文件,程序重启后可以恢复预约队列