fix: speed up fansclub reservation prejoin

This commit is contained in:
Your Name committed 2026-06-23 10:43:17 +08:00
1 parent 0efdc83d0b
commit a449b7634c
15 files changed
+312 -31

No files matched your search

+31 -20
View File
@@ -11,6 +11,10 @@ from datetime import datetime
from typing import Any
from douyin.core import path_config
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
decide_button_status,
is_button_text_non_actionable,
)
from .coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK
@@ -102,26 +106,7 @@ def attend_choujiang(analyser) -> bool:
if candidate:
bt = str(candidate or "").strip()
if bt:
# 推断按钮状态(与并行OCR的判断逻辑保持一致)
if (
"参与成功" in bt
or "等待开奖" in bt
or "失去抽奖" in bt
or "否则会失去" in bt
):
bs = "已参与"
elif "加入粉丝团" in bt or "粉丝团" in bt:
bs = "需要加入粉丝团"
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
bs = "需要评论"
elif "还需看播" in bt or "开始观看" in bt:
bs = "需要观看"
elif "未达成" in bt:
bs = "未达成要求"
elif "参与抽奖" in bt or "参与" in bt:
bs = "可以参与"
else:
bs = "未知状态"
bs = decide_button_status(bt)
try:
analyser._fudai_button_status = bs
@@ -234,6 +219,32 @@ def attend_choujiang(analyser) -> bool:
return False
# 基于并行OCR结果进行决策
if attend_button_text and is_button_text_non_actionable(attend_button_text):
analyser.last_attend_fail_reason = "button_not_actionable"
analyser._log_kv(
"参与",
"按钮文案不可参与,直接放弃",
result="不参与",
reason="button_not_actionable",
button_text=attend_button_text[:120],
button_status=str(button_status or ""),
decision="close_detail_without_attend",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="button_not_actionable",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
if attend_button_text and "不满足参与条件" in attend_button_text:
analyser.last_attend_fail_reason = "condition_not_met"
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
@@ -2,9 +2,9 @@
from __future__ import annotations
from typing import Any
from .fansclub_handler_impl import handle_fansclub_branch
__all__ = ["handle_fansclub_branch"]
from .fansclub_handler_impl import (
handle_fansclub_branch,
handle_reservation_prejoin_fansclub,
)
__all__ = ["handle_fansclub_branch", "handle_reservation_prejoin_fansclub"]
@@ -2,10 +2,9 @@
from __future__ import annotations
import os
import time
from typing import Any
from douyin.core import path_config
from douyin.fudai.core.coords import (
DETAIL_OUTSIDE_CLICK,
PARTICIPATE_BTN_CLICK,
@@ -21,3 +20,124 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
return _legacy_impl(analyser, attend_button_text)
def _scaled_point(analyser: Any, point: tuple[int, int]) -> tuple[int, int]:
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
return int(point[0] * rx // 1080), int(point[1] * ry // 2400)
def _fast_delay(analyser: Any, attr_name: str, default_seconds: float) -> None:
try:
seconds = float(getattr(analyser, attr_name, default_seconds) or default_seconds)
except Exception:
seconds = default_seconds
seconds = max(0.0, min(seconds, 1.2))
try:
analyser.operation.delay(seconds)
except Exception:
time.sleep(seconds)
def handle_reservation_prejoin_fansclub(
analyser: Any, attend_button_text: str
) -> bool:
"""预约记录前的粉丝团快路径:固定坐标点击,不做OCR和详情恢复。"""
start_ts = time.time()
try:
analyser.last_attend_fail_reason = "fansclub_required"
except Exception:
pass
try:
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:先点击参与按钮",
button_text=str(attend_button_text or "")[:80],
base_x=PARTICIPATE_BTN_CLICK[0],
base_y=PARTICIPATE_BTN_CLICK[1],
)
except Exception as exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击参与按钮失败",
error=str(exc),
error_type=type(exc).__name__,
level="WARNING",
)
except Exception:
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_participate_wait_seconds", 0.6)
click_point = FANSCLUB_JOIN_CLICK
click_x, click_y = _scaled_point(analyser, click_point)
try:
analyser.operation.click(analyser.device_id, click_x, click_y)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击加入粉丝团固定坐标",
x=click_x,
y=click_y,
base_x=click_point[0],
base_y=click_point[1],
strategy="fixed_coord_no_ocr",
)
except Exception as exc:
fallback_point = FANSCLUB_JOIN_FALLBACK_CLICK
fallback_x, fallback_y = _scaled_point(analyser, fallback_point)
try:
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:固定坐标失败后使用备用坐标",
x=fallback_x,
y=fallback_y,
base_x=fallback_point[0],
base_y=fallback_point[1],
first_error=str(exc),
level="WARNING",
)
except Exception as fallback_exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击加入粉丝团失败",
error=str(fallback_exc),
error_type=type(fallback_exc).__name__,
first_error=str(exc),
level="WARNING",
)
except Exception:
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_confirm_wait_seconds", 0.8)
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:关闭详情并跳过详情恢复",
action="close_detail_after_fast_prejoin",
elapsed_seconds=round(time.time() - start_ts, 2),
)
except Exception as exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:关闭详情失败",
error=str(exc),
error_type=type(exc).__name__,
elapsed_seconds=round(time.time() - start_ts, 2),
level="WARNING",
)
except Exception:
pass
return True
@@ -141,10 +141,10 @@ def _prejoin_fansclub_before_reservation(
try:
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
handle_fansclub_branch,
handle_reservation_prejoin_fansclub,
)
ok = bool(handle_fansclub_branch(analyser, text))
ok = bool(handle_reservation_prejoin_fansclub(analyser, text))
try:
setattr(analyser, "_reservation_prejoined_fansclub", ok)
setattr(analyser, "_reservation_prejoin_fansclub_button_text", text)
@@ -14,6 +14,10 @@ import re
import time
from typing import Any, Tuple
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS,
)
from .helpers import (
_is_short_countdown_text,
check_contain,
@@ -463,6 +467,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
if button_text:
# 检查是否包含无法参与的关键词
unable_to_participate_keywords = [
*NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS,
"无法参与",
"不能参与",
"不可参与",
@@ -6,8 +6,33 @@ import time
from typing import Any
NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
"抽奖剩余时间不足",
"剩余时间不足",
"下次再来参与",
"下次再来",
"还没到时间",
"无法参与",
"不能参与",
"不可参与",
"活动已结束",
"活动结束",
"已结束",
"已过期",
"已截止",
"时长不足",
)
def is_button_text_non_actionable(button_text: str) -> bool:
txt = str(button_text or "").strip()
return bool(txt and any(snippet in txt for snippet in NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS))
def decide_button_status(button_text: str) -> str:
txt = str(button_text or "").strip()
if is_button_text_non_actionable(txt):
return "不可参与"
# 新版按钮文案:“直播间,否则会失去抽奖机会” 实际语义等价于已参与后等待开奖。
if "失去抽奖" in txt or "否则会失去" in txt:
return "已参与"
@@ -14,6 +14,9 @@ from typing import Any, Dict, Optional
from douyin.core import path_config
from douyin.fudai import douyin_fudai_detail
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
is_button_text_non_actionable,
)
from douyin.handlers import douyin_swipe_handler
from douyin.reservation import douyin_reservation_logic
@@ -297,6 +300,8 @@ def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, An
or getattr(analyser, "button_status", "")
or ""
)
if is_button_text_non_actionable(button_text):
return False, button_text, button_status
if button_status in _DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES:
return True, button_text, button_status
if button_text and any(snippet in button_text for snippet in _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS):
+9
View File
@@ -246,6 +246,15 @@ class ConfigManager:
else:
analyser.fansclub_manual_wait_seconds = 3.0
analyser.reservation_prejoin_fansclub_participate_wait_seconds = float(
config.get("reservation_prejoin_fansclub_participate_wait_seconds", 0.6)
or 0.6
)
analyser.reservation_prejoin_fansclub_confirm_wait_seconds = float(
config.get("reservation_prejoin_fansclub_confirm_wait_seconds", 0.8)
or 0.8
)
# 其他配置项(根据实际需要添加)
if "no_attend_timeout_minutes" in config:
analyser._no_attend_timeout_minutes = float(
+19
View File
@@ -289,6 +289,25 @@ class TestFudaiDetectionDefaults:
assert analyser.reservation_direct_attend_max_failures == 3
assert analyser.reservation_direct_attend_open_max_wait_seconds == 2.25
def test_config_loader_loads_reservation_prejoin_fansclub_delays(self):
from douyin.utils.douyin_config import ConfigManager
analyser = SimpleNamespace()
config = {
"reservation_prejoin_fansclub_participate_wait_seconds": 0.25,
"reservation_prejoin_fansclub_confirm_wait_seconds": 0.35,
}
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump(config, f)
tmp_path = f.name
try:
ConfigManager.load_config_from_file(analyser, tmp_path)
finally:
os.unlink(tmp_path)
assert analyser.reservation_prejoin_fansclub_participate_wait_seconds == 0.25
assert analyser.reservation_prejoin_fansclub_confirm_wait_seconds == 0.35
class TestCoreModules:
"""core 子模块存在性测试。"""
+29
View File
@@ -15,6 +15,7 @@ import pytest
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
handle_fansclub_branch,
handle_reservation_prejoin_fansclub,
)
@@ -113,3 +114,31 @@ class TestHandleFansclubBranch:
a = _mk_analyser(auto_join_fansclub=True)
result = handle_fansclub_branch(a, "加入粉丝团")
assert result is True
class TestReservationPrejoinFansclub:
def test_fast_prejoin_uses_fixed_clicks_without_ocr_or_recovery(self):
a = _mk_analyser(auto_join_fansclub=True)
result = handle_reservation_prejoin_fansclub(a, "加入直播粉丝团并关注主播")
assert result is True
assert a.last_attend_fail_reason == "fansclub_required"
assert any(c.args == (543, 2070) for c in a.click.call_args_list)
assert any(c.args == (500, 470) for c in a.click.call_args_list)
assert any(c.args == ("MOCK", 540, 2006) for c in a.operation.click.call_args_list)
a.cut_pic.assert_not_called()
a.operation.analyse_pic_word.assert_not_called()
a._shot_and_diagnose.assert_not_called()
log_msgs = [str(c) for c in a._log_kv.call_args_list]
assert any("快速预处理" in m for m in log_msgs)
def test_fast_prejoin_uses_short_configured_delays(self):
a = _mk_analyser(auto_join_fansclub=True)
a.reservation_prejoin_fansclub_participate_wait_seconds = 0.2
a.reservation_prejoin_fansclub_confirm_wait_seconds = 0.3
handle_reservation_prejoin_fansclub(a, "加入购物粉丝团并关注主播")
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
assert delay_args == [0.2, 0.3]
+26
View File
@@ -57,6 +57,32 @@ def test_attend_choujiang_treat_notice_text_as_attended() -> None:
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
def test_attend_choujiang_blocks_insufficient_time_text_even_if_status_actionable() -> None:
analyser = MagicMock()
analyser._fudai_button_status = "可以参与"
analyser._fudai_button_text = "抽奖剩余时间不足,下次再来参与吧"
analyser._fudai_button_ocr_time = 25_000.0
analyser._fudai_button_room_pos = 0
analyser.room_pos = 0
analyser.click = MagicMock()
analyser._log_kv = MagicMock()
analyser.operation = MagicMock()
analyser.operation.delay = MagicMock()
import time as _time
old_time = _time.time
_time.time = lambda: 25_001.0
try:
ok = attend_choujiang(analyser)
finally:
_time.time = old_time
assert ok is False
assert analyser.last_attend_fail_reason == "button_not_actionable"
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
def test_attend_choujiang_does_not_reuse_fresh_button_cache_from_other_room() -> None:
analyser = MagicMock()
analyser._fudai_button_status = "可以参与"
+4
View File
@@ -12,6 +12,10 @@ def test_decide_button_status_attended_for_notice_text() -> None:
assert decide_button_status("直播间,否则会失去抽奖机会") == "已参与"
def test_decide_button_status_blocks_insufficient_time_text() -> None:
assert decide_button_status("抽奖剩余时间不足,下次再来参与吧") == "不可参与"
def test_apply_button_ocr_result_records_room_pos_when_enabled() -> None:
log_calls = []
analyser = SimpleNamespace(room_pos=12)
+9
View File
@@ -147,6 +147,15 @@ class TestShouldSkipFudaiByConfig:
assert isinstance(skip, bool)
assert isinstance(reason, str)
def test_insufficient_time_button_skips(self):
analyser = self._mock()
analyser.button_text_raw = "抽奖剩余时间不足,下次再来参与吧"
detail = ('现金1000元', '00:28', 50, 1, 1000.0,
(time.time()+28, time.time()+28))
skip, reason = should_skip_fudai_by_config(analyser, detail)
assert skip is True
assert "button_unable_to_participate" in reason
# ============================================================
# join_decision.py — basic_join_decision
+2 -2
View File
@@ -73,7 +73,7 @@ def test_high_value_reservation_prejoins_fansclub_before_recording():
"douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config",
return_value=(True, "countdown_gt_118"),
), patch(
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_fansclub_branch",
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_reservation_prejoin_fansclub",
side_effect=_fake_prejoin,
) as mock_prejoin, patch(
"douyin.reservation.reservation_logic.record.record_high_value_reservation",
@@ -111,7 +111,7 @@ def test_high_value_reservation_prejoins_live_fansclub_variant():
"douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config",
return_value=(True, "countdown_gt_118"),
), patch(
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_fansclub_branch",
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_reservation_prejoin_fansclub",
return_value=True,
) as mock_prejoin, patch(
"douyin.reservation.reservation_logic.record.record_high_value_reservation",
@@ -33,6 +33,25 @@ def _has_log_reason(analyser, reason: str) -> bool:
return False
def test_reservation_button_fallback_blocks_insufficient_time_text():
from douyin.reservation.douyin_reservation_handler_pkg import direct_attend
analyser = _mk_analyser()
item = {
"button_text": "抽奖剩余时间不足,下次再来参与吧",
"button_status": "可以参与",
}
ok, button_text, button_status = direct_attend._reservation_button_fallback_is_actionable(
analyser,
item,
)
assert ok is False
assert button_text == "抽奖剩余时间不足,下次再来参与吧"
assert button_status == "可以参与"
def test_direct_attend_logs_fixed_success_marker():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,