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 # 如果启动时,配置文件中的app_id为空,那么将app_id写入配置文件 if not self.app_id and 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} 写入配置文件") self.app_id = app_id def client_set_callback(self): """在server启动后调用此方法设置回调""" resp = self.client.set_callback(self.app_id, self.callback_url) print(f"set_callback 成功: {resp}") # 项目全局唯一 client 实例 gewe_client = Client()