From 2d59114ce121d126a31c3b6af201a433364c5f21 Mon Sep 17 00:00:00 2001 From: HYY Date: Fri, 14 Mar 2025 18:08:57 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E5=AE=A2=E6=88=B7=E7=AB=AF?= =?UTF-8?q?=E5=9C=A8=E7=BA=BF=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + src/plugins/remote/__init__.py | 3 + src/plugins/remote/remote.py | 100 +++++++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 src/plugins/remote/__init__.py create mode 100644 src/plugins/remote/remote.py diff --git a/.gitignore b/.gitignore index b4c7154de..2dd6de62e 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ memory_graph.gml .env.* config/bot_config_dev.toml config/bot_config.toml +src/plugins/remote/client_uuid.json # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/src/plugins/remote/__init__.py b/src/plugins/remote/__init__.py new file mode 100644 index 000000000..6f9a7b362 --- /dev/null +++ b/src/plugins/remote/__init__.py @@ -0,0 +1,3 @@ +import asyncio +from .remote import main +asyncio.run(main()) \ No newline at end of file diff --git a/src/plugins/remote/remote.py b/src/plugins/remote/remote.py new file mode 100644 index 000000000..6e0b0c9eb --- /dev/null +++ b/src/plugins/remote/remote.py @@ -0,0 +1,100 @@ +import requests +import time +import uuid +import platform +import os +import json +from loguru import logger +import asyncio + +# UUID文件路径 +UUID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "client_uuid.json") + +# 生成或获取客户端唯一ID +def get_unique_id(): + # 检查是否已经有保存的UUID + if os.path.exists(UUID_FILE): + try: + with open(UUID_FILE, 'r') as f: + data = json.load(f) + if 'client_id' in data: + print("从本地文件读取客户端ID") + return data['client_id'] + except (json.JSONDecodeError, IOError) as e: + print(f"读取UUID文件出错: {e},将生成新的UUID") + + # 如果没有保存的UUID或读取出错,则生成新的 + client_id = generate_unique_id() + + # 保存UUID到文件 + try: + with open(UUID_FILE, 'w') as f: + json.dump({'client_id': client_id}, f) + print("已保存新生成的客户端ID到本地文件") + except IOError as e: + print(f"保存UUID时出错: {e}") + + return client_id + +# 生成客户端唯一ID +def generate_unique_id(): + # 结合主机名、系统信息和随机UUID生成唯一ID + system_info = platform.system() + unique_id = f"{system_info}-{uuid.uuid4()}" + return unique_id + +def send_heartbeat(server_url, client_id): + """向服务器发送心跳""" + sys = platform.system() + try: + headers = { + 'Client-ID': client_id, + 'User-Agent': f'HeartbeatClient/{client_id[:8]}' + } + data = json.dumps({ + 'system': sys + }) + response = requests.post( + f"{server_url}/api/clients", + headers=headers, + data=data + ) + + if response.status_code == 201: + data = response.json() + logger.debug(f"心跳发送成功。服务器响应: {data}") + return True + else: + logger.debug(f"心跳发送失败。状态码: {response.status_code}") + return False + + except requests.RequestException as e: + logger.debug(f"发送心跳时出错: {e}") + return False + +async def main(): + # 配置 + SERVER_URL = "http://hyybuth.xyz:10058" # 更改为你的服务器地址 + HEARTBEAT_INTERVAL = 300 # 5分钟(秒) + + # 获取或生成客户端ID + client_id = get_unique_id() + logger.debug(f"客户端已启动,ID: {client_id}") + + # 主心跳循环 + try: + while True: + if send_heartbeat(SERVER_URL, client_id): + print(f"{HEARTBEAT_INTERVAL}秒后发送下一次心跳...") + else: + print(f"{HEARTBEAT_INTERVAL}秒后重试...") + + await asyncio.sleep(HEARTBEAT_INTERVAL) + + except KeyboardInterrupt: + print("用户已停止客户端") + except Exception as e: + print(f"发生意外错误: {e}") + +if __name__ == "__main__": + asyncio.run(main()) From 321dfe4f56d45a27113a106408ebcbc3a3332d98 Mon Sep 17 00:00:00 2001 From: HYY Date: Fri, 14 Mar 2025 18:11:16 +0800 Subject: [PATCH 2/2] =?UTF-8?q?ruff=E6=A0=BC=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/remote/__init__.py | 3 ++- src/plugins/remote/remote.py | 48 ++++++++++++++++------------------ 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/plugins/remote/__init__.py b/src/plugins/remote/__init__.py index 6f9a7b362..7a4a88472 100644 --- a/src/plugins/remote/__init__.py +++ b/src/plugins/remote/__init__.py @@ -1,3 +1,4 @@ import asyncio from .remote import main -asyncio.run(main()) \ No newline at end of file + +asyncio.run(main()) diff --git a/src/plugins/remote/remote.py b/src/plugins/remote/remote.py index 6e0b0c9eb..f2741b222 100644 --- a/src/plugins/remote/remote.py +++ b/src/plugins/remote/remote.py @@ -10,32 +10,34 @@ import asyncio # UUID文件路径 UUID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "client_uuid.json") + # 生成或获取客户端唯一ID def get_unique_id(): # 检查是否已经有保存的UUID if os.path.exists(UUID_FILE): try: - with open(UUID_FILE, 'r') as f: + with open(UUID_FILE, "r") as f: data = json.load(f) - if 'client_id' in data: + if "client_id" in data: print("从本地文件读取客户端ID") - return data['client_id'] + return data["client_id"] except (json.JSONDecodeError, IOError) as e: print(f"读取UUID文件出错: {e},将生成新的UUID") - + # 如果没有保存的UUID或读取出错,则生成新的 client_id = generate_unique_id() - + # 保存UUID到文件 try: - with open(UUID_FILE, 'w') as f: - json.dump({'client_id': client_id}, f) + with open(UUID_FILE, "w") as f: + json.dump({"client_id": client_id}, f) print("已保存新生成的客户端ID到本地文件") except IOError as e: print(f"保存UUID时出错: {e}") - + return client_id + # 生成客户端唯一ID def generate_unique_id(): # 结合主机名、系统信息和随机UUID生成唯一ID @@ -43,23 +45,15 @@ def generate_unique_id(): unique_id = f"{system_info}-{uuid.uuid4()}" return unique_id + def send_heartbeat(server_url, client_id): """向服务器发送心跳""" sys = platform.system() try: - headers = { - 'Client-ID': client_id, - 'User-Agent': f'HeartbeatClient/{client_id[:8]}' - } - data = json.dumps({ - 'system': sys - }) - response = requests.post( - f"{server_url}/api/clients", - headers=headers, - data=data - ) - + headers = {"Client-ID": client_id, "User-Agent": f"HeartbeatClient/{client_id[:8]}"} + data = json.dumps({"system": sys}) + response = requests.post(f"{server_url}/api/clients", headers=headers, data=data) + if response.status_code == 201: data = response.json() logger.debug(f"心跳发送成功。服务器响应: {data}") @@ -67,20 +61,21 @@ def send_heartbeat(server_url, client_id): else: logger.debug(f"心跳发送失败。状态码: {response.status_code}") return False - + except requests.RequestException as e: logger.debug(f"发送心跳时出错: {e}") return False + async def main(): # 配置 SERVER_URL = "http://hyybuth.xyz:10058" # 更改为你的服务器地址 HEARTBEAT_INTERVAL = 300 # 5分钟(秒) - + # 获取或生成客户端ID client_id = get_unique_id() logger.debug(f"客户端已启动,ID: {client_id}") - + # 主心跳循环 try: while True: @@ -88,13 +83,14 @@ async def main(): print(f"{HEARTBEAT_INTERVAL}秒后发送下一次心跳...") else: print(f"{HEARTBEAT_INTERVAL}秒后重试...") - + await asyncio.sleep(HEARTBEAT_INTERVAL) - + except KeyboardInterrupt: print("用户已停止客户端") except Exception as e: print(f"发生意外错误: {e}") + if __name__ == "__main__": asyncio.run(main())