Files
douyin_guaji-main/douyin/other/douyin_yanghao.py
T

711 lines
30 KiB
Python

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
def _scaled_click(analyser, 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 _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)
print(f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})")
_scaled_click(analyser, btn_x, btn_y)
analyser.operation.delay(2.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)
print(f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})")
_scaled_click(analyser, input_x, input_y)
analyser.operation.delay(2.0)
# 步骤3: 输入评论文本
comment_texts = getattr(analyser, "yanghao_comment_texts", []) or []
if not comment_texts:
comment_texts = ["加油", "不错", "很好看"]
selected_text = random.choice(comment_texts)
print(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)
)
print(f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})")
analyser.operation.delay(2.0)
# 步骤4: 发送评论
ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id))
print(f"[养号][评论] Step4: 发送评论 -> ok={ok_send}")
analyser.operation.delay(2.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)
print(f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})")
_scaled_click(analyser, close_x, close_y)
analyser.operation.delay(2.0)
except Exception as e:
print(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)
print(
"[养号] 动作: 下滑/切换 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
print(
f"[养号] 检测: {action} -> 模板文件={template_path} tpl_exists={tpl_exists}"
)
# 真实的模板匹配检测,直接在full screenshot上进行
try:
if not tpl_exists or not os.path.exists(str(template_path or "")):
print(f"[养号] {action}: 模板文件不存在,假设图标存在")
return True, 1.0
# 使用共享的full screenshot,不做ROI截图
if not shared_screenshot_path or not os.path.exists(
shared_screenshot_path
):
print(f"[养号] {action}: 截图文件不存在,假设图标存在")
return True, 1.0
# 读取full screenshot
pic = cv2.imread(shared_screenshot_path)
if pic is None:
print(f"[养号] {action}: 读取截图失败,假设图标存在")
return True, 1.0
# 读取模板
template = cv2.imread(str(template_path))
if template is None:
print(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:
print(f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})")
return True, float(max_val)
else:
print(
f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})"
)
return False, float(max_val)
except Exception as e:
print(f"[养号] {action}: 模板匹配异常 {e},假设图标存在")
return True, 1.0
end_ts = time.time() + int(max(1, total_seconds))
print(f"[养号] 开始养号模式,总时长 {total_seconds}s")
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
)
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
# 跟踪是否实际触发了 点爱心/点收藏 动作(只有在对应概率命中并执行点击时为 True)
did_like = False
did_fav = False
# 根据概率点击爱心
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(2.0) # 延迟2秒
print(
"[养号] 动作: 点爱心(prob={})".format(
getattr(analyser, "yanghao_like_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_like_prob", 0)
if like_ok:
print("[养号] 动作: 跳过点爱心(prob={prob})")
else:
print("[养号] 动作: 跳过点爱心(未检测到图标)")
# 根据概率点击收藏
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(2.0) # 延迟2秒
print(
"[养号] 动作: 点收藏(prob={})".format(
getattr(analyser, "yanghao_fav_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_fav_prob", 0)
if fav_ok:
print("[养号] 动作: 跳过点收藏(prob={prob})")
else:
print("[养号] 动作: 跳过点收藏(未检测到图标)")
# 根据概率评论
# 仅在爱心和收藏都实际触发(都被点击)时才考虑评论
# 记录评论是否实际执行
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
):
_do_comment(analyser)
did_comment = True
print(
"[养号] 动作: 评论(prob={})".format(
getattr(analyser, "yanghao_comment_prob", 0)
)
)
else:
prob = getattr(analyser, "yanghao_comment_prob", 0)
if not (did_like and did_fav):
print("[养号] 动作: 跳过评论(爱心/收藏未同时触发)")
else:
print("[养号] 动作: 跳过评论(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)
print(f"[养号] 检测到动作,停留 {dwell_time:.1f}s")
analyser.operation.delay(dwell_time)
else:
# 每次操作后随机等待,避免行为太机械
_human_delay(2.0, 6.0)
except Exception as e:
print(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:
print(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)
print("[养号] 自救: 恢复操作完成")
return True
except Exception as e:
print(f"[养号] 自救: 恢复操作失败: {e}")
return False
else:
return False
except Exception as e:
print(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):
print("[养号] 检测到不在抖音前台,已尝试恢复")
analyser.operation.delay(1)
except Exception as e:
print(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)
print(
"[养号] 动作: 下滑/切换 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:
print(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)
print("[养号] 自救: 恢复操作完成")
return True
except Exception as e:
print(f"[养号] 自救: 恢复操作失败: {e}")
return False
else:
return False
except Exception as e:
print(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
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大小
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
)
# 只截图不识别,总是假设图标存在并返回高置信度
print(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
print(f"设备分辨率为:{resx}*{resy}")
print(f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}")
print("[养号] 开始推荐页养号流程")
# 步骤1: 发送系统返回键退出当前直播间
print("[养号] 步骤1: 发送系统返回键退出直播间")
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
analyser.operation.delay(3.0)
# 步骤2: 再次发送返回键确保退出
print("[养号] 步骤2: 再次发送返回键")
analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4
analyser.operation.delay(3.0)
# 步骤3: 在推荐页执行养号
print(f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒")
analyser.operation.delay(3.0)
yanghao_idle(analyser, total_seconds)
print("[养号] 推荐页养号流程完成")
except Exception as e:
print(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)):
print("[养号] 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