Files
iOSAI/script/ScriptManager.py

906 lines
42 KiB
Python
Raw Normal View History

2025-08-06 22:11:33 +08:00
import random
2025-08-13 20:20:13 +08:00
import re
2025-08-08 22:08:10 +08:00
import threading
2025-08-06 22:11:33 +08:00
import time
2025-08-08 22:08:10 +08:00
from enum import Enum
2025-08-01 13:43:51 +08:00
import wda
import os
2025-08-05 15:41:20 +08:00
from Utils.AiUtils import AiUtils
2025-08-06 22:11:33 +08:00
from Utils.ControlUtils import ControlUtils
2025-09-11 21:14:57 +08:00
from Utils.JsonUtils import JsonUtils
from Utils.LogManager import LogManager
2025-09-05 19:16:14 +08:00
from Entity.Variables import anchorList, removeModelFromAnchorList, anchorWithSession
2025-08-12 18:53:06 +08:00
from Utils.Requester import Requester
2025-09-05 19:16:14 +08:00
import Entity.Variables as ev
2025-08-01 13:43:51 +08:00
# 脚本管理类
class ScriptManager():
2025-08-05 15:41:20 +08:00
# 单利对象
_instance = None # 类变量,用于存储单例实例
def __new__(cls):
# 如果实例不存在,则创建一个新实例
if cls._instance is None:
cls._instance = super(ScriptManager, cls).__new__(cls)
# 返回已存在的实例
return cls._instance
2025-08-01 13:43:51 +08:00
def __init__(self):
super().__init__()
2025-08-05 15:41:20 +08:00
self.initialized = True # 标记已初始化
2025-08-01 13:43:51 +08:00
# 养号
2025-08-27 21:58:55 +08:00
def growAccount(self, udid, event, max_retries=None):
"""
自动养号方法带重生机制
:param udid: 设备 UDID
:param event: 线程控制 Event
:param max_retries: 最大重试次数 (None 表示无限重试)
"""
retries = 10
2025-08-06 22:11:33 +08:00
while not event.is_set():
try:
2025-08-27 21:58:55 +08:00
# ========= 初始化 =========
client = wda.USBClient(udid)
session = client.session()
# 关闭并重新打开 TikTok
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
2025-08-27 21:58:55 +08:00
ControlUtils.openTikTok(session, udid)
time.sleep(3)
2025-09-01 21:51:36 +08:00
LogManager.method_info("养号重启tiktok", "养号", udid)
2025-08-27 21:58:55 +08:00
AiUtils.makeUdidDir(udid)
# ========= 主循环 =========
while not event.is_set():
# 设置手机的节点深度为15,判断该页面是否正确
session.appium_settings({"snapshotMaxDepth": 15})
# 判断当前页面上是否有推荐按钮
2025-08-28 16:24:32 +08:00
# el = session(xpath='//XCUIElementTypeButton[@name="top_tabs_recomend"]')
# node = session.xpath(
# '//XCUIElementTypeButton[@name="top_tabs_recomend" or @name="推荐" or @label="推荐"]'
# )
el = session.xpath(
'//XCUIElementTypeButton[@name="top_tabs_recomend" or @name="推荐" or @label="推荐"]'
)
2025-08-27 21:58:55 +08:00
if not el.exists:
# 记录日志
2025-09-01 21:51:36 +08:00
LogManager.method_error("找不到推荐按钮,养号出现问题,重启养号功能", "养号", udid=udid)
2025-08-27 21:58:55 +08:00
# 手动的抛出异常 重启流程
raise Exception("找不到推荐按钮,养号出现问题,重启养号功能")
if el.value != "1":
2025-09-01 21:51:36 +08:00
LogManager.method_error("当前页面不是推荐页面,养号出现问题,重启养号功能", "养号", udid=udid)
2025-08-27 21:58:55 +08:00
raise Exception("当前页面不是推荐页面,养号出现问题,重启养号功能")
2025-09-01 21:51:36 +08:00
LogManager.method_info("当前页面是推荐页面,开始养号", "养号", udid=udid)
2025-08-27 21:58:55 +08:00
# 重新设置节点的深度,防止手机进行卡顿
session.appium_settings({"snapshotMaxDepth": 0})
# ---- 截图保存 ----
try:
img = client.screenshot()
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
resource_dir = os.path.join(base_dir, "resources", udid)
os.makedirs(resource_dir, exist_ok=True)
filePath = os.path.join(resource_dir, "bgv.png")
img.save(filePath)
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"保存屏幕图像成功 -> {filePath}", "养号", udid)
2025-08-27 21:58:55 +08:00
print("保存了背景图:", filePath)
time.sleep(1)
2025-08-27 21:58:55 +08:00
except Exception as e:
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"截图或保存失败,失败原因:{e}", "养号", udid)
2025-08-27 21:58:55 +08:00
raise Exception("截图或保存失败,重启养号功能")
# ---- 视频逻辑 ----
try:
addX, addY = AiUtils.findImageInScreen("add", udid)
isSame = False
2025-08-27 21:58:55 +08:00
for i in range(2):
tx, ty = AiUtils.findImageInScreen("add", udid)
if addX == tx and addY == ty:
isSame = True
time.sleep(1)
else:
isSame = False
break
if addX > 0 and isSame:
needLike = random.randint(0, 100)
homeButton = AiUtils.findHomeButton(udid)
if homeButton:
2025-09-01 21:51:36 +08:00
LogManager.method_info("有首页按钮,查看视频", "养号", udid)
2025-08-27 21:58:55 +08:00
videoTime = random.randint(5, 15)
time.sleep(videoTime)
# 重置 session
client = wda.USBClient(udid)
session = client.session()
session.appium_settings({"snapshotMaxDepth": 0})
2025-09-03 19:03:34 +08:00
if needLike < 23:
2025-09-01 21:51:36 +08:00
LogManager.method_info("进行点赞", "养号", udid)
2025-08-27 21:58:55 +08:00
ControlUtils.clickLike(session, udid)
2025-09-01 21:51:36 +08:00
LogManager.method_info("继续观看视频", "养号", udid)
2025-08-27 21:58:55 +08:00
videoTime = random.randint(10, 30)
time.sleep(videoTime)
2025-09-01 21:51:36 +08:00
LogManager.method_info("准备划到下一个视频", "养号", udid)
2025-08-27 21:58:55 +08:00
client.swipe_up()
else:
2025-09-01 21:51:36 +08:00
LogManager.method_error("找不到首页按钮。出错了", "养号", udid)
2025-08-27 21:58:55 +08:00
else:
nextTime = random.randint(1, 5)
time.sleep(nextTime)
client.swipe_up()
except Exception as e:
2025-09-01 21:51:36 +08:00
LogManager.method_error(f"刷视频过程出现错误,重试", "养号", udid)
2025-08-27 21:58:55 +08:00
raise e # 抛出给上层,触发重生机制
2025-08-06 22:11:33 +08:00
except Exception as e:
2025-09-13 01:03:15 +08:00
LogManager.method_error(f"[{udid}] 养号出现异常,将重启流程: {e}", "养号", udid)
2025-08-27 21:58:55 +08:00
retries += 1
2025-09-13 01:03:15 +08:00
time.sleep(3) # 等待后重生
2025-08-06 22:11:33 +08:00
2025-08-08 22:08:10 +08:00
# 观看直播
2025-08-15 19:51:02 +08:00
def watchLiveForGrowth(self, udid, event, max_retries=None):
import time, random, wda
2025-08-08 22:08:10 +08:00
2025-08-15 19:51:02 +08:00
retry_count = 0
2025-08-27 21:58:55 +08:00
backoff_sec = 10 # 异常后冷却,避免频繁重启
2025-08-11 22:06:48 +08:00
while not event.is_set():
try:
2025-08-15 19:51:02 +08:00
# —— 每次重启都新建 client/session ——
client = wda.USBClient(udid)
session = client.session()
session.appium_settings({"snapshotMaxDepth": 15})
# 1) 先关再开
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
ControlUtils.openTikTok(session, udid)
2025-08-11 22:06:48 +08:00
time.sleep(3)
2025-08-20 14:38:02 +08:00
# 2) 进入直播 (使用英文)
2025-09-10 16:54:05 +08:00
live_button = session(
xpath='//XCUIElementTypeButton[@name="直播"] | //XCUIElementTypeOther[@name="直播"]')
2025-08-20 14:38:02 +08:00
2025-08-15 19:51:02 +08:00
if live_button.exists:
live_button.click()
else:
2025-09-01 21:51:36 +08:00
LogManager.method_error("无法找到直播间按钮 抛出异常 重新启动", "直播养号", udid)
2025-08-15 19:51:02 +08:00
# 抛出异常
raise Exception(f"找不到直播按钮,抛出异常 重新启动")
time.sleep(20)
2025-08-28 16:24:32 +08:00
live_button = session(xpath='//XCUIElementTypeButton[@name="直播"]')
if live_button.exists:
continue
# 下滑一下
client.swipe_up()
2025-08-15 19:51:02 +08:00
# 3) 取分辨率;可选重建 session 规避句柄陈旧
size = session.window_size()
width, height = size.width, size.height
session = client.session()
# 4) 主循环:刷直播
while not event.is_set():
time.sleep(3)
2025-08-11 22:06:48 +08:00
2025-08-20 14:38:02 +08:00
# 找到一个看直播的时候肯定有的元素,当这个元素没有的时候,就代表当前的页面出现了问题
# 需要抛出异常,重启这个流程
2025-08-28 16:24:32 +08:00
el1 = session.xpath('//XCUIElementTypeOther[@name="GBLFeedRootViewComponent"]')
el2 = session.xpath('//XCUIElementTypeOther[@value="0%"]')
2025-08-20 14:38:02 +08:00
2025-08-28 16:24:32 +08:00
if not (el1.exists or el2.exists):
print("当前页面不是直播间,重启刷直播")
2025-09-01 21:51:36 +08:00
LogManager.method_error("当前页面不是直播间,重启刷直播", "直播养号", udid=udid)
2025-08-27 21:58:55 +08:00
raise Exception("当前页面不是直播间")
2025-08-28 16:24:32 +08:00
else:
print("当前页面是直播间,继续刷直播")
2025-09-01 21:51:36 +08:00
LogManager.method_info("当前页面是直播间,继续刷直播", "直播养号", udid=udid)
2025-08-20 14:38:02 +08:00
2025-08-15 19:51:02 +08:00
# PK 直接划走
if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists:
print("✅ 当前是 PK跳过")
2025-09-01 21:51:36 +08:00
LogManager.method_info("✅ 当前是 PK跳过", "直播养号", udid=udid)
2025-08-15 19:51:02 +08:00
session.swipe_up()
continue
2025-08-11 22:06:48 +08:00
2025-08-15 19:51:02 +08:00
# 计算直播显示窗口数量(主画面+连麦小窗)
count = AiUtils.count_add_by_xml(session)
print(f"检测到直播显示区域窗口数:{count}")
if count > 1:
print("❌ 多窗口(有人连麦/分屏),划走")
2025-09-01 21:51:36 +08:00
LogManager.method_info("❌ 多窗口(有人连麦/分屏),划走", "直播养号", udid=udid)
2025-08-15 19:51:02 +08:00
session.swipe_up()
continue
else:
2025-08-20 14:38:02 +08:00
print("✅ 单窗口,(10%概率)开始点赞")
2025-09-01 21:51:36 +08:00
LogManager.method_info("✅ 单窗口,(3%概率)开始点赞", "直播养号", udid=udid)
2025-08-15 19:51:02 +08:00
# 随机点赞(仍保留中途保护)
2025-08-28 16:24:32 +08:00
if random.random() >= 0.97:
2025-08-15 19:51:02 +08:00
print("开始点赞")
2025-09-01 21:51:36 +08:00
LogManager.method_info("开始点赞", "直播养号", udid=udid)
2025-08-15 19:51:02 +08:00
for _ in range(random.randint(10, 30)):
# 中途转PK/连麦立即跳过
if session(xpath='//XCUIElementTypeOther[@name="kGBLInteractionViewMatchScoreBar"]').exists \
or AiUtils.count_add_by_xml(session) > 1:
print("❗ 中途发生 PK/连麦,跳过")
2025-09-01 21:51:36 +08:00
LogManager.method_info("❗ 中途发生 PK/连麦,跳过", "直播养号", udid=udid)
2025-08-15 19:51:02 +08:00
session.swipe_up()
break
x = width // 3 + random.randint(-10, 10)
y = height // 3 + random.randint(10, 20)
print("双击坐标:", x, y)
2025-09-01 21:51:36 +08:00
2025-08-15 19:51:02 +08:00
session.double_tap(x, y)
print("--------------------------------------------")
time.sleep(random.randint(180, 300))
2025-08-11 22:06:48 +08:00
session.swipe_up()
2025-08-15 19:51:02 +08:00
# 正常退出(外部 event 触发)
break
2025-08-11 22:06:48 +08:00
except Exception as e:
2025-08-15 19:51:02 +08:00
retry_count += 1
2025-09-01 21:51:36 +08:00
LogManager.method_error(f"watchLiveForGrowth 异常(第{retry_count}次):{repr(e)}", "直播养号", udid)
2025-08-15 19:51:02 +08:00
# 尝试轻量恢复一次,避免一些短暂性 session 失效
2025-08-11 22:06:48 +08:00
try:
2025-08-15 19:51:02 +08:00
client = wda.USBClient(udid)
_ = client.session()
2025-08-11 22:06:48 +08:00
except Exception:
2025-08-15 19:51:02 +08:00
pass
time.sleep(backoff_sec) # 冷却后整段流程重来
continue
2025-08-27 21:58:55 +08:00
"""
外层包装出现异常自动重试
关注打招呼以及回复主播消息
"""
def safe_greetNewFollowers(self, udid, needReply, event):
retries = 0
while not event.is_set():
2025-09-10 22:17:27 +08:00
try:
# AiUtils.pop_aclist_first()
# anchor = AiUtils.pop_aclist_first()
# if not anchor:
# break
self.greetNewFollowers(udid, needReply, event)
except Exception as e:
retries += 1
2025-09-13 01:03:15 +08:00
LogManager.method_error(f"greetNewFollowers 出现异常: {e},准备第 {retries} 次重试", "关注打招呼", udid)
2025-09-10 22:17:27 +08:00
time.sleep(3)
LogManager.method_error("greetNewFollowers 重试次数耗尽,任务终止", "关注打招呼", udid)
2025-09-08 21:42:09 +08:00
2025-08-11 22:06:48 +08:00
# 关注打招呼以及回复主播消息
2025-08-08 22:08:10 +08:00
def greetNewFollowers(self, udid, needReply, event):
2025-08-29 20:48:33 +08:00
2025-08-08 22:08:10 +08:00
client = wda.USBClient(udid)
session = client.session()
2025-09-03 19:03:34 +08:00
2025-08-15 19:51:02 +08:00
print(f"是否要自动回复消息:{needReply}")
2025-08-27 21:58:55 +08:00
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"是否要自动回复消息:{needReply}", "关注打招呼", udid)
2025-08-08 22:08:10 +08:00
# 先关闭Tik Tok
2025-09-15 22:40:45 +08:00
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
# 重新打开Tik Tok
ControlUtils.openTikTok(session, udid)
time.sleep(3)
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"重启tiktok", "关注打招呼", udid)
2025-08-12 18:53:06 +08:00
# 设置查找深度
session.appium_settings({"snapshotMaxDepth": 15})
2025-08-11 22:06:48 +08:00
2025-08-14 14:46:52 +08:00
# 创建udid名称的目录
AiUtils.makeUdidDir(udid)
2025-08-11 22:06:48 +08:00
# 返回上一步
2025-08-12 22:03:08 +08:00
def goBack(count):
for i in range(count):
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"返回上一步", "关注打招呼", udid)
2025-09-12 21:36:47 +08:00
session.appium_settings({"snapshotMaxDepth": 15})
2025-08-12 22:03:08 +08:00
ControlUtils.clickBack(session)
2025-09-15 22:40:45 +08:00
time.sleep(2)
2025-08-11 22:06:48 +08:00
2025-09-11 22:39:57 +08:00
LogManager.method_info(f"循环条件1:{not event.is_set()}", "关注打招呼", udid)
LogManager.method_info(f"循环条件2:{len(anchorList) > 0}", "关注打招呼", udid)
LogManager.method_info(f"循环条件3:{not event.is_set() and len(anchorList) > 0}", "关注打招呼", udid)
2025-09-05 19:16:14 +08:00
2025-08-11 22:06:48 +08:00
# 循环条件。1、 循环关闭 2、 数据处理完毕
2025-09-08 21:42:09 +08:00
while not event.is_set():
2025-08-12 18:53:06 +08:00
2025-08-27 21:58:55 +08:00
# 获取一个主播,并删除
2025-09-08 21:42:09 +08:00
anchor = AiUtils.pop_aclist_first()
if not anchor:
2025-09-10 22:17:27 +08:00
LogManager.method_info(f"数据库中的数据不足", "关注打招呼", udid)
2025-09-15 22:40:45 +08:00
time.sleep(30)
2025-09-10 22:17:27 +08:00
continue
2025-09-08 21:42:09 +08:00
aid = anchor["anchorId"]
anchorCountry = anchor.get("country", "")
2025-08-11 22:06:48 +08:00
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"主播的数据,用户名:{aid},国家:{anchorCountry}", "关注打招呼", udid)
2025-08-27 21:58:55 +08:00
# 点击搜索按钮
ControlUtils.clickSearch(session)
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"点击搜索按钮", "关注打招呼", udid)
2025-08-27 21:58:55 +08:00
# 强制刷新session
session.appium_settings({"snapshotMaxDepth": 15})
2025-09-01 21:51:36 +08:00
2025-08-27 21:58:55 +08:00
# 查找输入框
input = session.xpath('//XCUIElementTypeSearchField')
2025-09-01 21:51:36 +08:00
2025-08-27 21:58:55 +08:00
# 如果找到了输入框,就点击并且输入内容
if input.exists:
input.click()
# 稍作停顿
time.sleep(0.5)
else:
print(f"找不到输入框")
2025-09-01 21:51:36 +08:00
2025-08-12 18:53:06 +08:00
input.clear_text()
2025-09-15 22:40:45 +08:00
time.sleep(1)
2025-08-11 22:06:48 +08:00
# 输入主播id
2025-09-11 22:39:57 +08:00
input.set_text(f"{aid or '暂无数据'}\n")
2025-08-08 22:08:10 +08:00
2025-08-11 22:06:48 +08:00
# 定位 "关注" 按钮 通过关注按钮的位置点击主播首页
2025-08-27 21:58:55 +08:00
session.appium_settings({"snapshotMaxDepth": 23})
try:
2025-09-16 14:03:43 +08:00
# 点击进入首页
2025-08-29 20:48:33 +08:00
ControlUtils.clickFollow(session, aid)
2025-09-16 14:03:43 +08:00
LogManager.method_info("点击进入主播首页", "关注打招呼", udid)
2025-08-27 21:58:55 +08:00
except wda.WDAElementNotFoundError:
2025-09-16 14:03:43 +08:00
LogManager.method_info("未找到进入主播首页的按钮,跳过点击。", "关注打招呼", udid)
2025-08-27 21:58:55 +08:00
goBack(2)
session.appium_settings({"snapshotMaxDepth": 15})
2025-08-12 22:03:08 +08:00
continue
2025-08-08 22:08:10 +08:00
2025-09-15 22:40:45 +08:00
time.sleep(2)
2025-08-13 20:20:13 +08:00
2025-08-11 22:06:48 +08:00
# 找到并点击第一个视频
2025-08-27 21:58:55 +08:00
cellClickResult, workCount = ControlUtils.clickFirstVideoFromDetailPage(session)
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"点击第一个视频", "关注打招呼", udid)
2025-09-15 22:40:45 +08:00
time.sleep(2)
2025-08-08 22:08:10 +08:00
# 观看主播视频
2025-08-27 21:58:55 +08:00
def viewAnchorVideo(workCount):
2025-08-13 20:20:13 +08:00
print("开始查看视频,并且重新调整查询深度")
session.appium_settings({"snapshotMaxDepth": 5})
2025-08-27 21:58:55 +08:00
if workCount > 3:
count = 3
else:
count = workCount
2025-08-12 22:03:08 +08:00
while count != 0:
2025-09-15 22:40:45 +08:00
time.sleep(5)
2025-08-11 22:06:48 +08:00
img = client.screenshot()
2025-09-15 22:40:45 +08:00
time.sleep(1)
2025-08-27 21:58:55 +08:00
2025-09-15 22:40:45 +08:00
# filePath = f"resources/{udid}/bgv.png"
2025-09-13 01:03:15 +08:00
2025-08-27 21:58:55 +08:00
base_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # 当前脚本目录的上一级
filePath = os.path.join(base_dir, "resources", udid, "bgv.png")
dirPath = os.path.dirname(filePath)
if not os.path.exists(dirPath):
os.makedirs(dirPath)
2025-08-11 22:06:48 +08:00
img.save(filePath)
2025-08-27 21:58:55 +08:00
2025-09-01 21:51:36 +08:00
LogManager.method_info("保存屏幕图像成功", "关注打招呼", udid)
2025-09-15 22:40:45 +08:00
time.sleep(2)
2025-08-12 22:03:08 +08:00
# 查找add图标
2025-08-13 20:20:13 +08:00
r = ControlUtils.clickLike(session, udid)
2025-08-29 20:48:33 +08:00
2025-08-13 20:20:13 +08:00
# 点赞成功。
2025-08-27 21:58:55 +08:00
# if r == True:
2025-08-11 22:06:48 +08:00
2025-08-27 21:58:55 +08:00
count -= 1
# 随机看视频 15~30秒
time.sleep(random.randint(15, 30))
2025-08-14 13:49:28 +08:00
if count != 0:
client.swipe_up()
2025-08-12 22:03:08 +08:00
2025-08-13 20:20:13 +08:00
# 右滑返回
client.swipe_right()
2025-08-11 22:06:48 +08:00
2025-08-12 22:03:08 +08:00
# 如果打开视频失败。说明该主播没有视频
if cellClickResult == True:
2025-08-13 20:20:13 +08:00
# 观看主播视频
2025-09-01 21:51:36 +08:00
LogManager.method_info("去查看主播视频", "关注打招呼", udid)
2025-08-27 21:58:55 +08:00
viewAnchorVideo(workCount)
2025-08-13 20:20:13 +08:00
time.sleep(3)
2025-09-01 21:51:36 +08:00
LogManager.method_info("视频看完了,重置试图查询深度", "关注打招呼", udid)
2025-08-12 18:53:06 +08:00
session.appium_settings({"snapshotMaxDepth": 25})
2025-08-27 21:58:55 +08:00
2025-09-04 19:35:36 +08:00
time.sleep(0.5)
2025-08-27 21:58:55 +08:00
# 向上滑动
session.swipe_down()
2025-08-12 18:53:06 +08:00
time.sleep(2)
2025-08-13 20:20:13 +08:00
msgButton = AiUtils.getSendMesageButton(session)
2025-08-12 18:53:06 +08:00
time.sleep(2)
2025-08-13 20:20:13 +08:00
if msgButton is not None:
2025-09-01 21:51:36 +08:00
LogManager.method_info("找到发消息按钮了", "关注打招呼", udid)
2025-08-13 20:20:13 +08:00
print("找到发消息按钮了")
# 进入聊天页面
msgButton.click()
else:
2025-09-01 21:51:36 +08:00
LogManager.method_info("没有识别出发消息按钮", "关注打招呼", udid)
2025-08-13 20:20:13 +08:00
print("没有识别出发消息按钮")
goBack(3)
2025-08-29 20:48:33 +08:00
session.appium_settings({"snapshotMaxDepth": 15})
2025-08-13 20:20:13 +08:00
continue
2025-08-11 22:06:48 +08:00
2025-08-13 20:20:13 +08:00
time.sleep(3)
2025-08-12 18:53:06 +08:00
# 查找聊天界面中的输入框节点
2025-08-13 20:20:13 +08:00
chatInput = session.xpath("//TextView")
2025-08-11 22:06:48 +08:00
if chatInput.exists:
2025-09-05 19:16:14 +08:00
2025-08-13 20:20:13 +08:00
print("找到输入框了, 准备发送一条打招呼消息")
2025-09-01 21:51:36 +08:00
LogManager.method_info("找到输入框了, 准备发送一条打招呼消息", "关注打招呼", udid)
2025-09-05 19:16:14 +08:00
print("打招呼的数据", ev.prologueList)
2025-09-09 20:45:02 +08:00
LogManager.method_info(f"传递的打招呼的数据:{ev.prologueList}", "关注打招呼", udid)
2025-09-05 19:16:14 +08:00
2025-08-13 20:20:13 +08:00
# 准备打招呼的文案
2025-09-16 14:03:43 +08:00
text = random.choice(ev.prologueList)
# text = 'hello'
2025-09-05 19:16:14 +08:00
2025-09-09 20:45:02 +08:00
LogManager.method_info(f"取出打招呼的数据,{text}, 判断是否需要翻译", "关注打招呼", udid)
2025-09-08 21:42:09 +08:00
2025-09-05 19:16:14 +08:00
isContainChniese = AiUtils.contains_chinese(text)
if isContainChniese:
# 翻译成主播国家的语言
2025-09-16 16:16:50 +08:00
LogManager.method_info(f"需要翻译:{text},参数为:国家为{anchorCountry}, 即将进行翻译",
"关注打招呼", udid)
2025-09-09 20:45:02 +08:00
2025-09-05 19:16:14 +08:00
msg = Requester.translation(text, anchorCountry)
2025-09-16 14:03:43 +08:00
2025-09-09 20:45:02 +08:00
LogManager.method_info(f"翻译成功:{msg}, ", "关注打招呼", udid)
2025-09-05 19:16:14 +08:00
else:
msg = text
2025-09-09 20:45:02 +08:00
LogManager.method_info(f"即将发送的私信内容:{msg}", "关注打招呼", udid)
2025-09-08 21:42:09 +08:00
2025-08-12 18:53:06 +08:00
# 准备发送一条信息
chatInput.click()
2025-09-15 22:40:45 +08:00
time.sleep(2)
2025-08-13 20:20:13 +08:00
# 发送消息
2025-09-11 22:39:57 +08:00
chatInput.set_text(f"{msg or '暂无数据'}\n")
2025-09-10 16:54:05 +08:00
2025-09-11 22:39:57 +08:00
# input.set_text(f"{aid or '暂无数据'}\n")
2025-09-10 16:54:05 +08:00
2025-09-15 22:40:45 +08:00
time.sleep(1)
2025-09-10 16:54:05 +08:00
2025-08-11 22:06:48 +08:00
else:
2025-08-13 20:20:13 +08:00
print("无法发送信息")
2025-09-09 20:45:02 +08:00
LogManager.method_info(f"给主播{aid} 发送消息失败", "关注打招呼", udid)
2025-08-14 14:30:36 +08:00
2025-08-13 20:20:13 +08:00
# 接着下一个主播
2025-08-27 21:58:55 +08:00
# removeModelFromAnchorList(anchor)
2025-09-10 16:54:05 +08:00
goBack(1)
# 点击关注按钮
2025-09-16 15:37:36 +08:00
followButton = AiUtils.getFollowButton(session).get(timeout=5)
if followButton is not None:
# LogManager.method_info("找到关注按钮了", "关注打招呼", udid)
# followButton.click()
2025-09-16 16:16:50 +08:00
x, y, w, h = followButton.bounds
cx = int(x + w / 2)
cy = int(y + h / 2)
# 随机偏移 ±5 px可自己改范围
cx += random.randint(-5, 5)
cy += random.randint(-5, 5)
2025-09-16 15:37:36 +08:00
2025-09-16 16:16:50 +08:00
ControlUtils.tap_mini_cluster(cx, cy, session)
2025-09-16 15:37:36 +08:00
else:
LogManager.method_info("没找到关注按钮", "关注打招呼", udid)
time.sleep(1)
goBack(4)
session.appium_settings({"snapshotMaxDepth": 15})
continue
2025-09-10 16:54:05 +08:00
2025-08-29 20:48:33 +08:00
session.appium_settings({"snapshotMaxDepth": 15})
2025-09-10 16:54:05 +08:00
goBack(3)
2025-08-11 22:06:48 +08:00
else:
2025-09-09 20:45:02 +08:00
print(f"{aid}:该主播没有视频")
LogManager.method_info(f"{aid}:该主播没有视频", "关注打招呼", udid)
2025-08-13 20:20:13 +08:00
goBack(3)
2025-08-27 21:58:55 +08:00
session.appium_settings({"snapshotMaxDepth": 15})
2025-08-13 20:20:13 +08:00
continue
2025-08-08 22:08:10 +08:00
2025-08-13 20:20:13 +08:00
# 设置查找深度
session.appium_settings({"snapshotMaxDepth": 15})
time.sleep(2)
2025-08-15 19:51:02 +08:00
print("即将要回复消息")
2025-09-01 21:51:36 +08:00
LogManager.method_info("即将要回复消息", "关注打招呼", udid)
2025-09-04 19:35:36 +08:00
2025-08-13 20:20:13 +08:00
if needReply:
print("如果需要回复主播消息。走此逻辑")
2025-08-15 19:51:02 +08:00
2025-09-03 19:03:34 +08:00
print("----------------------------------------------------------")
print("监控回复消息")
# 执行回复消息逻辑
self.monitorMessages(session, udid)
homeButton = AiUtils.findHomeButton(udid)
if homeButton.exists:
homeButton.click()
else:
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
2025-08-13 20:20:13 +08:00
2025-08-15 19:51:02 +08:00
print("重新创建wda会话 防止wda会话失效")
client = wda.USBClient(udid)
session = client.session()
2025-08-13 20:20:13 +08:00
# 执行完成之后。继续点击搜索
session.appium_settings({"snapshotMaxDepth": 15})
else:
session.appium_settings({"snapshotMaxDepth": 15})
2025-09-04 19:35:36 +08:00
2025-08-27 21:58:55 +08:00
print("greetNewFollowers方法执行完毕")
2025-08-13 20:20:13 +08:00
2025-08-27 21:58:55 +08:00
# 检测消息
2025-08-14 15:40:17 +08:00
def replyMessages(self, udid, event):
client = wda.USBClient(udid)
session = client.session()
2025-08-13 20:20:13 +08:00
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
2025-08-14 15:40:17 +08:00
ControlUtils.openTikTok(session, udid)
2025-08-13 20:20:13 +08:00
time.sleep(3)
2025-09-13 01:03:15 +08:00
2025-08-15 19:51:02 +08:00
while not event.is_set():
2025-09-11 22:39:57 +08:00
try:
2025-08-27 21:58:55 +08:00
# 调用检测消息的方法
2025-09-11 22:39:57 +08:00
self.monitorMessages(session, udid)
except Exception as e:
2025-09-13 01:03:15 +08:00
LogManager.method_error(f"监控消息 出现异常: {e},重新启动监控直播", "检测消息", udid)
# 出现异常时,稍等再重启 TikTok 并重试
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
ControlUtils.openTikTok(session, udid)
2025-09-11 22:39:57 +08:00
time.sleep(3)
2025-09-13 01:03:15 +08:00
continue # 重新进入 while 循环,调用 monitorMessages
2025-08-13 20:20:13 +08:00
2025-08-14 15:40:17 +08:00
# 检查未读消息并回复
def monitorMessages(self, session, udid):
2025-08-15 19:51:02 +08:00
2025-08-27 21:58:55 +08:00
# 调整节点的深度为 7
2025-08-13 20:20:13 +08:00
session.appium_settings({"snapshotMaxDepth": 7})
2025-08-15 19:51:02 +08:00
2025-09-10 16:54:05 +08:00
el = session.xpath(
'//XCUIElementTypeButton[@name="a11y_vo_inbox"]'
' | '
'//XCUIElementTypeButton[contains(@name,"收件箱")]'
' | '
'//XCUIElementTypeButton[.//XCUIElementTypeStaticText[@value="收件箱"]]'
)
2025-08-27 21:58:55 +08:00
2025-08-13 20:20:13 +08:00
# 如果收件箱有消息 则进行点击
if el.exists:
m = re.search(r'(\d+)', el.label) # 抓到的第一个数字串
count = int(m.group(1)) if m else 0
if count:
el.click()
2025-08-27 21:58:55 +08:00
session.appium_settings({"snapshotMaxDepth": 25})
time.sleep(3)
while True:
info_count = 0
# 创建新的会话
2025-09-10 16:54:05 +08:00
el = session.xpath(
'//XCUIElementTypeButton[@name="a11y_vo_inbox"]'
' | '
'//XCUIElementTypeButton[contains(@name,"收件箱")]'
' | '
'//XCUIElementTypeButton[.//XCUIElementTypeStaticText[@value="收件箱"]]'
)
2025-08-27 21:58:55 +08:00
print("el", el)
if not el.exists:
2025-09-01 21:51:36 +08:00
LogManager.method_error(f"检测不到收件箱", "检测消息", udid)
2025-08-27 21:58:55 +08:00
raise Exception("当前页面找不到收件箱,重启")
# break
# 支持中文“收件箱”和英文“Inbox”
xpath_query = (
"//XCUIElementTypeStaticText"
"[@value='收件箱' or @label='收件箱' or @name='收件箱'"
" or @value='Inbox' or @label='Inbox' or @name='Inbox']"
)
# 查找所有收件箱节点
inbox_nodes = session.xpath(xpath_query).find_elements()
if len(inbox_nodes) < 2:
2025-09-01 21:51:36 +08:00
LogManager.method_error(f"当前页面不再收件箱页面,重启", "检测消息", udid)
2025-08-27 21:58:55 +08:00
raise Exception("当前页面不再收件箱页面,重启")
m = re.search(r'(\d+)', el.label) # 抓到的第一个数字串
count = int(m.group(1)) if m else 0
if not count:
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"当前收件箱的总数量{count}", "检测消息", udid)
2025-08-27 21:58:55 +08:00
break
2025-08-13 20:20:13 +08:00
2025-08-27 21:58:55 +08:00
# 新粉丝
xp_new_fan_badge = (
"//XCUIElementTypeCell[.//XCUIElementTypeLink[@name='新粉丝']]"
"//XCUIElementTypeStaticText[string-length(@value)>0 and translate(@value,'0123456789','')='']"
)
# 活动
xp_activity_badge = (
"//XCUIElementTypeCell[.//XCUIElementTypeLink[@name='活动']]"
"//XCUIElementTypeStaticText[string-length(@value)>0 and translate(@value,'0123456789','')='']"
)
# 系统通知
xp_system_badge = (
"//XCUIElementTypeCell[.//XCUIElementTypeLink[@name='系统通知']]"
"//XCUIElementTypeStaticText[string-length(@value)>0 and translate(@value,'0123456789','')='']"
)
# 消息请求
xp_request_badge = (
"//XCUIElementTypeCell"
"[.//*[self::XCUIElementTypeLink or self::XCUIElementTypeStaticText]"
" [@name='消息请求' or @label='消息请求' or @value='消息请求']]"
"//XCUIElementTypeStaticText[string-length(@value)>0 and translate(@value,'0123456789','')='']"
)
# 用户消息
2025-09-10 16:54:05 +08:00
# xp_badge_numeric = (
# '//XCUIElementTypeOther['
# ' @name="AWEIMChatListCellUnreadCountViewComponent"'
# ' or @name="TikTokIMImpl.InboxCellUnreadCountViewBuilder"'
# ']//XCUIElementTypeStaticText[@value and translate(@value,"0123456789","")=""]'
# )
2025-08-27 21:58:55 +08:00
xp_badge_numeric = (
2025-09-10 16:54:05 +08:00
"("
# 你的两类未读容器组件 + 数字徽标value 纯数字)
"//XCUIElementTypeOther["
" @name='AWEIMChatListCellUnreadCountViewComponent'"
" or @name='TikTokIMImpl.InboxCellUnreadCountViewBuilder'"
"]//XCUIElementTypeStaticText[@value and translate(@value,'0123456789','')='']"
")/ancestor::XCUIElementTypeCell[1]"
" | "
# 兜底:任何在 CollectionView 下、value 纯数字的徽标 → 找其最近的 Cell
"//XCUIElementTypeCollectionView//XCUIElementTypeStaticText"
"[@value and translate(@value,'0123456789','')='']"
"/ancestor::XCUIElementTypeCell[1]"
2025-08-27 21:58:55 +08:00
)
2025-08-29 20:48:33 +08:00
try:
# 如果 2 秒内找不到,会抛异常
user_text = session.xpath(xp_badge_numeric).get(timeout=2.0)
val = (user_text.info.get("value") or
user_text.info.get("label") or
user_text.info.get("name"))
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"用户未读数量:{val}", "检测消息", udid)
2025-08-29 20:48:33 +08:00
except Exception:
2025-09-01 21:51:36 +08:00
LogManager.method_warning("当前屏幕没有找到 用户 未读徽标数字", "检测消息", udid)
2025-08-29 20:48:33 +08:00
print("当前屏幕没有找到 用户消息 未读徽标数字", udid)
user_text = None
info_count += 1
if user_text:
user_text.tap()
time.sleep(3)
xml = session.source()
msgs = AiUtils.extract_messages_from_xml(xml)
# 检测出对方发的最后一条信息
2025-09-03 19:03:34 +08:00
# last_msg_text = next(item['text'] for item in reversed(msgs) if item['type'] == 'msg')
text_list = ['What do you think of my live stream?',
'What do you think makes my streams special?',
'Do you think Im one of the most engaging streamers youve seen?']
2025-09-08 21:42:09 +08:00
last_msg = next((item['text'] for item in reversed(msgs) if item['type'] == 'msg'),
2025-09-10 16:54:05 +08:00
random.choice(text_list))
2025-09-03 19:03:34 +08:00
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"检测到对方最后发送的消息:{last_msg}", "检测消息", udid)
2025-09-08 21:42:09 +08:00
isLanguage = AiUtils.is_language(last_msg)
if isLanguage:
2025-09-16 14:03:43 +08:00
# LogManager.method_info(f"{last_msg}", "检测消息", udid)
2025-09-08 21:42:09 +08:00
last_msg_text = last_msg
else:
2025-09-16 16:16:50 +08:00
LogManager.method_info(f"对方发送的消息不是语言,随机挑选作为最后一条进行回复:{last_msg}",
"检测消息", udid)
2025-09-08 21:42:09 +08:00
last_msg_text = random.choice(text_list)
2025-09-12 21:36:47 +08:00
if AiUtils.contains_chinese(last_msg_text):
LogManager.method_info(f"需要翻译:{last_msg_text}, 即将进行翻译", "检测消息", udid)
last_msg_text = Requester.translation(last_msg_text)
LogManager.method_info(f"翻译成功:{last_msg_text}, ", "检测消息", udid)
2025-08-29 20:48:33 +08:00
# 向ai发送信息
# 获取主播的名称
anchor_name = AiUtils.get_navbar_anchor_name(session)
2025-09-10 22:17:27 +08:00
LogManager.method_info(f"获取主播的名称:{anchor_name}", "检测消息", udid)
2025-09-12 21:36:47 +08:00
LogManager.method_info(f"获取主播最后发送的消息 进行翻译:{last_msg}", "检测消息", udid)
last_msg = Requester.translation(last_msg, "中国")
LogManager.method_info(f"翻译后的内容:{last_msg}", "检测消息", udid)
2025-08-29 20:48:33 +08:00
# 找到输入框
2025-09-11 21:14:57 +08:00
last_data = [{
"sender": anchor_name,
"device": udid,
"text": last_msg,
"status": 0
}]
print(last_data)
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"主播最后发送的数据,传递给前端进行记录:{last_data}", "检测消息", udid)
2025-09-11 21:14:57 +08:00
JsonUtils.append_json_items(last_data, "log/last_message.json")
2025-08-29 20:48:33 +08:00
2025-09-16 14:03:43 +08:00
sel = session.xpath("//TextView")
2025-08-29 20:48:33 +08:00
if anchor_name not in anchorWithSession:
# 如果是第一次发消息(没有sessionId的情况)
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"第一次发消息:{anchor_name},没有记忆", "检测消息", udid)
2025-09-11 22:39:57 +08:00
2025-09-12 21:36:47 +08:00
aiResult, sessionId = Requester.chatToAi({"query": last_msg_text, "user": "1"})
2025-08-29 20:48:33 +08:00
anchorWithSession[anchor_name] = sessionId
# 找到输入框输入ai返回出来的消息
2025-09-12 21:36:47 +08:00
2025-08-29 20:48:33 +08:00
if sel.exists:
sel.click() # 聚焦
time.sleep(1)
sel.clear_text()
2025-09-11 22:39:57 +08:00
sel.set_text(f"{aiResult or '暂无数据'}\n")
2025-08-29 20:48:33 +08:00
else:
2025-09-01 21:51:36 +08:00
LogManager.method_error("找不到输入框,重启", "检测消息", udid)
2025-08-29 20:48:33 +08:00
raise Exception("找不到输入框,重启")
else:
2025-09-16 14:03:43 +08:00
LogManager.method_info(f"不是一次发消息:{anchor_name},有记忆", "检测消息", udid)
2025-08-29 20:48:33 +08:00
# 如果不是第一次发消息证明存储的有sessionId
sessionId = anchorWithSession[anchor_name]
2025-09-12 21:36:47 +08:00
# TODO: user后续添加暂时写死
aiResult, sessionId = Requester.chatToAi(
{"query": last_msg_text, "conversation_id": sessionId, "user": "1"})
# aiResult = response['result']
2025-08-29 20:48:33 +08:00
if sel.exists:
sel.click() # 聚焦
time.sleep(1)
sel.clear_text()
2025-09-11 22:39:57 +08:00
sel.set_text(f"{aiResult or '暂无数据'}\n")
2025-08-29 20:48:33 +08:00
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"存储的sessionId:{anchorWithSession}", "检测消息", udid)
2025-08-29 20:48:33 +08:00
time.sleep(1)
# 返回
ControlUtils.clickBack(session)
# 重新回到收件箱页面后,强制刷新节点
session.appium_settings({"snapshotMaxDepth": 25})
time.sleep(1)
2025-08-27 21:58:55 +08:00
try:
# 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_new_fan_badge).get(timeout=2.0)
val = (badge_text.info.get("value") or
badge_text.info.get("label") or
badge_text.info.get("name"))
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"新粉丝未读数量:{val}", "检测消息", udid)
2025-08-27 21:58:55 +08:00
if badge_text:
badge_text.tap()
2025-08-13 20:20:13 +08:00
time.sleep(1)
2025-08-27 21:58:55 +08:00
ControlUtils.clickBack(session)
2025-08-13 20:20:13 +08:00
time.sleep(1)
2025-08-27 21:58:55 +08:00
except Exception:
2025-09-01 21:51:36 +08:00
LogManager.method_warning("当前屏幕没有找到 新粉丝 未读徽标数字", "检测消息", udid)
2025-08-27 21:58:55 +08:00
print("当前屏幕没有找到 新粉丝 未读徽标数字", udid)
badge_text = None
info_count += 1
try:
# 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_activity_badge).get(timeout=2.0)
val = (badge_text.info.get("value") or
badge_text.info.get("label") or
badge_text.info.get("name"))
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"活动未读数量:{val}", "检测消息", udid)
2025-08-27 21:58:55 +08:00
if badge_text:
badge_text.tap()
time.sleep(1)
ControlUtils.clickBack(session)
time.sleep(1)
except Exception:
2025-09-01 21:51:36 +08:00
LogManager.method_warning("当前屏幕没有找到 活动 未读徽标数字", "检测消息", udid)
2025-08-27 21:58:55 +08:00
print("当前屏幕没有找到 活动 未读徽标数字", udid)
badge_text = None
info_count += 1
try:
# 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_system_badge).get(timeout=2.0)
val = (badge_text.info.get("value") or
badge_text.info.get("label") or
badge_text.info.get("name"))
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"系统通知未读数量:{val}", "检测消息", udid)
2025-08-27 21:58:55 +08:00
if badge_text:
badge_text.tap()
time.sleep(1)
ControlUtils.clickBack(session)
time.sleep(1)
except Exception:
2025-09-01 21:51:36 +08:00
LogManager.method_warning("当前屏幕没有找到 系统通知 未读徽标数字", "检测消息", udid)
2025-08-27 21:58:55 +08:00
print("当前屏幕没有找到 系统通知 未读徽标数字", udid)
badge_text = None
info_count += 1
try:
# 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_request_badge).get(timeout=2.0)
val = (badge_text.info.get("value") or
badge_text.info.get("label") or
badge_text.info.get("name"))
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"消息请求未读数量:{val}", "检测消息", udid)
2025-08-27 21:58:55 +08:00
if badge_text:
badge_text.tap()
time.sleep(1)
ControlUtils.clickBack(session)
time.sleep(1)
except Exception:
2025-09-01 21:51:36 +08:00
LogManager.method_warning("当前屏幕没有找到 消息请求 未读徽标数字", "检测消息", udid)
2025-08-27 21:58:55 +08:00
print("当前屏幕没有找到 消息请求 未读徽标数字", udid)
badge_text = None
info_count += 1
# 双击收件箱 定位到消息的位置
if info_count == 5:
r = el.bounds # 可能是命名属性,也可能是 tuple
cx = int((r.x + r.width / 2) if hasattr(r, "x") else (r[0] + r[2] / 2))
cy = int((r.y + r.height / 2) if hasattr(r, "y") else (r[1] + r[3] / 2))
session.double_tap(cx, cy) # 可能抛异常:方法不存在
2025-09-01 21:51:36 +08:00
LogManager.method_info(f"双击收件箱 定位到信息", "检测消息", udid)
2025-08-29 20:48:33 +08:00
2025-08-27 21:58:55 +08:00
else:
return
else:
2025-09-01 21:51:36 +08:00
LogManager.method_error(f"检测不到收件箱", "检测消息", udid)
2025-08-27 21:58:55 +08:00
raise Exception("当前页面找不到收件箱,重启")