优化停止脚本,调整停止脚本方案

This commit is contained in:
2025-09-20 14:50:58 +08:00
parent fa667d2520
commit a4effb8058
5 changed files with 94 additions and 72 deletions

3
.idea/workspace.xml generated
View File

@@ -5,7 +5,8 @@
</component>
<component name="ChangeListManager">
<list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="20250904-初步功能已完成">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Utils/ThreadManager.py" beforeDir="false" afterPath="$PROJECT_DIR$/Utils/ThreadManager.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/script/ScriptManager.py" beforeDir="false" afterPath="$PROJECT_DIR$/script/ScriptManager.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />

View File

@@ -68,19 +68,41 @@ class ThreadManager:
@classmethod
def batch_stop(cls, udids: List[str]) -> Tuple[int, List[str], str]:
"""
批量停止任务,使用多线程并发执行
:param udids: 待停止的设备唯一标识列表
:return: (code, fail_list, msg)
code=200 全部成功fail_list=[]
code=1001 部分/全部失败fail_list 为失败描述字符串列表
批量停止任务——瞬间下发停止信号,仍统计失败结果
返回格式与原接口 100% 兼容:
(code, fail_list, msg)
code=200 全部成功
code=1001 部分/全部失败
"""
if not udids:
return 200, [], "无设备需要停止"
fail_list: List[str] = []
# ---------- 1. 瞬间置位 event ----------
with cls._lock:
for udid in udids:
task = cls._tasks.get(udid)
if not task or not task.get("running"):
fail_list.append(f"设备{udid}停止失败:当前设备没有执行相关任务")
continue
task["event"].set() # 下发停止信号
# ---------- 2. 并发等 0.2 s 收尾 ----------
def _wait_and_clean(udid: str) -> Tuple[int, str]:
"""子线程里只做极短 join 并清理记录"""
with cls._lock:
task = cls._tasks.get(udid)
if not task:
return 400, f"设备{udid}任务记录已丢失"
thread = task["thread"]
# 浅等 0.2 s后台还没死也继续
thread.join(0.2)
del cls._tasks[udid] # 立即清理
return 200, f"设备{udid}已下发停止指令"
with ThreadPoolExecutor(max_workers=min(32, len(udids))) as executor:
future_map = {executor.submit(cls.stop, udid): udid for udid in udids}
future_map = {executor.submit(_wait_and_clean, udid): udid for udid in udids}
for future in as_completed(future_map):
udid = future_map[future]
try:
@@ -89,8 +111,10 @@ class ThreadManager:
fail_list.append(f"设备{udid}停止失败:{reason}")
except Exception as exc:
fail_list.append(f"设备{udid}停止异常:{exc}")
# ---------- 3. 返回兼容格式 ----------
if fail_list:
return 1001, fail_list, "停止失败"
return 1001, fail_list, "部分设备停止失败"
return 200, [], "全部设备停止成功"

View File

@@ -41,9 +41,9 @@ class ScriptManager():
# 关闭并重新打开 TikTok
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
event.wait(timeout=1)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
LogManager.method_info("养号重启tiktok", "养号", udid)
AiUtils.makeUdidDir(udid)
@@ -81,7 +81,7 @@ class ScriptManager():
img.save(filePath)
LogManager.method_info(f"保存屏幕图像成功 -> {filePath}", "养号", udid)
print("保存了背景图:", filePath)
time.sleep(1)
event.wait(timeout=1)
except Exception as e:
LogManager.method_info(f"截图或保存失败,失败原因:{e}", "养号", udid)
raise Exception("截图或保存失败,重启养号功能")
@@ -94,7 +94,7 @@ class ScriptManager():
tx, ty = AiUtils.findImageInScreen("add", udid)
if addX == tx and addY == ty:
isSame = True
time.sleep(1)
event.wait(timeout=1)
else:
isSame = False
break
@@ -105,7 +105,7 @@ class ScriptManager():
if homeButton:
LogManager.method_info("有首页按钮,查看视频", "养号", udid)
videoTime = random.randint(5, 15)
time.sleep(videoTime)
event.wait(timeout=videoTime)
# 重置 session
client = wda.USBClient(udid)
@@ -118,14 +118,15 @@ class ScriptManager():
LogManager.method_info("继续观看视频", "养号", udid)
videoTime = random.randint(10, 30)
time.sleep(videoTime)
event.wait(timeout=videoTime)
LogManager.method_info("准备划到下一个视频", "养号", udid)
client.swipe_up()
else:
LogManager.method_error("找不到首页按钮。出错了", "养号", udid)
else:
nextTime = random.randint(1, 5)
time.sleep(nextTime)
event.wait(timeout=nextTime)
client.swipe_up()
except Exception as e:
@@ -134,7 +135,7 @@ class ScriptManager():
except Exception as e:
LogManager.method_error(f"[{udid}] 养号出现异常,将重启流程: {e}", "养号", udid)
time.sleep(3) # 等待后重生
event.wait(timeout=3)
# 观看直播
def watchLiveForGrowth(self, udid, event, max_retries=None):
@@ -152,9 +153,9 @@ class ScriptManager():
# 1) 先关再开
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
event.wait(timeout=1)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
# 2) 进入直播 (使用英文)
live_button = session(
@@ -166,7 +167,8 @@ class ScriptManager():
LogManager.method_error("无法找到直播间按钮 抛出异常 重新启动", "直播养号", udid)
# 抛出异常
raise Exception(f"找不到直播按钮,抛出异常 重新启动")
time.sleep(20)
waitTime = random.randint(15, 20)
event.wait(timeout=waitTime)
live_button = session(xpath='//XCUIElementTypeButton[@name="直播"]')
if live_button.exists:
@@ -182,7 +184,7 @@ class ScriptManager():
# 4) 主循环:刷直播
while not event.is_set():
time.sleep(3)
event.wait(timeout=3)
# 找到一个看直播的时候肯定有的元素,当这个元素没有的时候,就代表当前的页面出现了问题
# 需要抛出异常,重启这个流程
@@ -236,7 +238,7 @@ class ScriptManager():
session.double_tap(x, y)
print("--------------------------------------------")
time.sleep(random.randint(300, 600))
event.wait(timeout=random.randint(300, 600))
session.swipe_up()
# 正常退出(外部 event 触发)
@@ -251,7 +253,8 @@ class ScriptManager():
_ = client.session()
except Exception:
pass
time.sleep(backoff_sec) # 冷却后整段流程重来
# 冷却后整段流程重来
event.wait(timeout=backoff_sec)
continue
"""
@@ -269,7 +272,7 @@ class ScriptManager():
except Exception as e:
retries += 1
LogManager.method_error(f"greetNewFollowers 出现异常: {e},准备第 {retries} 次重试", "关注打招呼", udid)
time.sleep(3)
event.wait(timeout=3)
LogManager.method_error("greetNewFollowers 重试次数耗尽,任务终止", "关注打招呼", udid)
# 关注打招呼以及回复主播消息
@@ -284,11 +287,11 @@ class ScriptManager():
# 先关闭Tik Tok
ControlUtils.closeTikTok(session, udid)
time.sleep(1)
event.wait(timeout=1)
# 重新打开Tik Tok
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
LogManager.method_info(f"重启tiktok", "关注打招呼", udid)
# 设置查找深度
session.appium_settings({"snapshotMaxDepth": 15})
@@ -303,7 +306,7 @@ class ScriptManager():
session.appium_settings({"snapshotMaxDepth": 15})
ControlUtils.clickBack(session)
time.sleep(2)
event.wait(timeout=2)
LogManager.method_info(f"循环条件1:{not event.is_set()}", "关注打招呼", udid)
LogManager.method_info(f"循环条件2:{len(anchorList) > 0}", "关注打招呼", udid)
@@ -331,7 +334,7 @@ class ScriptManager():
if not anchor:
LogManager.method_info(f"数据库中的数据不足", "关注打招呼", udid)
time.sleep(30)
event.wait(timeout=30)
continue
aid = anchor.get("anchorId", "")
@@ -354,14 +357,14 @@ class ScriptManager():
if input.exists:
input.click()
# 稍作停顿
time.sleep(0.5)
event.wait(timeout=0.5)
else:
print(f"找不到输入框")
input = session.xpath('//XCUIElementTypeSearchField')
if input.exists:
input.clear_text()
time.sleep(1)
event.wait(timeout=1)
# 输入主播id
input.set_text(f"{aid or '暂无数据'}\n")
@@ -381,13 +384,12 @@ class ScriptManager():
session.appium_settings({"snapshotMaxDepth": 15})
continue
time.sleep(2)
event.wait(timeout=2)
# 找到并点击第一个视频
cellClickResult, workCount = ControlUtils.clickFirstVideoFromDetailPage(session)
LogManager.method_info(f"点击第一个视频", "关注打招呼", udid)
time.sleep(2)
event.wait(timeout=2)
# 观看主播视频
def viewAnchorVideo(workCount):
@@ -400,9 +402,9 @@ class ScriptManager():
count = workCount
while count != 0:
time.sleep(5)
event.wait(timeout=5)
img = client.screenshot()
time.sleep(1)
event.wait(timeout=1)
# filePath = f"resources/{udid}/bgv.png"
@@ -415,7 +417,7 @@ class ScriptManager():
img.save(filePath)
LogManager.method_info("保存屏幕图像成功", "关注打招呼", udid)
time.sleep(2)
event.wait(timeout=2)
# 查找add图标
r = ControlUtils.clickLike(session, udid)
@@ -425,7 +427,7 @@ class ScriptManager():
count -= 1
# 随机看视频 15~30秒
time.sleep(random.randint(15, 30))
event.wait(timeout=random.randint(15, 30))
if count != 0:
client.swipe_up()
@@ -437,17 +439,17 @@ class ScriptManager():
# 观看主播视频
LogManager.method_info("去查看主播视频", "关注打招呼", udid)
viewAnchorVideo(workCount)
time.sleep(3)
event.wait(timeout=3)
LogManager.method_info("视频看完了,重置试图查询深度", "关注打招呼", udid)
session.appium_settings({"snapshotMaxDepth": 25})
time.sleep(0.5)
event.wait(timeout=0.5)
# 向上滑动
session.swipe_down()
time.sleep(2)
event.wait(timeout=2)
msgButton = AiUtils.getSendMesageButton(session)
time.sleep(2)
event.wait(timeout=2)
if msgButton.exists:
# 进入聊天页面
msgButton.click()
@@ -460,7 +462,7 @@ class ScriptManager():
session.appium_settings({"snapshotMaxDepth": 15})
continue
time.sleep(3)
event.wait(timeout=3)
# 查找聊天界面中的输入框节点
chatInput = session.xpath("//TextView")
if chatInput.exists:
@@ -497,12 +499,10 @@ class ScriptManager():
if chatInput.exists:
chatInput.click()
chatInput.set_text(f"{msg or '暂无数据'}\n")
time.sleep(2)
event.wait(timeout=2)
# 发送消息
# input.set_text(f"{aid or '暂无数据'}\n")
time.sleep(1)
event.wait(timeout=1)
else:
print("无法发送信息")
LogManager.method_info(f"给主播{aid} 发送消息失败", "关注打招呼", udid)
@@ -544,8 +544,7 @@ class ScriptManager():
# 设置查找深度
session.appium_settings({"snapshotMaxDepth": 15})
time.sleep(2)
event.wait(timeout=2)
print("即将要回复消息")
LogManager.method_info("即将要回复消息", "关注打招呼", udid)
@@ -562,10 +561,9 @@ class ScriptManager():
homeButton.click()
else:
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
event.wait(timeout=2)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
print("重新创建wda会话 防止wda会话失效")
client = wda.USBClient(udid)
@@ -582,25 +580,25 @@ class ScriptManager():
client = wda.USBClient(udid)
session = client.session()
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
event.wait(timeout=2)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
while not event.is_set():
try:
# 调用检测消息的方法
self.monitorMessages(session, udid)
self.monitorMessages(session, udid, event)
except Exception as e:
LogManager.method_error(f"监控消息 出现异常: {e},重新启动监控直播", "检测消息", udid)
# 出现异常时,稍等再重启 TikTok 并重试
ControlUtils.closeTikTok(session, udid)
time.sleep(2)
event.wait(timeout=2)
ControlUtils.openTikTok(session, udid)
time.sleep(3)
event.wait(timeout=3)
continue # 重新进入 while 循环,调用 monitorMessages
# 检查未读消息并回复
def monitorMessages(self, session, udid):
def monitorMessages(self, session, udid, event):
# 调整节点的深度为 7
session.appium_settings({"snapshotMaxDepth": 7})
@@ -620,7 +618,7 @@ class ScriptManager():
if count:
el.click()
session.appium_settings({"snapshotMaxDepth": 25})
time.sleep(3)
event.wait(timeout=3)
while True:
info_count = 0
@@ -724,7 +722,7 @@ class ScriptManager():
if user_text:
user_text.tap()
time.sleep(3)
event.wait(timeout=3)
xml = session.source()
msgs = AiUtils.extract_messages_from_xml(xml)
# 检测出对方发的最后一条信息
@@ -786,7 +784,7 @@ class ScriptManager():
if sel.exists:
sel.click() # 聚焦
time.sleep(1)
event.wait(timeout=1)
sel.clear_text()
sel.set_text(f"{aiResult or '暂无数据'}\n")
else:
@@ -804,19 +802,18 @@ class ScriptManager():
# aiResult = response['result']
if sel.exists:
sel.click() # 聚焦
time.sleep(1)
event.wait(timeout=1)
sel.clear_text()
sel.set_text(f"{aiResult or '暂无数据'}\n")
LogManager.method_info(f"存储的sessionId:{anchorWithSession}", "检测消息", udid)
time.sleep(1)
event.wait(timeout=1)
# 返回
ControlUtils.clickBack(session)
# 重新回到收件箱页面后,强制刷新节点
session.appium_settings({"snapshotMaxDepth": 25})
time.sleep(1)
event.wait(timeout=1)
try:
# 如果 2 秒内找不到,会抛异常
badge_text = session.xpath(xp_new_fan_badge).get(timeout=2.0)
@@ -827,9 +824,9 @@ class ScriptManager():
LogManager.method_info(f"新粉丝未读数量:{val}", "检测消息", udid)
if badge_text:
badge_text.tap()
time.sleep(1)
event.wait(timeout=1)
ControlUtils.clickBack(session)
time.sleep(1)
event.wait(timeout=1)
except Exception:
LogManager.method_warning("当前屏幕没有找到 新粉丝 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 新粉丝 未读徽标数字", udid)
@@ -846,9 +843,9 @@ class ScriptManager():
LogManager.method_info(f"活动未读数量:{val}", "检测消息", udid)
if badge_text:
badge_text.tap()
time.sleep(1)
event.wait(timeout=1)
ControlUtils.clickBack(session)
time.sleep(1)
event.wait(timeout=1)
except Exception:
LogManager.method_warning("当前屏幕没有找到 活动 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 活动 未读徽标数字", udid)
@@ -864,9 +861,9 @@ class ScriptManager():
LogManager.method_info(f"系统通知未读数量:{val}", "检测消息", udid)
if badge_text:
badge_text.tap()
time.sleep(1)
event.wait(timeout=1)
ControlUtils.clickBack(session)
time.sleep(1)
event.wait(timeout=1)
except Exception:
LogManager.method_warning("当前屏幕没有找到 系统通知 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 系统通知 未读徽标数字", udid)
@@ -882,9 +879,9 @@ class ScriptManager():
LogManager.method_info(f"消息请求未读数量:{val}", "检测消息", udid)
if badge_text:
badge_text.tap()
time.sleep(1)
event.wait(timeout=1)
ControlUtils.clickBack(session)
time.sleep(1)
event.wait(timeout=1)
except Exception:
LogManager.method_warning("当前屏幕没有找到 消息请求 未读徽标数字", "检测消息", udid)
print("当前屏幕没有找到 消息请求 未读徽标数字", udid)