Files
douyin_guaji-main/douyin/other/douyin_yanghao.py
T
Your Name a61ba62864 feat: Enhance yanghao detection with polygon support and template matching
- Updated config.json to include new parameters for yanghao template paths and match thresholds.
- Adjusted default icon match threshold in config to 0.70 for better detection.
- Implemented polygon detection logic in yanghao_idle function to allow for flexible ROI configurations.
- Added support for per-action ROI scaling and sizes in the configuration.
- Introduced new methods in fudai_analyse for capturing ROI screenshots and matching templates.
- Created a test script to validate polygon detection against provided templates.
- Improved error handling and logging for better debugging during detection processes.
2026-01-04 09:06:25 +08:00

876 lines
42 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
def yanghao_idle(analyser, total_seconds: int) -> None:
"""养号等待。
- 若启用 `yanghao_enable_actions`:停留期间可按概率点爱心/收藏,停留结束后自动滑动。
- 否则:保持原有“分段等待 + 可选轻微滑动 + 定时休息”。
"""
if total_seconds <= 0:
return
if getattr(analyser, "yanghao_enable_actions", False):
# 循环:持续检测图标;都未检测到则立刻下滑继续;检测到则停留 10-15 秒并按概率执行动作,然后再下滑。
need_settle_after_swipe = False
def _step_shot(label: str) -> None:
# 环境变量优先:YANGHAO_STEP_SCREENSHOT=1
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:
nonlocal need_settle_after_swipe
_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)
print("[养号] 动作: 下滑/切换 direction={} dist={}px".format(getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist))
_step_shot("after_swipe")
# 标记:下滑后下一轮截图/检测前需要随机等待,避免动画未结束影响识别
need_settle_after_swipe = True
def _scaled_click(base_x: int, base_y: int) -> None:
sx, sy = analyser._scale_from_base(int(base_x), int(base_y))
analyser.operation.click(analyser.device_id, sx, sy)
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) -> tuple[bool, float]:
nonlocal need_settle_after_swipe
if need_settle_after_swipe:
# 下滑后:先随机等一下,再进行截图与模板匹配
_human_delay(1.0, 2.2)
need_settle_after_swipe = False
_step_shot(f"before_detect_{roi_label}")
# 如果坐标未配置且提供了模板文件,则使用屏幕右侧的默认坐标作为 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
print(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 大小,优先使用专用配置,否则回退到通用配置
# 优先使用明确的矩形配置(x1,y1,x2,y2),否则使用 per-action roi_size 或通用 roi_size
try:
rect_used = False
if action == "爱心":
rx1 = getattr(analyser, "yanghao_like_rect_x1", None)
ry1 = getattr(analyser, "yanghao_like_rect_y1", None)
rx2 = getattr(analyser, "yanghao_like_rect_x2", None)
ry2 = getattr(analyser, "yanghao_like_rect_y2", None)
elif action == "收藏":
rx1 = getattr(analyser, "yanghao_fav_rect_x1", None)
ry1 = getattr(analyser, "yanghao_fav_rect_y1", None)
rx2 = getattr(analyser, "yanghao_fav_rect_x2", None)
ry2 = getattr(analyser, "yanghao_fav_rect_y2", None)
else:
rx1 = ry1 = rx2 = ry2 = None
# 支持多边形配置(优先),格式期望为列表[[x,y],...];否则回退到矩形(x1,y1,x2,y2)
poly = None
if action == "爱心":
poly = getattr(analyser, "yanghao_like_poly", None)
elif action == "收藏":
poly = getattr(analyser, "yanghao_fav_poly", None)
if poly:
try:
pts = list(poly)
if len(pts) >= 1:
xs = [int(p[0]) for p in pts]
ys = [int(p[1]) for p in pts]
# 计算多边形质心(面积加权),若顶点过少回退到顶点平均
def _poly_centroid(pts_list):
if len(pts_list) < 3:
return (sum(xs) // len(xs), sum(ys) // len(ys))
area = 0.0
cx = 0.0
cy = 0.0
n = len(pts_list)
for i in range(n):
x0 = float(pts_list[i][0])
y0 = float(pts_list[i][1])
x1 = float(pts_list[(i + 1) % n][0])
y1 = float(pts_list[(i + 1) % n][1])
cross = x0 * y1 - x1 * y0
area += cross
cx += (x0 + x1) * cross
cy += (y0 + y1) * cross
area = area / 2.0
if abs(area) < 1e-9:
return (sum(xs) // len(xs), sum(ys) // len(ys))
cx = cx / (6.0 * area)
cy = cy / (6.0 * area)
return (int(round(cx)), int(round(cy)))
base_cx, base_cy = _poly_centroid(pts)
x1 = min(xs)
y1 = min(ys)
x2 = max(xs)
y2 = max(ys)
w = x2 - x1
h = y2 - y1
size = max(1, int(max(w, h)))
sx, sy = analyser._scale_from_base(int(base_cx), int(base_cy))
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
size_px = max(1, int(size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(size_px))
rect_used = True
except Exception:
rect_used = False
elif rx1 is not None and ry1 is not None and rx2 is not None and ry2 is not None:
try:
# 允许任意顺序的点,取 min/max
x1 = int(min(int(rx1), int(rx2)))
y1 = int(min(int(ry1), int(ry2)))
x2 = int(max(int(rx1), int(rx2)))
y2 = int(max(int(ry1), int(ry2)))
base_cx = (x1 + x2) // 2
base_cy = (y1 + y2) // 2
w = x2 - x1
h = y2 - y1
size = max(1, int(max(w, h)))
sx, sy = analyser._scale_from_base(int(base_cx), int(base_cy))
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
size_px = max(1, int(size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(size_px))
rect_used = True
except Exception:
rect_used = False
if not rect_used:
try:
if action == "爱心":
roi_size = int(getattr(analyser, "yanghao_like_icon_roi_size", None) or getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
elif action == "收藏":
roi_size = int(getattr(analyser, "yanghao_fav_icon_roi_size", None) or getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
else:
roi_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
except Exception:
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))
except Exception:
try:
default_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
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
default_size = int(getattr(analyser, "yanghao_icon_roi_size", 180) or 180)
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(default_size * max(scale_x, scale_y) * float(action_scale)))
roi_path = analyser._capture_roi_screenshot(roi_label, sx, sy, int(roi_px))
if not template_path or not os.path.exists(template_path):
print(f"[养号] 检测: {action} -> 失败(缺少模板文件:{template_path})")
return False, 0.0
try:
if action == "爱心":
thr = getattr(analyser, "yanghao_like_icon_match_threshold", None)
elif action == "收藏":
thr = getattr(analyser, "yanghao_fav_icon_match_threshold", None)
else:
thr = None
if thr is None:
detected, score = analyser._match_icon_template(roi_path, template_path)
else:
detected, score = analyser._match_icon_template(roi_path, template_path, float(thr))
except Exception:
detected, score = analyser._match_icon_template(roi_path, template_path)
print(f"[养号] 检测: {action} -> {'检测到' if detected else '未检测到'}(score={score:.3f})")
return detected, score
# 当已配置坐标或已提供模板文件时,启用图标检测
def _tpl_exists_check(tpl_path: str) -> tuple[bool, str]:
try:
tpl = str(tpl_path or "").strip()
if not tpl:
return False, tpl
# 直接存在
if os.path.exists(tpl):
return True, tpl
# 尝试相对于 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 os.path.exists(candidate):
return True, candidate
except Exception:
pass
except Exception:
pass
return False, tpl_path
try:
like_tpl = str(getattr(analyser, "yanghao_like_template_path", "") or "").strip()
fav_tpl = str(getattr(analyser, "yanghao_fav_template_path", "") or "").strip()
like_tpl_exists, like_tpl = _tpl_exists_check(like_tpl)
fav_tpl_exists, fav_tpl = _tpl_exists_check(fav_tpl)
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))
except Exception:
project_root = None
print(f"[养号][DEBUG] like_tpl='{like_tpl}' exists={like_tpl_exists}; fav_tpl='{fav_tpl}' exists={fav_tpl_exists}; project_root={project_root}")
# 如果解析得到的绝对路径不同,更新属性以便后续使用
if like_tpl_exists:
try:
setattr(analyser, "yanghao_like_template_path", like_tpl)
except Exception:
pass
if fav_tpl_exists:
try:
setattr(analyser, "yanghao_fav_template_path", fav_tpl)
except Exception:
pass
except Exception:
like_tpl_exists = False
fav_tpl_exists = False
use_icon = (
(
int(getattr(analyser, "yanghao_like_icon_x", 0) or 0) > 0
and int(getattr(analyser, "yanghao_like_icon_y", 0) or 0) > 0
and int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0) > 0
and int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0) > 0
)
or (like_tpl_exists and fav_tpl_exists)
)
start_ts = time.time()
last_desktop_check_ts = 0.0
while True:
if time.time() - start_ts >= total_seconds:
return
# 定期检测是否在桌面(每5秒检测一次,避免过于频繁)
now_ts = time.time()
check_interval = 5.0
if now_ts - last_desktop_check_ts >= check_interval:
last_desktop_check_ts = now_ts
try:
if yanghao_check_and_recover_from_desktop(analyser):
print("[养号] 检测到在桌面,已尝试恢复")
analyser.operation.delay(1)
except Exception:
pass
if not use_icon:
# 未配置图标检测时,退化为有动作的养号:周期性下滑并按概率使用坐标兜底点击/点赞
end_ts = time.time() + int(max(1, total_seconds))
print("[养号] 未配置图标模板,退化为坐标动作养号")
while time.time() < end_ts:
# 每次循环尝试按概率执行点赞/收藏/下滑
try:
# 尝试点赞(使用配置坐标作为兜底)
like_prob = float(getattr(analyser, "yanghao_like_prob", 0) or 0)
fav_prob = float(getattr(analyser, "yanghao_fav_prob", 0) or 0)
# 随机触发动作
r = random.random()
if r < like_prob and int(getattr(analyser, "yanghao_like_icon_x", 0) or 0) > 0:
_step_shot("before_like_click_fallback")
_scaled_click(int(getattr(analyser, "yanghao_like_icon_x", 0) or 0), int(getattr(analyser, "yanghao_like_icon_y", 0) or 0))
_step_shot("after_like_click_fallback")
print("[养号] 退化动作: 点爱心(坐标兜底)")
elif r < like_prob + fav_prob and int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0) > 0:
_step_shot("before_fav_click_fallback")
_scaled_click(int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0), int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0))
_step_shot("after_fav_click_fallback")
print("[养号] 退化动作: 点收藏(坐标兜底)")
else:
# 未触发具体动作则下滑切换内容
_do_swipe_next()
# 随机短暂停顿,避免行为太机械
_human_delay(2.0, 6.0)
except Exception:
# 出错时尽量不阻塞太久
analyser.operation.delay(1)
return
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",
)
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",
)
if (not like_ok) and (not fav_ok):
# 两个都没检测到:立刻下滑继续检测
_human_delay(0.3, 0.8)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
continue
# 检测到其中任意一个:在这里停留 10-15 秒,并按概率执行动作
dwell = int(random.randint(10, 15))
print(f"[养号] 检测到图标,停留 {dwell}s 后再切换")
# 仅当“同时检测到爱心+收藏”时,按概率触发评论动作
if (
like_ok
and fav_ok
and float(getattr(analyser, "yanghao_comment_prob", 0) or 0) > 0
and random.random() < float(getattr(analyser, "yanghao_comment_prob", 0) or 0)
):
comment_texts = getattr(analyser, "yanghao_comment_texts", None)
if comment_texts:
msg = random.choice(comment_texts)
print("[养号] 动作: 评论(prob={}) -> {}".format(getattr(analyser, "yanghao_comment_prob", 0), msg))
try:
_step_shot("comment_before_open")
_scaled_click(int(getattr(analyser, "yanghao_comment_btn_x", 0) or 0), int(getattr(analyser, "yanghao_comment_btn_y", 0) or 0))
_human_delay(0.8, 1.6)
_step_shot("comment_after_open")
_scaled_click(int(getattr(analyser, "yanghao_comment_input_x", 0) or 0), int(getattr(analyser, "yanghao_comment_input_y", 0) or 0))
_human_delay(0.6, 1.2)
_step_shot("comment_after_focus")
# 输入随机文本(优先 ADBKeyboard;否则走剪贴板/兜底)
ix, iy = analyser._scale_from_base(
int(getattr(analyser, "yanghao_comment_input_x", 0) or 0),
int(getattr(analyser, "yanghao_comment_input_y", 0) or 0),
)
prev_ime = ""
try:
ok_ime, prev_ime, _adb_ime = analyser.operation.ensure_adbkeyboard_ime(analyser.device_id)
except Exception:
ok_ime = False
ok_input = False
if ok_ime:
try:
ok_input = analyser.operation.input_text_adbkeyboard(analyser.device_id, msg, restore_prev=False)
except Exception:
ok_input = False
if not ok_input:
ok_input = bool(analyser.operation.paste_text_at(analyser.device_id, ix, iy, msg))
print(f"[养号] 评论输入{'成功' if ok_input else '失败'}")
_step_shot("comment_after_input")
_human_delay(0.6, 1.4)
# 发送:改为键盘确认(优先 ADBKeyBoard 的 SEND editor action;兜底 Enter)
try:
analyser.operation.confirm_from_keyboard(analyser.device_id)
except Exception:
pass
_human_delay(0.8, 1.6)
_step_shot("comment_after_send")
_scaled_click(int(getattr(analyser, "yanghao_comment_close_x", 0) or 0), int(getattr(analyser, "yanghao_comment_close_y", 0) or 0))
_human_delay(0.6, 1.2)
_step_shot("comment_after_close")
# 恢复原输入法(如果之前切换过)
if prev_ime:
try:
analyser.operation.restore_ime(analyser.device_id, prev_ime)
except Exception:
pass
except Exception as e:
print(f"[养号] 动作: 评论失败:{e}")
else:
print("[养号] 动作: 评论(prob={}) -> 跳过(未配置文案列表)".format(getattr(analyser, "yanghao_comment_prob", 0)))
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):
_human_delay(0.3, 0.9)
_step_shot("before_like_click")
_scaled_click(int(getattr(analyser, "yanghao_like_icon_x", 0) or 0), int(getattr(analyser, "yanghao_like_icon_y", 0) or 0))
_human_delay(0.2, 0.6)
_step_shot("after_like_click")
print("[养号] 动作: 点爱心(prob={})".format(getattr(analyser, "yanghao_like_prob", 0)))
else:
print("[养号] 动作: 跳过点爱心(prob={})".format(getattr(analyser, "yanghao_like_prob", 0)))
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):
_human_delay(0.3, 0.9)
_step_shot("before_fav_click")
_scaled_click(int(getattr(analyser, "yanghao_fav_icon_x", 0) or 0), int(getattr(analyser, "yanghao_fav_icon_y", 0) or 0))
_human_delay(0.2, 0.6)
_step_shot("after_fav_click")
print("[养号] 动作: 点收藏(prob={})".format(getattr(analyser, "yanghao_fav_prob", 0)))
else:
print("[养号] 动作: 跳过点收藏(prob={})".format(getattr(analyser, "yanghao_fav_prob", 0)))
# 停留
analyser.operation.delay(dwell)
# 接着下滑
_human_delay(0.4, 1.0)
_do_swipe_next()
# 下滑后的延迟在下一轮截图/检测前统一处理
# 理论上不会走到这里
return
# 不启用动作时,采用原有“分段等待 + 桌面检测”逻辑
start_ts = time.time()
last_desktop_check_ts = 0.0
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):
print("[养号] 检测到在桌面,已尝试恢复")
analyser.operation.delay(1)
except Exception:
pass
# 分段等待(避免一次 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 yanghao_try_tap_text_or_fallback(
analyser,
text: str,
fx: int,
fy: int,
contains: bool = True,
wait_after: float = 1.2,
use_fallback: bool = True,
tap_timeout: float = 1.5,
) -> bool:
ok = False
# 测试模式下尽量快(避免用户以为卡死)
if str(os.environ.get("FAST_UI", "")).strip() in ("1", "true", "True"):
wait_after = 0.2
try:
ok = analyser.operation.tap_by_text(analyser.device_id, text, contains=contains, timeout_seconds=tap_timeout)
except Exception:
ok = False
if ok:
print("[养号] 点击 '{}':UI 命中".format(text))
else:
if use_fallback:
print("[养号] 点击 '{}':UI 未命中,坐标兜底 ({},{})".format(text, fx, fy))
analyser.click(int(fx), int(fy))
ok = True
else:
print("[养号] 点击 '{}':UI 未命中,跳过兜底".format(text))
if wait_after and wait_after > 0:
analyser.operation.delay(wait_after)
return ok
def yanghao_try_multi_texts(
analyser,
texts: list[str],
contains: bool = True,
wait_after: float = 1.2,
tap_timeout: float = 2.5,
) -> bool:
"""依次尝试多组文案(无坐标兜底)。"""
for idx, t in enumerate(texts, 1):
ok = yanghao_try_tap_text_or_fallback(
analyser,
t,
0,
0,
contains=contains,
wait_after=wait_after if idx == len(texts) else 0.0,
use_fallback=False,
tap_timeout=tap_timeout,
)
if ok:
return True
return False
def yanghao_tap_close_icon(analyser) -> None:
"""仅使用系统返回键退出当前页(不再尝试坐标点击)。"""
print("[养号] 发送系统返回键 1/1")
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(0.8)
def yanghao_check_and_recover_from_desktop(analyser) -> bool:
"""检测是否在桌面,如果是则尝试恢复回到抖音。
返回 True 表示检测到桌面并已尝试恢复,False 表示不在桌面或无需处理。
"""
try:
top_pkg = ""
try:
top_pkg = str(analyser.operation.get_top_package(analyser.device_id) or "")
except Exception:
top_pkg = ""
# 如果包名存在且不是抖音相关包,说明可能在桌面或其他应用
if top_pkg and ("aweme" not in top_pkg and "douyin" not in top_pkg and "com.ss.android.ugc" not in top_pkg):
print(f"[养号] 检测到不在抖音前台(前台包: {top_pkg}),尝试恢复")
try:
# 点击桌面图标的预设坐标
try:
analyser.click(int(getattr(analyser, "desktop_icon_x", 0) or 0), int(getattr(analyser, "desktop_icon_y", 0) or 0))
except Exception:
# 退化为默认硬编码位置
analyser.click(153, 260)
analyser.operation.delay(2)
# 点击直播与进入直播间的备用坐标
try:
lx = int(getattr(analyser, "yanghao_fallback_live_x", 0) or 0)
ly = int(getattr(analyser, "yanghao_fallback_live_y", 0) or 0)
print(f"[养号] 点击直播按钮 -> ({lx},{ly})")
analyser.click(lx, ly)
analyser.operation.delay(1.5)
except Exception:
pass
try:
ex = int(getattr(analyser, "yanghao_fallback_enter_live_x", 0) or 0)
ey = int(getattr(analyser, "yanghao_fallback_enter_live_y", 0) or 0)
print(f"[养号] 点击进入直播间 -> ({ex},{ey}) 连点两次")
analyser.click(ex, ey)
analyser.operation.delay(0.6)
analyser.click(ex, ey)
analyser.operation.delay(2.0)
except Exception:
pass
return True
except Exception as e:
print(f"[养号] 恢复失败: {e}")
# 仍然返回 True 表示检测到了问题并尝试过恢复
return True
except Exception:
pass
return False
def yanghao_recommend_flow(analyser, total_seconds: int) -> None:
"""按你的需求执行:X 退出直播 -> 点推荐 -> 养号 -> 点直播 -> 点“点击进入直播间”。
如果识别不到文字,会使用坐标兜底;兜底仍失败时就退化成原地养号(不阻塞主流程)。
"""
try:
print("[养号] 推荐页流程:退出直播→推荐→养号→直播→进入直播间")
capture_steps = str(os.environ.get("YANGHAO_STEP_SCREENSHOT", "")).strip() in ("1", "true", "True")
if capture_steps:
analyser._save_step_screenshot("start")
print("[养号] Step1/5:系统返回键退出当前页")
yanghao_tap_close_icon(analyser)
print("[养号] step1: 已发送系统返回键(1次)")
if capture_steps:
analyser._save_step_screenshot("step1_close")
print("[养号] Step2/5:再次发送返回键")
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(1.2)
if capture_steps:
analyser._save_step_screenshot("step2_back")
print("[养号] Step3/5:在当前页停留/浏览 {} 秒".format(int(total_seconds)))
# 养号前检测是否在桌面
if yanghao_check_and_recover_from_desktop(analyser):
print("[养号] 检测到在桌面,已尝试恢复,继续养号流程")
analyser.operation.delay(1)
yanghao_idle(analyser, total_seconds)
print("[养号] step3: 停留/浏览完成 {} 秒".format(total_seconds))
if capture_steps:
analyser._save_step_screenshot("step3_browse_done")
print("[养号] Step4/5:回到『直播』")
fx = int(getattr(analyser, "yanghao_fallback_live_x", 0) or 0)
fy = int(getattr(analyser, "yanghao_fallback_live_y", 0) or 0)
print("[养号] step4: 坐标点击直播 -> ({},{})".format(fx, fy))
analyser.click(fx, fy)
analyser.operation.delay(1.5)
if capture_steps:
analyser._save_step_screenshot("step4_live")
print("[养号] Step5/5:点击『点击进入直播间』")
ex = int(getattr(analyser, "yanghao_fallback_enter_live_x", 0) or 0)
ey = int(getattr(analyser, "yanghao_fallback_enter_live_y", 0) or 0)
print("[养号] step5: 坐标点击进入直播间 -> ({},{}) 连点两次".format(ex, ey))
analyser.click(ex, ey)
analyser.operation.delay(0.6)
analyser.click(ex, ey)
analyser.operation.delay(2.0)
if capture_steps:
analyser._save_step_screenshot("step5_enter")
print("[养号] 推荐页流程完成")
except Exception as e:
print("[养号] 推荐页流程失败,退化为原地养号:{}".format(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)):
# 用户要求:关闭养号后不要再等待太久,而是继续执行主流程
print(f"[养号] yanghao_enabled=0:跳过推荐页养号(不再等待 {int(total_seconds)}s,快速继续)")
try:
analyser.operation.delay(1)
except Exception:
pass
return
# 只保留推荐页养号;增加“间隔(冷却)”控制,避免触发过于频繁
try:
# 如果启用了高价值预约且存在未完成的预约,则在开始养号前等待预约完成
try:
high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False))
except Exception:
high_value_enabled = False
if high_value_enabled:
try:
has_reservations = bool(getattr(analyser, "reservations", None) and len(getattr(analyser, "reservations", [])) > 0)
except Exception:
has_reservations = False
try:
after_pending = bool(getattr(analyser, "reservation_after_action_pending", False))
except Exception:
after_pending = False
if has_reservations or after_pending:
try:
analyser._log_kv(
"养号",
"检测到未完成的预约,养号将等待预约完成后再开始",
reservations_count=(len(getattr(analyser, "reservations", [])) if getattr(analyser, "reservations", None) else 0),
reservation_after_action_pending=after_pending,
)
except Exception:
print("[养号] 检测到未完成的预约,等待预约完成后再开始")
# 无限等待直到预约完成(不再使用超时),每次轮询间隔短暂休眠
poll_interval = 3
waited = 0
while True:
try:
still_has = bool(getattr(analyser, "reservations", None) and len(getattr(analyser, "reservations", [])) > 0)
still_pending = bool(getattr(analyser, "reservation_after_action_pending", False))
if not still_has and not still_pending:
break
except Exception:
# 若查询出错,继续等待并重试
still_has = True
still_pending = True
try:
analyser.operation.delay(poll_interval)
except Exception:
time.sleep(poll_interval)
waited += poll_interval
try:
analyser._log_kv(
"养号",
"预约已完成,开始养号",
waited_seconds=waited,
reservations_count=(len(getattr(analyser, "reservations", [])) if getattr(analyser, "reservations", None) else 0),
reservation_after_action_pending=bool(getattr(analyser, "reservation_after_action_pending", False)),
)
except Exception:
print(f"[养号] 预约已完成,等待了{waited}s,开始养号")
now = time.time()
interval = int(getattr(analyser, "yanghao_recommend_interval_seconds", 0) or 0)
last_ts = float(getattr(analyser, "_yanghao_last_recommend_ts", 0.0) or 0.0)
if interval > 0 and last_ts > 0:
dt = now - last_ts
if dt < interval:
remain = int(interval - dt)
print(f"[养号] 推荐页养号冷却中,剩余 {remain}s,跳过本次(改为等待 {int(total_seconds)}s)")
analyser.operation.delay(int(max(1, total_seconds)))
return
analyser._yanghao_last_recommend_ts = time.time()
except Exception:
pass
yanghao_recommend_flow(analyser, total_seconds)
def yanghao_get_recommend_seconds(analyser) -> int:
s = 60
try:
s = int(getattr(analyser, "yanghao_recommend_duration_seconds", 60) or 60)
except Exception:
s = 60
if s < 1:
s = 1
if s > 3600:
s = 3600
return s
def maybe_reset_after_swipes(analyser, needswitch: bool, swipe_times: int) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。"""
if not needswitch:
return swipe_times
if not bool(getattr(analyser, "reset_after_swipes_enabled", False)):
return swipe_times
threshold = max(1, int(getattr(analyser, "reset_after_swipes", 0) or 0))
if swipe_times < threshold:
return swipe_times
print("已切换直播间{}次,达到阈值{}:下滑回退到第一个直播间".format(swipe_times, threshold))
# 回退次数按当前已切换次数来(更符合“回到本轮第一个直播间”的语义)
back_times = int(swipe_times)
if back_times <= 0:
return 0
# 下滑回退:与上划切换相反方向
# 使用配置的滑动持续时间,如果没有配置则使用300ms(比之前的200ms更快)
swipe_duration_ms = int(
getattr(analyser, "swipe_duration_ms", 300) or 300
)
for i in range(back_times):
analyser.swipe(760, 800, 760, 1600, swipe_duration_ms)
print("回退直播间 {}/{}".format(i + 1, back_times))
analyser.operation.delay(2)
# 回到第一个后,计数归零
analyser.operation.delay(3)
return 0