runner.py
7.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from __future__ import annotations
import logging
import os
import time
from datetime import datetime
import httpx
from app.infrastructure.time import china_now
from app.config.loader import ConfigLoader
from app.infrastructure.database import SessionLocal
from app.infrastructure.wecom_sync_client import HttpWeComSyncClient, WeComSyncClientError
from app.jobs.log_context import JOB_NAME_MAP, format_job_log, reset_job_log_context, set_job_log_context
from app.model.wecom_sync import WeComBot, WeComCustomerGroup
from app.service.wecom_customer_group_orchestration_service import (
HttpChatCompletionsBatchDispatcher,
WeComCustomerGroupOrchestrationService,
)
from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService
from app.customer_info.service import CustomerInfoService
from app.customer_info.weekly_report_service import WeeklyReportService
logger = logging.getLogger(__name__)
_COURSE_BASE_URL = os.environ.get("COURSE_BASE_URL", "").rstrip("/")
def _push_content(record) -> str:
"""生成推送消息内容,包含填写链接。"""
url = f"{_COURSE_BASE_URL}/save?group_id={record.group_id}"
return f"【系统提醒】您还未绑定手机号,请点击下方链接完成绑定:\n\n{url}\n"
def _build_services():
db = SessionLocal()
client = HttpWeComSyncClient()
sync_service = WeComSyncService(db, client, NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(
db,
client,
sync_service,
batch_dispatcher=HttpChatCompletionsBatchDispatcher(),
)
customer_info_service = CustomerInfoService(db)
weekly_report_service = WeeklyReportService(db)
return db, sync_service, orchestration_service, customer_info_service, weekly_report_service
def run_job(job_key: str) -> None:
db, sync_service, orchestration_service, customer_info_service, weekly_report_service = _build_services()
token = set_job_log_context(job_key)
try:
config = sync_service.ensure_job_config(job_key)
if not config.enabled:
logger.info(format_job_log("任务已禁用,跳过执行"))
return
logger.info(format_job_log("任务开始: %s" % JOB_NAME_MAP.get(job_key, job_key)))
if job_key == "sync_wecom_bots_groups_messages":
bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all() if item.bot_id]
if bot_ids:
logger.info(
format_job_log("开始同步机器人与客户群消息,候选机器人数量=%s" % len(bot_ids))
)
result = sync_service.sync_wecom_bots_groups_messages(
bot_ids=bot_ids,
start_time=None,
end_time=None,
)
count = sum(result.values())
elif job_key == "sync_customer_groups":
logger.info(format_job_log("开始处理一客一群编排"))
result = orchestration_service.sync_customer_groups(bot_ids=None)
count = sum(result.values())
elif job_key == "dispatch_customer_group_messages":
count = orchestration_service.dispatch_customer_group_messages(bot_ids=None)
elif job_key == "sync_customer_group_phones":
count = _run_sync_customer_group_phones(customer_info_service)
elif job_key == "daily_phone_push":
count = _run_daily_phone_push(customer_info_service)
elif job_key == "weekly_customer_group_report":
count = _run_weekly_customer_group_report(weekly_report_service)
else:
raise ValueError(f"Unsupported job_key: {job_key}")
sync_service.mark_job_result(job_key, "success", None)
logger.info(format_job_log("任务完成: processed_count=%s" % count))
except WeComSyncClientError as exc:
sync_service.mark_job_result(job_key, "failed", str(exc))
logger.exception(format_job_log("任务执行失败,外部接口调用异常"))
except Exception as exc: # pragma: no cover
sync_service.mark_job_result(job_key, "failed", str(exc))
logger.exception(format_job_log("任务执行失败,出现未处理异常"))
finally:
reset_job_log_context(token)
db.close()
def _run_sync_customer_group_phones(service: CustomerInfoService) -> int:
"""执行同步 + 同步触发推送。"""
affected = service.sync_from_customer_groups()
candidates = service.get_push_candidates(mode="sync")
for record in candidates:
if _do_push(record, _push_content(record)):
service.mark_pushed(record)
logger.info("同步触发推送: candidates=%s", len(candidates))
return affected
def _run_daily_phone_push(service: CustomerInfoService) -> int:
"""执行每日 9 点推送。"""
candidates = service.get_push_candidates(mode="daily")
for record in candidates:
if _do_push(record, _push_content(record)):
service.mark_pushed(record)
logger.info("每日推送: pushed=%s", len(candidates))
return len(candidates)
def _run_weekly_customer_group_report(service: WeeklyReportService) -> int:
"""执行每周一客户群机器人周报推送。"""
result = service.run_and_send()
if result["send_result"]["success"]:
logger.info(format_job_log("客户群周报推送成功: stats=%s" % result["stats"]))
return 1
logger.error(format_job_log("客户群周报推送失败: %s" % result["send_result"]))
return 0
def send_im_message(
bot_id: str,
group_id: str,
content: str,
msg_type: str = "text",
) -> bool:
"""发送 IM 消息到指定群(可服用)。
Args:
bot_id: 机器人账号
group_id: 目标群 contact_id
content: 消息正文
msg_type: 消息类型,默认 text
Returns:
True 发送成功 / False 发送失败
"""
settings = ConfigLoader().load_settings()
base_url = os.getenv("IM_BASE_URL", settings.im.base_url)
api_key = os.getenv("IM_API_KEY", settings.im.api_key) or settings.im.api_key
payload = {
"contact_id": group_id,
"content": content,
"bot_id": bot_id,
"msg_type": msg_type,
"biz_rela_no": f"biz-msg-{int(time.time() * 1000)}",
}
headers = {"Content-Type": "application/json"}
if api_key:
headers["X-Api-Key"] = api_key
url = f"{base_url}/api/v1/business/messages/send"
try:
resp = httpx.post(url, json=payload, headers=headers, timeout=10)
resp.raise_for_status()
logger.info("IM 消息发送成功: group_id=%s", group_id)
return True
except Exception:
logger.exception("IM 消息发送失败: group_id=%s", group_id)
return False
def _do_push(record, content: str) -> bool:
"""向群发送消息(兼容旧逻辑,查 DB 获取 bot_id 后委托 send_im_message)。"""
db = SessionLocal()
try:
cg = db.query(WeComCustomerGroup).filter(
WeComCustomerGroup.group_id == record.group_id,
WeComCustomerGroup.is_deleted == False,
).first()
if not cg or not cg.bot_id:
logger.warning("未找到群对应的 bot_id: group_id=%s", record.group_id)
return False
return send_im_message(cg.bot_id, record.group_id, content)
finally:
db.close()