Files
douyin_guaji-main/douyin/other/douyin_yanghao.py
T
CodexandClaude Opus 4.7 49704834d8 douyin_yanghao: print → _yanghao_log + 修 3 处 f-string bug
- 新增模块级 _yanghao_log(analyser, msg, level):优先走 analyser._log_kv,
  退化到模块 logger,最后兜底 stdout,避免日志静默丢失
- 全部 58 处裸 print 改为 _yanghao_log 调用
- 修 3 处 f-string 缺前缀 bug({prob} 之前是字面量而非插值):
  L440 跳过点爱心、L466 跳过点收藏、L498 跳过评论的概率显示

回归:全量 149 .py compileall 通过;douyin_yanghao 4 条 helper 路径
(_log_kv / broken _log_kv / 无 _log_kv 兜底 / 4 个 yanghao_* 顶级函数)
全部 PASS;test_filter_logging / check_web_gui_config_sync 通过。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 09:37:46 +08:00

923 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import os
import random
import time
from typing import Any
import cv2 as _cv2
cv2: Any = _cv2
# pylint: disable=E1101
import numpy as np
# 模块级日志:优先走 analyser._log_kv,回退到 logging(避免裸 print 散落到 stdout)
import logging as _logging
_LOGGER = _logging.getLogger("douyin.other.douyin_yanghao")
def _yanghao_log(analyser, msg: str, level: str = "INFO") -> None:
"""统一养号日志出口。
- 当 analyser 提供 `_log_kv` 时,优先用它(与项目统一日志体系一致)。
- 否则回退到模块 logger;最后兜底到 stdout 以避免静默丢日志。
"""
try:
log_kv = getattr(analyser, "_log_kv", None)
if callable(log_kv):
log_kv("养号", str(msg), level=str(level or "INFO"))
return
except Exception:
pass
try:
if str(level).upper() == "ERROR":
_LOGGER.error(str(msg))
elif str(level).upper() == "WARNING":
_LOGGER.warning(str(msg))
else:
_LOGGER.info(str(msg))
except Exception:
try:
_yanghao_log(analyser, str(msg))
except Exception:
pass
def _scaled_click(analyser, base_x: int, base_y: int) -> None:
"""模块级点击封装:根据基准坐标缩放并点击(兼容原嵌套实现)。"""
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
# 使用底层 click 时不打印底层日志,以避免养号动作产生多余的聚焦/日志噪音
try:
analyser.operation.click(analyser.device_id, sx, sy, log=False)
except TypeError:
# 向后兼容:如果底层 click 还没有 log 参数,回退到旧调用
analyser.operation.click(analyser.device_id, sx, sy)
def _do_comment(analyser) -> None:
"""模块级评论操作:点击评论按钮 -> 输入框 -> 输入文本 -> 发送 -> 关闭"""
try:
# 步骤1: 点击评论按钮
btn_x = int(getattr(analyser, "yanghao_comment_btn_x", 540) or 540)
btn_y = int(getattr(analyser, "yanghao_comment_btn_y", 2000) or 2000)
_yanghao_log(analyser, f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})")
_scaled_click(analyser, btn_x, btn_y)
analyser.operation.delay(1.0)
# 步骤2: 点击输入框
input_x = int(getattr(analyser, "yanghao_comment_input_x", 144) or 144)
input_y = int(getattr(analyser, "yanghao_comment_input_y", 2179) or 2179)
_yanghao_log(analyser, f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})")
_scaled_click(analyser, input_x, input_y)
analyser.operation.delay(1.0)
# 步骤3: 输入评论文本
comment_texts = getattr(analyser, "yanghao_comment_texts", []) or []
if not comment_texts:
comment_texts = ["加油", "不错", "很好看"]
selected_text = random.choice(comment_texts)
_yanghao_log(analyser, f"[养号][评论] Step3: 选择文本 -> {selected_text}")
ix, iy = analyser._scale_from_base(input_x, input_y)
ok_input = bool(
analyser.operation.paste_text_at(
analyser.device_id, ix, iy, selected_text, ensure_focus=False
)
)
_yanghao_log(analyser, f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})")
analyser.operation.delay(1.0)
# 步骤4: 发送评论
ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id))
_yanghao_log(analyser, f"[养号][评论] Step4: 发送评论 -> ok={ok_send}")
analyser.operation.delay(1.0)
# 步骤5: 关闭评论窗口
close_x = int(getattr(analyser, "yanghao_comment_close_x", 900) or 900)
close_y = int(getattr(analyser, "yanghao_comment_close_y", 300) or 300)
_yanghao_log(analyser, f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})")
_scaled_click(analyser, close_x, close_y)
analyser.operation.delay(1.0)
except Exception as e:
_yanghao_log(analyser, f"[养号] 评论操作失败: {e}")
def yanghao_idle(analyser, total_seconds: int) -> None:
"""养号等待。
- 若启用 `yanghao_enable_actions`:停留期间可按概率点爱心/收藏,停留结束后自动滑动。
- 否则:保持原有“分段等待 + 可选轻微滑动 + 定时休息”。
"""
if total_seconds <= 0:
return
if getattr(analyser, "yanghao_enable_actions", False):
# 切换直播间后1秒截图,检测like/fav图标,按概率点击,然后继续下一个直播间
def _step_shot(label: str) -> None:
"""只截图不识别模板的调试函数"""
try:
env_on = bool(
str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip()
)
except Exception:
env_on = False
if env_on or bool(getattr(analyser, "yanghao_step_screenshot", False)):
analyser._save_step_screenshot(label)
def _do_swipe_next() -> None:
"""执行滑动切换到下一个直播间的操作"""
dist = int(
getattr(analyser, "yanghao_after_dwell_swipe_distance_px", 900) or 900
)
if dist < 200:
dist = 200
if dist > 1400:
dist = 1400
x = int(1080 * 0.7)
y_mid = int(2400 * 0.55)
if (
str(
getattr(analyser, "yanghao_after_dwell_swipe_direction", "up")
or "up"
).lower()
== "up"
):
# up:上滑切换到下一个内容(手指从下往上)
y1 = y_mid + int(dist / 2)
y2 = y_mid - int(dist / 2)
else:
# down:下滑回到上一个内容(手指从上往下)
y1 = y_mid - int(dist / 2)
y2 = y_mid + int(dist / 2)
analyser.swipe(x, y1, x, y2, 180)
_yanghao_log(analyser,
"[养号] 动作: 下滑/切换 direction={} dist={}px".format(
getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist
)
)
def _human_delay(min_s: float = 0.4, max_s: float = 1.2) -> None:
try:
mn = float(min_s)
mx = float(max_s)
if mx < mn:
mx = mn
analyser.operation.delay(random.uniform(mn, mx))
except Exception:
analyser.operation.delay(1)
def _detect_icon(
action: str,
base_x: int,
base_y: int,
template_path: str,
roi_label: str,
shared_screenshot_path: str = None,
) -> tuple[bool, float]:
"""模板匹配检测爱心/收藏图标,只在full screenshot上做一次匹配"""
# 检查模板文件是否存在
tpl = str(template_path or "").strip()
tpl_exists = False
try:
# 直接存在
if tpl and os.path.exists(tpl):
tpl_exists = True
else:
# 尝试相对于 config 路径的仓库根解析
try:
cfg = (
getattr(analyser, "config_path", "config/config.json")
or "config/config.json"
)
cfg_abspath = os.path.abspath(cfg)
project_root = os.path.dirname(os.path.dirname(cfg_abspath))
candidate = os.path.join(project_root, tpl)
if tpl and os.path.exists(candidate):
tpl_exists = True
template_path = candidate
except Exception:
pass
except Exception:
tpl_exists = False
_yanghao_log(analyser,
f"[养号] 检测: {action} -> 模板文件={template_path} tpl_exists={tpl_exists}"
)
# 真实的模板匹配检测,直接在full screenshot上进行
try:
if not tpl_exists or not os.path.exists(str(template_path or "")):
_yanghao_log(analyser, f"[养号] {action}: 模板文件不存在,假设图标存在")
return True, 1.0
# 使用共享的full screenshot,不做ROI截图
if not shared_screenshot_path or not os.path.exists(
shared_screenshot_path
):
_yanghao_log(analyser, f"[养号] {action}: 截图文件不存在,假设图标存在")
return True, 1.0
# 读取full screenshot
pic = cv2.imread(shared_screenshot_path)
if pic is None:
_yanghao_log(analyser, f"[养号] {action}: 读取截图失败,假设图标存在")
return True, 1.0
# 读取模板
template = cv2.imread(str(template_path))
if template is None:
_yanghao_log(analyser, f"[养号] {action}: 读取模板失败,假设图标存在")
return True, 1.0
# 灰度化处理
pic_gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# 使用标准化相关系数进行模板匹配
result = cv2.matchTemplate(
pic_gray, template_gray, cv2.TM_CCOEFF_NORMED
)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 获取匹配阈值
threshold = float(
getattr(analyser, "yanghao_icon_match_threshold", 0.6) or 0.6
)
if max_val >= threshold:
_yanghao_log(analyser, f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})")
return True, float(max_val)
else:
_yanghao_log(analyser,
f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})"
)
return False, float(max_val)
except Exception as e:
_yanghao_log(analyser, f"[养号] {action}: 模板匹配异常 {e},假设图标存在")
return True, 1.0
end_ts = time.time() + int(max(1, total_seconds))
_yanghao_log(analyser, f"[养号] 开始养号模式,总时长 {total_seconds}s")
# 连续未检测到任何模板时的自救阈值(超过此次数尝试按返回键一次)
consecutive_miss = 0
miss_recover_threshold = int(
getattr(analyser, "yanghao_miss_recover_threshold", 6) or 6
)
# 周期性桌面检测(若返回桌面则尝试自救恢复到直播间)
last_desktop_check_ts = 0.0
desktop_check_interval = float(
getattr(analyser, "yanghao_desktop_check_interval", 5.0) or 5.0
)
while time.time() < end_ts:
try:
# 切换到下一个直播间
_do_swipe_next()
# 切换后等待1秒让界面稳定
analyser.operation.delay(1.0)
# 截图一次
try:
analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
from douyin.core import path_config
screenshot_path = path_config.get_screenshot_path()
except Exception:
screenshot_path = None
continue
# 用同一个截图检测like和fav
like_ok, _like_score = _detect_icon(
"爱心",
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_like_icon_y", 0) or 0),
getattr(analyser, "yanghao_like_template_path", "") or "",
"action_like_roi",
screenshot_path,
)
fav_ok, _fav_score = _detect_icon(
"收藏",
int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0),
getattr(analyser, "yanghao_fav_template_path", "") or "",
"action_fav_roi",
screenshot_path,
)
# 检查是否检测到爱心或收藏任意一个
action_detected = like_ok or fav_ok
# 自救:若连续多次未检测到任何模板,则尝试按一次返回键脱离卡死状态
try:
if not action_detected:
consecutive_miss += 1
_yanghao_log(analyser,
f"[养号] 连续未检测到模板次数={consecutive_miss}/{miss_recover_threshold}"
)
else:
consecutive_miss = 0
if consecutive_miss >= miss_recover_threshold:
_yanghao_log(analyser, "[养号] 连续多次未检测到模板,尝试按一次返回键进行自救")
try:
analyser.operation.keyevent(analyser.device_id, 4)
analyser.operation.delay(1.0)
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救按返回键失败: {e}")
consecutive_miss = 0
except Exception:
# 任何自救逻辑异常都不应影响主循环
consecutive_miss = 0
# 跟踪是否实际触发了 点爱心/点收藏 动作(只有在对应概率命中并执行点击时为 True)
# 同时周期性检测是否返回桌面并尝试恢复
did_like = False
did_fav = False
# 定时禁抢(仅在养号动作启用时生效):根据配置跳过爱心/收藏/评论
try:
if bool(getattr(analyser, "fudai_quiet_hours_enabled", False)):
start_h = int(
getattr(analyser, "fudai_quiet_start_hour", 0) or 0
)
end_h = int(getattr(analyser, "fudai_quiet_end_hour", 0) or 0)
now_h = time.localtime().tm_hour
in_quiet = False
if start_h <= end_h:
in_quiet = start_h <= now_h < end_h
else:
# 跨天区间,例如 23-6
in_quiet = now_h >= start_h or now_h < end_h
if in_quiet:
_yanghao_log(analyser,
f"[养号] 定时禁抢生效({start_h}:00-{end_h}:00),当前小时={now_h},跳过爱心/收藏/评论"
)
# 避免频繁循环,做一次随机短等待再继续
try:
_human_delay(2.0, 6.0)
except Exception:
analyser.operation.delay(3.0)
continue
except Exception:
# 配置读取异常不应影响主循环
pass
try:
now = time.time()
if now - last_desktop_check_ts >= desktop_check_interval:
last_desktop_check_ts = now
try:
top_pkg = (
analyser.operation.get_top_package(analyser.device_id)
or ""
)
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser,
f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}"
)
try:
desktop_x = int(
getattr(analyser, "desktop_icon_x", 153) or 153
)
desktop_y = int(
getattr(analyser, "desktop_icon_y", 260) or 260
)
analyser.operation.click(
analyser.device_id, desktop_x, desktop_y
)
analyser.operation.delay(2)
fallback_x = int(
getattr(
analyser, "yanghao_fallback_live_x", 540
)
or 540
)
fallback_y = int(
getattr(
analyser, "yanghao_fallback_live_y", 2000
)
or 2000
)
analyser.operation.click(
analyser.device_id, fallback_x, fallback_y
)
analyser.operation.delay(1.5)
enter_x = int(
getattr(
analyser,
"yanghao_fallback_enter_live_x",
540,
)
or 540
)
enter_y = int(
getattr(
analyser,
"yanghao_fallback_enter_live_y",
1200,
)
or 1200
)
analyser.operation.click(
analyser.device_id, enter_x, enter_y
)
analyser.operation.delay(0.6)
analyser.operation.click(
analyser.device_id, enter_x, enter_y
)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
except Exception:
pass
# 根据概率点击爱心
if (
like_ok
and float(getattr(analyser, "yanghao_like_prob", 0) or 0) > 0
and random.random()
< float(getattr(analyser, "yanghao_like_prob", 0) or 0)
):
_scaled_click(
analyser,
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_like_icon_y", 0) or 0),
)
did_like = True
analyser.operation.delay(1.0) # 延迟1秒
_yanghao_log(analyser,
"[养号] 动作: 点爱心(prob={})".format(
getattr(analyser, "yanghao_like_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_like_prob", 0)
if like_ok:
_yanghao_log(analyser, f"[养号] 动作: 跳过点爱心(prob={prob})")
else:
_yanghao_log(analyser, "[养号] 动作: 跳过点爱心(未检测到图标)")
# 根据概率点击收藏
if (
fav_ok
and float(getattr(analyser, "yanghao_fav_prob", 0) or 0) > 0
and random.random()
< float(getattr(analyser, "yanghao_fav_prob", 0) or 0)
):
_scaled_click(
analyser,
int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0),
int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0),
)
did_fav = True
analyser.operation.delay(1.0) # 延迟1秒
_yanghao_log(analyser,
"[养号] 动作: 点收藏(prob={})".format(
getattr(analyser, "yanghao_fav_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_fav_prob", 0)
if fav_ok:
_yanghao_log(analyser, f"[养号] 动作: 跳过点收藏(prob={prob})")
else:
_yanghao_log(analyser, "[养号] 动作: 跳过点收藏(未检测到图标)")
# 根据概率评论
# 仅在爱心和收藏都实际触发(都被点击)时才考虑评论
# 记录评论是否实际执行
did_comment = False
if (
did_like
and did_fav
and float(getattr(analyser, "yanghao_comment_prob", 0) or 0) > 0
and random.random()
< float(getattr(analyser, "yanghao_comment_prob", 0) or 0)
):
# 确保在评论前已完成爱心和收藏的点击效果,短暂等待保证顺序
try:
analyser.operation.delay(0.5)
except Exception:
pass
_do_comment(analyser)
did_comment = True
_yanghao_log(analyser,
"[养号] 动作: 评论(prob={})".format(
getattr(analyser, "yanghao_comment_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_comment_prob", 0)
if not (did_like and did_fav):
_yanghao_log(analyser, "[养号] 动作: 跳过评论(爱心/收藏未同时触发)")
else:
_yanghao_log(analyser, f"[养号] 动作: 跳过评论(prob={prob})")
# 只有在实际执行了任意动作(爱心/收藏/评论)时才停留;仅检测到图标但未执行任何动作则直接跳过
if did_like or did_fav or did_comment:
dwell_min = float(
getattr(analyser, "yanghao_dwell_on_action_min_seconds", 5) or 5
)
dwell_max = float(
getattr(analyser, "yanghao_dwell_on_action_max_seconds", 30)
or 30
)
dwell_time = random.uniform(dwell_min, dwell_max)
_yanghao_log(analyser, f"[养号] 检测到动作,停留 {dwell_time:.1f}s")
analyser.operation.delay(dwell_time)
else:
# 每次操作后随机等待,避免行为太机械
_human_delay(2.0, 6.0)
except Exception as e:
_yanghao_log(analyser, f"[养号] 循环异常: {e}")
analyser.operation.delay(1)
return
# 不启用动作时,采用原有"分段等待 + 桌面检测"逻辑
start_ts = time.time()
last_desktop_check_ts = 0.0
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""养号模式下的桌面检测和自救恢复(提前定义以供循环使用)。"""
try:
# 获取前台包名
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
# 检查是否在抖音前台
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
# 执行自救操作
try:
# 点击桌面图标
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
analyser.operation.click(analyser.device_id, desktop_x, desktop_y)
analyser.operation.delay(2)
# 点击直播按钮(备用坐标)
fallback_x = int(
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
)
fallback_y = int(
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
)
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
analyser.operation.delay(1.5)
# 点击进入直播间(备用坐标)
enter_x = int(
getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540
)
enter_y = int(
getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200
)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(0.6)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
return True
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
return False
else:
return False
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
return False
while True:
now = time.time()
elapsed = now - start_ts
if elapsed >= total_seconds:
return
# 定期检测是否在桌面(每5秒检测一次,避免过于频繁)
check_interval = 5.0
if now - last_desktop_check_ts >= check_interval:
last_desktop_check_ts = now
try:
# 桌面检测与恢复逻辑
if _yanghao_check_and_recover_from_desktop(analyser):
_yanghao_log(analyser, "[养号] 检测到不在抖音前台,已尝试恢复")
analyser.operation.delay(1)
except Exception as e:
_yanghao_log(analyser, f"[养号] 桌面检测异常: {e}")
# 分段等待(避免一次 sleep 太久,看起来更自然)
remaining = int(total_seconds - (time.time() - start_ts))
if remaining <= 0:
return
chunk = 10 if remaining > 10 else remaining
analyser.operation.delay(chunk)
def _do_swipe_next() -> None:
_step_shot("before_swipe")
dist = int(
getattr(analyser, "yanghao_after_dwell_swipe_distance_px", 900) or 900
)
if dist < 200:
dist = 200
if dist > 1400:
dist = 1400
x = int(1080 * 0.7)
y_mid = int(2400 * 0.55)
if (
str(
getattr(analyser, "yanghao_after_dwell_swipe_direction", "up")
or "up"
).lower()
== "up"
):
# up:上滑切换到下一个内容(手指从下往上)
y1 = y_mid + int(dist / 2)
y2 = y_mid - int(dist / 2)
else:
# down:下滑回到上一个内容(手指从上往下)
y1 = y_mid - int(dist / 2)
y2 = y_mid + int(dist / 2)
analyser.swipe(x, y1, x, y2, 180)
_yanghao_log(analyser,
"[养号] 动作: 下滑/切换 direction={} dist={}px".format(
getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist
)
)
_step_shot("after_swipe")
# 使用模块级 `_scaled_click(analyser, ...)` 和 `_do_comment(analyser)` 实现
def _human_delay(min_s: float = 0.4, max_s: float = 1.2) -> None:
try:
mn = float(min_s)
mx = float(max_s)
if mx < mn:
mx = mn
analyser.operation.delay(random.uniform(mn, mx))
except Exception:
analyser.operation.delay(1)
def _yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""养号模式下的桌面检测和自救恢复"""
try:
# 获取前台包名
top_pkg = analyser.operation.get_top_package(analyser.device_id) or ""
# 检查是否在抖音前台
is_douyin_pkg = top_pkg and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
if top_pkg and not is_douyin_pkg:
_yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}")
# 执行自救操作
try:
# 点击桌面图标
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
analyser.operation.click(
analyser.device_id, desktop_x, desktop_y
)
analyser.operation.delay(2)
# 点击直播按钮(备用坐标)
fallback_x = int(
getattr(analyser, "yanghao_fallback_live_x", 540) or 540
)
fallback_y = int(
getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000
)
analyser.operation.click(
analyser.device_id, fallback_x, fallback_y
)
analyser.operation.delay(1.5)
# 点击进入直播间(备用坐标)
enter_x = int(
getattr(analyser, "yanghao_fallback_enter_live_x", 540)
or 540
)
enter_y = int(
getattr(analyser, "yanghao_fallback_enter_live_y", 1200)
or 1200
)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(0.6)
analyser.operation.click(analyser.device_id, enter_x, enter_y)
analyser.operation.delay(2.0)
_yanghao_log(analyser, "[养号] 自救: 恢复操作完成")
return True
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}")
return False
else:
return False
except Exception as e:
_yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}")
return False
def _detect_icon(
action: str,
base_x: int,
base_y: int,
template_path: str,
roi_label: str,
shared_screenshot_path: str = None,
) -> tuple[bool, float]:
_step_shot(f"before_detect_{roi_label}")
# 确保在所有分支中都定义了 roi_path,避免后续使用时未赋值错误
roi_path = ""
# 如果坐标未配置且提供了模板文件,则使用屏幕右侧的默认坐标作为 ROI
tpl = str(template_path or "").strip()
tpl_exists = False
try:
# 直接存在
if tpl and os.path.exists(tpl):
tpl_exists = True
else:
# 尝试相对于 config 路径的仓库根解析(保证 assets/ 在不同 cwd 下也能被找到)
try:
cfg = (
getattr(analyser, "config_path", "config/config.json")
or "config/config.json"
)
cfg_abspath = os.path.abspath(cfg)
project_root = os.path.dirname(os.path.dirname(cfg_abspath))
candidate = os.path.join(project_root, tpl)
if tpl and os.path.exists(candidate):
tpl_exists = True
template_path = candidate
except Exception:
pass
except Exception:
tpl_exists = False
_yanghao_log(analyser,
f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}"
)
if int(base_x or 0) <= 0 or int(base_y or 0) <= 0:
if tpl_exists:
try:
if action == "爱心":
base_x = int(1080 * 0.88)
base_y = int(2400 * 0.78)
else:
base_x = int(1080 * 0.78)
base_y = int(2400 * 0.78)
except Exception:
base_x = 900
base_y = 1800
else:
return False, 0.0
# ROI 中心点允许独立偏移(仅影响截图检测,不影响点击坐标)
off_x = 0
off_y = 0
if action == "爱心":
off_x = int(getattr(analyser, "yanghao_like_roi_offset_x", 0) or 0)
off_y = int(getattr(analyser, "yanghao_like_roi_offset_y", 0) or 0)
elif action == "收藏":
off_x = int(getattr(analyser, "yanghao_fav_roi_offset_x", 0) or 0)
off_y = int(getattr(analyser, "yanghao_fav_roi_offset_y", 0) or 0)
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
if off_x or off_y:
try:
sx = int(sx) + int(
off_x
* int(getattr(analyser, "resolution_ratio_x", 1080))
/ 1080
)
sy = int(sy) + int(
off_y
* int(getattr(analyser, "resolution_ratio_y", 2400))
/ 2400
)
except Exception:
pass
# 使用默认的ROI大小
roi_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
try:
scale_x = float(getattr(analyser, "resolution_ratio_x", 1080)) / 1080.0
scale_y = float(getattr(analyser, "resolution_ratio_y", 2400)) / 2400.0
except Exception:
scale_x = scale_y = 1.0
try:
if action == "爱心":
action_scale = float(
getattr(analyser, "yanghao_like_roi_scale", 1.5)
)
elif action == "收藏":
action_scale = float(
getattr(analyser, "yanghao_fav_roi_scale", 1.5)
)
else:
action_scale = 1.0
except Exception:
action_scale = 1.5
roi_px = max(1, int(roi_size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(
roi_label, sx, sy, int(roi_px), shared_screenshot_path
)
# 只截图不识别,总是假设图标存在并返回高置信度
_yanghao_log(analyser, f"[养号] 检测: {action} -> 只截图不识别,假设图标存在")
return True, 1.0
def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
"""执行推荐页养号流程:退出直播间 -> 进入推荐页 -> 养号。
每一步操作间隔1秒,确保界面稳定。
"""
try:
# 输出设备分辨率与调试行(兼容原始日志格式)
try:
resx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
resy = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
resx, resy = 1080, 2400
_yanghao_log(analyser, f"设备分辨率为:{resx}*{resy}")
_yanghao_log(analyser, f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}")
_yanghao_log(analyser, "[养号] 开始推荐页养号流程")
# 步骤1: 发送系统返回键退出当前直播间
_yanghao_log(analyser, "[养号] 步骤1: 发送系统返回键退出直播间")
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
analyser.operation.delay(3.0)
# 步骤2: 再次发送返回键确保退出
_yanghao_log(analyser, "[养号] 步骤2: 再次发送返回键")
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
analyser.operation.delay(3.0)
# 步骤3: 在推荐页执行养号
_yanghao_log(analyser, f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒")
analyser.operation.delay(3.0)
yanghao_idle(analyser, total_seconds)
_yanghao_log(analyser, "[养号] 推荐页养号流程完成")
except Exception as e:
_yanghao_log(analyser, f"[养号] 推荐页养号流程失败: {e}")
# 失败时退化为普通养号
yanghao_idle(analyser, total_seconds)
def yanghao_wait(analyser, total_seconds: int) -> None:
"""养号等待函数(兼容接口)。"""
if total_seconds <= 0:
return
# 检查是否启用养号
if not bool(getattr(analyser, "yanghao_enabled", True)):
_yanghao_log(analyser, "[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)")
return
# 执行推荐页养号流程
yanghao_recommend_flow(analyser, total_seconds)
def yanghao_get_recommend_seconds(analyser) -> int:
"""返回推荐页养号的默认时长(兼容接口)。"""
try:
return int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
except Exception:
return 60