From 7e7d183f5fbf84209c7a334435686b5df50d6c7a Mon Sep 17 00:00:00 2001
From: zhangkai <2403741920@qq.com>
Date: Thu, 11 Sep 2025 21:14:57 +0800
Subject: [PATCH] =?UTF-8?q?20250911-=E5=88=9D=E6=AD=A5=E5=8A=9F=E8=83=BD?=
=?UTF-8?q?=E5=B7=B2=E5=AE=8C=E6=88=90?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.idea/workspace.xml | 105 ++++++++++++++++++++++----------
Module/FlaskService.py | 44 ++++++++++++++
Utils/AiUtils.py | 2 +-
Utils/JsonUtils.py | 128 ++++++++++++++++++++++++++++++++++++++++
script/ScriptManager.py | 31 ++++++----
5 files changed, 267 insertions(+), 43 deletions(-)
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 8481fb9..5e7915d 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -4,7 +4,13 @@
-
+
+
+
+
+
+
+
@@ -46,29 +52,31 @@
- {
- "keyToString": {
- "ASKED_ADD_EXTERNAL_FILES": "true",
- "Python.123.executor": "Run",
- "Python.Main.executor": "Run",
- "Python.tidevice_entry.executor": "Run",
- "RunOnceActivity.ShowReadmeOnStart": "true",
- "RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
- "RunOnceActivity.git.unshallow": "true",
- "SHARE_PROJECT_CONFIGURATION_FILES": "true",
- "git-widget-placeholder": "main",
- "javascript.nodejs.core.library.configured.version": "20.17.0",
- "javascript.nodejs.core.library.typings.version": "20.17.58",
- "last_opened_file_path": "F:/company code/AI item/20250820/iOSAI",
- "node.js.detected.package.eslint": "true",
- "node.js.detected.package.tslint": "true",
- "node.js.selected.package.eslint": "(autodetect)",
- "node.js.selected.package.tslint": "(autodetect)",
- "nodejs_package_manager_path": "npm",
- "settings.editor.selected.configurable": "com.gitee.ui.GiteeSettingsConfigurable",
- "vue.rearranger.settings.migration": "true"
+
+}]]>
@@ -90,7 +98,7 @@
-
+
@@ -114,6 +122,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -162,8 +193,9 @@
-
+
+
@@ -235,7 +267,7 @@
-
+
@@ -277,7 +309,15 @@
1757587781103
-
+
+
+ 1757588135521
+
+
+
+ 1757588135521
+
+
@@ -305,15 +345,16 @@
-
-
-
-
-
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Module/FlaskService.py b/Module/FlaskService.py
index bd1c41c..c1a21d7 100644
--- a/Module/FlaskService.py
+++ b/Module/FlaskService.py
@@ -19,6 +19,7 @@ from Utils.ThreadManager import ThreadManager
from script.ScriptManager import ScriptManager
from Entity.Variables import anchorList, prologueList, addModelToAnchorList, removeModelFromAnchorList
import Entity.Variables as ev
+from Utils.JsonUtils import JsonUtils
app = Flask(__name__)
CORS(app)
@@ -367,5 +368,48 @@ def deleteAnchorWithIds():
return ResultData(data={"deleted": deleted}).toJson()
+# 查询主播聊天发送的最后一条信息
+@app.route("/select_last_message", methods=['GET'])
+def select_last_message():
+ data = JsonUtils.query_all_json_items()
+
+ return ResultData(data=data).toJson()
+
+
+@app.route("/update_last_message", methods=['POST'])
+def update_last_message():
+ data = request.get_json() # 解析 JSON
+ sender = data.get("sender")
+ udid = data.get("device")
+ text = data.get("text")
+
+ updated_count = JsonUtils.update_json_items(
+ match={"sender": sender, "text": text}, # 匹配条件
+ patch={"status": 1}, # 修改内容
+ filename="log/last_message.json", # 要修改的文件
+ multi=False # 只改第一条匹配的
+ )
+ if updated_count > 0:
+ return ResultData(data=updated_count, msg="修改成功").toJson()
+ return ResultData(data=updated_count, msg="修改失败").toJson()
+
+
+@app.route("/delete_last_message", methods=['POST'])
+def delete_last_message():
+ data = request.get_json() # 解析 JSON
+ sender = data.get("sender")
+ udid = data.get("device")
+ text = data.get("text")
+
+ updated_count = JsonUtils.delete_json_items(
+ match={"sender": sender, "text": text}, # 匹配条件
+ filename="log/last_message.json", # 要修改的文件
+ multi=False # 只改第一条匹配的
+ )
+ if updated_count > 0:
+ return ResultData(data=updated_count, msg="修改成功").toJson()
+ return ResultData(data=updated_count, msg="修改失败").toJson()
+
+
if __name__ == '__main__':
app.run("0.0.0.0", port=5000, debug=True, use_reloader=False)
diff --git a/Utils/AiUtils.py b/Utils/AiUtils.py
index 71515ce..f4f7934 100644
--- a/Utils/AiUtils.py
+++ b/Utils/AiUtils.py
@@ -709,4 +709,4 @@ class AiUtils(object):
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
LogManager.error(f"[delete_anchors_by_ids] 写入失败: {e}")
- return deleted
+ return deleted
\ No newline at end of file
diff --git a/Utils/JsonUtils.py b/Utils/JsonUtils.py
index e3ca259..d80e387 100644
--- a/Utils/JsonUtils.py
+++ b/Utils/JsonUtils.py
@@ -2,6 +2,8 @@ import os
import json
from pathlib import Path
+from Utils.LogManager import LogManager
+
class JsonUtils:
@staticmethod
@@ -98,3 +100,129 @@ class JsonUtils:
except Exception as e:
print(f"删除 JSON key 失败: {e}")
return False
+ # "-------------------------------------------------"
+ @classmethod
+ def _read_json_list(cls, file_path: Path) -> list:
+ try:
+ if not file_path.exists():
+ return []
+ with file_path.open("r", encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, list) else []
+ except Exception:
+ return []
+
+ @classmethod
+ def _write_json_list(cls, file_path: Path, data: list) -> None:
+ file_path.parent.mkdir(parents=True, exist_ok=True)
+ with file_path.open("w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=4)
+
+ # --- 新增:通用追加(不做字段校验) ---
+ @classmethod
+ def append_json_items(cls, items, filename="log/last_message.json"):
+ """
+ 将 dict 或 [dict, ...] 追加到 JSON 文件(数组)中;不校验字段。
+ """
+ file_path = Path(filename)
+ data = cls._read_json_list(file_path)
+
+ # 统一成 list
+ if isinstance(items, dict):
+ items = [items]
+ elif not isinstance(items, list):
+ # 既不是 dict 也不是 list,直接忽略
+ return
+
+ # 只接受字典项
+ items = [it for it in items if isinstance(it, dict)]
+ if not items:
+ return
+
+ data.extend(items)
+
+ LogManager.method_info(filename,"路径")
+ cls._write_json_list(file_path, data)
+
+
+ @classmethod
+ def update_json_items(cls, match: dict, patch: dict, filename="log/last_message.json", multi: bool = True) -> int:
+ """
+ 修改 JSON 文件(数组)中符合条件的项
+ :param match: 匹配条件(如 {"sender": "xxx"})
+ :param patch: 要修改/更新的字段(如 {"status": 1})
+ :param filename: JSON 文件路径
+ :param multi: True=修改所有匹配项,False=只修改第一项
+ :return: 修改的条数
+ """
+ file_path = Path(filename)
+ data = cls._read_json_list(file_path)
+
+ if not isinstance(match, dict) or not isinstance(patch, dict):
+ return 0
+
+ updated = 0
+ for idx, item in enumerate(data):
+ if not isinstance(item, dict):
+ continue
+
+ # 判断是否匹配
+ if all(item.get(k) == v for k, v in match.items()):
+ data[idx].update(patch)
+ updated += 1
+ if not multi:
+ break
+
+ if updated > 0:
+ cls._write_json_list(file_path, data)
+
+ return updated
+
+ @classmethod
+ def query_all_json_items(cls, filename="log/last_message.json") -> list:
+ """
+ 查询 JSON 文件(数组)中的所有项
+ :param filename: JSON 文件路径
+ :return: list,可能为空
+ """
+ file_path = Path(filename)
+ print(file_path)
+ data = cls._read_json_list(file_path)
+ return data if isinstance(data, list) else []
+
+
+
+ @classmethod
+ def delete_json_items(cls, match: dict, filename="log/last_message.json", multi: bool = True) -> int:
+ """
+ 删除 JSON 文件(数组)中符合条件的项
+ :param match: 匹配条件(如 {"sender": "xxx"})
+ :param filename: JSON 文件路径
+ :param multi: True=删除所有匹配项,False=只删除第一项
+ :return: 删除的条数
+ """
+ file_path = Path(filename)
+ data = cls._read_json_list(file_path)
+
+ if not isinstance(match, dict):
+ return 0
+
+ deleted = 0
+ new_data = []
+ for item in data:
+ if not isinstance(item, dict):
+ continue
+ # 是否匹配
+ if all(item.get(k) == v for k, v in match.items()):
+ deleted += 1
+ if not multi and deleted > 0:
+ # 只删除一条 → 剩下的全保留
+ new_data.extend(data[data.index(item) + 1:])
+ break
+ continue
+ new_data.append(item)
+
+ if deleted > 0:
+ cls._write_json_list(file_path, new_data)
+
+ return deleted
diff --git a/script/ScriptManager.py b/script/ScriptManager.py
index af1b221..eae5d2c 100644
--- a/script/ScriptManager.py
+++ b/script/ScriptManager.py
@@ -7,6 +7,7 @@ import wda
import os
from Utils.AiUtils import AiUtils
from Utils.ControlUtils import ControlUtils
+from Utils.JsonUtils import JsonUtils
from Utils.LogManager import LogManager
from Entity.Variables import anchorList, removeModelFromAnchorList, anchorWithSession
from Utils.Requester import Requester
@@ -567,17 +568,17 @@ class ScriptManager():
time.sleep(3)
while not event.is_set():
- try:
+ # try:
# 调用检测消息的方法
- self.monitorMessages(session, udid)
- except Exception as e:
- LogManager.method_error(f"监控消息 出现异常: {e},重新启动监控直播", "检测消息", udid)
- # 出现异常时,稍等再重启 TikTok 并重试
- ControlUtils.closeTikTok(session, udid)
- time.sleep(2)
- ControlUtils.openTikTok(session, udid)
- time.sleep(3)
- continue # 重新进入 while 循环,调用 monitorMessages
+ self.monitorMessages(session, udid)
+ # except Exception as e:
+ # LogManager.method_error(f"监控消息 出现异常: {e},重新启动监控直播", "检测消息", udid)
+ # # 出现异常时,稍等再重启 TikTok 并重试
+ # ControlUtils.closeTikTok(session, udid)
+ # time.sleep(2)
+ # ControlUtils.openTikTok(session, udid)
+ # time.sleep(3)
+ # continue # 重新进入 while 循环,调用 monitorMessages
# 检查未读消息并回复
def monitorMessages(self, session, udid):
@@ -731,7 +732,17 @@ class ScriptManager():
LogManager.method_info(f"获取主播的名称:{anchor_name}", "检测消息", udid)
# 找到输入框
+ last_data = [{
+ "sender": anchor_name,
+ "device": udid,
+ "text": last_msg,
+ "status": 0
+ }]
+ print(last_data)
+
+ LogManager.method_info(f"主播最后发送的数据:{last_data}", "检测消息", udid)
+ JsonUtils.append_json_items(last_data, "log/last_message.json")
sel = session.xpath("//TextView")
if anchor_name not in anchorWithSession: