Files
abot/gewechat/client.py

59 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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