加入一个全局Client ,方便所有地方调用。

This commit is contained in:
liuwei
2025-04-23 11:24:33 +08:00
parent 04ebb43fe5
commit b7e5a1ff3e
10 changed files with 69 additions and 433 deletions
+59
View File
@@ -0,0 +1,59 @@
import os
import toml
import time
import logging
# 假设 gewechat_client 已经安装,并且 GewechatClient 可直接导入
from gewechat_client import GewechatClient
logger = logging.getLogger(__name__)
class Client:
def __init__(self, config_path=None):
# 默认配置文件路径
if config_path is None:
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.toml")
self.config_path = config_path
config = toml.load(config_path)
gewechat_cfg = config.get("Gewechat", {})
self.base_url = gewechat_cfg.get("base_url", "")
self.gewechat_token = gewechat_cfg.get("gewechat_token", "")
self.app_id = gewechat_cfg.get("app_id", "")
self.callback_url = gewechat_cfg.get("callback_url", "")
# 初始化 GewechatClient
self.client = GewechatClient(
base_url=self.base_url,
token=self.gewechat_token
)
# 登录, 自动创建二维码,扫码后自动登录
app_id, error_msg = self.client.login(app_id=self.app_id)
if error_msg:
logger.error("登录失败")
return
# 休眠等待server启动,防止回调设置失败
max_retries = 5
retry_interval = 5 # 秒
for attempt in range(1, max_retries + 1):
resp = self.client.set_callback(self.app_id, self.callback_url)
if resp and resp.get("success", False):
print(f"set_callback 成功: {resp}")
break
else:
logger.warning(f"set_callback 第{attempt}次失败,{retry_interval}秒后重试...")
time.sleep(retry_interval)
else:
logger.error("set_callback 多次重试后仍失败,请检查server状态。")
# 如果启动时,配置文件中的app_id为空,那么将app_id写入配置文件
if not self.app_id and app_id:
# 更新 config.toml 文件中的 app_id
config["Gewechat"]["app_id"] = app_id
with open(self.config_path, "w", encoding="utf-8") as f:
toml.dump(config, f)
logger.info(f"已将新的APP_ID: {app_id} 写入配置文件")
# 同时更新当前实例的 app_id
self.app_id = app_id
# 项目全局唯一 client 实例
gewe_client = Client().client
+5
View File
@@ -0,0 +1,5 @@
[Gewechat]
base_url= "http://192.168.2.240:2531/v2/api"
gewechat_token= "cb43f52db27e4a56bb6ec7da54373582"
app_id="wx_3BC6eSHGE5xEm_hH3__7c"
callback_url="http://192.168.2.192:8999/gewechat/callback"