Commit 1e7ca9c2 by sunqi02

feat: add push_type routing to PhoneMessageSender

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent e0f6a315
...@@ -17,43 +17,96 @@ class SendByPhoneError(Exception): ...@@ -17,43 +17,96 @@ class SendByPhoneError(Exception):
class PhoneMessageSender: class PhoneMessageSender:
"""通过手机号查找群组并发送消息。""" """通过手机号 + push_type 查找群组并发送消息。"""
# language=MySQL
_QUERY = """
SELECT cgp.group_id, wcg.bot_id
FROM customer_group_phones cgp
JOIN wecom_customer_groups wcg ON cgp.group_id = wcg.group_id
WHERE cgp.phone = :phone AND wcg.is_deleted = 0
"""
def __init__(self, db: Session, im_service: IMService): def __init__(self, db: Session, im_service: IMService):
self.db = db self.db = db
self.im_service = im_service self.im_service = im_service
def _lookup_targets(self, phone: str) -> List[Tuple[str, str]]: def _lookup_push_targets(self, phone: str, push_type: str) -> Tuple[str, int, List[Tuple[str, str]]]:
"""联表查询获取 phone 对应的 (group_id, bot_id) 对。""" """三步查询链。
rows = self.db.execute(text(self._QUERY), {"phone": phone}).fetchall()
if not rows: Returns:
(bot_id, agents_id, [(group_id, bot_id), ...])
bot_id: 实际推送用的机器人ID
agents_id: 仅用于日志记录
targets: (group_id, bot_id) 对列表,已过滤 member_bot_ids
Raises:
SendByPhoneError: push_type 无效或 phone 未绑定群
"""
# Step 1: push_type → managed_user_id → bot_id
route_row = self.db.execute(
text("""
SELECT ptr.agents_id, wb.bot_id
FROM push_type_routes ptr
JOIN wecom_bots wb ON ptr.managed_user_id = wb.id
WHERE ptr.push_type = :push_type AND ptr.is_active = 1
"""),
{"push_type": push_type},
).fetchone()
if not route_row:
raise SendByPhoneError(f"未知推送类型: {push_type}")
agents_id: int = int(route_row.agents_id)
bot_id: str = route_row.bot_id
# Step 2: phone → [group_id, ...]
group_rows = self.db.execute(
text("""
SELECT cgp.group_id
FROM customer_group_phones cgp
WHERE cgp.phone = :phone
"""),
{"phone": phone},
).fetchall()
if not group_rows:
raise SendByPhoneError("号码未绑定微信群") raise SendByPhoneError("号码未绑定微信群")
return [(row.group_id, row.bot_id) for row in rows] # type: ignore[union-attr]
async def send_by_phone(self, phone: str, content: str) -> Dict[str, object]: # Step 3: 逐群查 member_bot_ids,过滤含 bot_id 的群
"""按手机号查找群组并发送消息。""" # 单 phone 通常 1-3 个群,逐条查询比 IN + JSON_CONTAINS 更清晰
targets = self._lookup_targets(phone) targets: List[Tuple[str, str]] = []
for row in group_rows:
wcg = self.db.execute(
text("""
SELECT member_bot_ids
FROM wecom_customer_groups
WHERE group_id = :group_id AND is_deleted = 0
"""),
{"group_id": row.group_id},
).fetchone()
if wcg and bot_id in (wcg.member_bot_ids or []):
targets.append((row.group_id, bot_id))
return bot_id, agents_id, targets
async def send_by_phone(self, phone: str, content: str, push_type: str) -> Dict[str, object]:
"""按手机号和推送类型查找群组并发送消息。"""
bot_id, agents_id, targets = self._lookup_push_targets(phone, push_type)
if not targets:
return {
"success": True,
"message": "无匹配的可推送群组",
"details": [],
}
results: List[Tuple[str, bool, str]] = [] results: List[Tuple[str, bool, str]] = []
for group_id, bot_id in targets: for group_id, bid in targets:
try: try:
resp = await self.im_service.send_message( resp = await self.im_service.send_message(
bot_id=bot_id, bot_id=bid,
content=content, content=content,
contact_id=group_id, contact_id=group_id,
) )
logger.info("发送成功: group_id=%s, bot_id=%s, resp=%s", group_id, bot_id, resp) logger.info("发送成功: group_id=%s, bot_id=%s, agents_id=%s, resp=%s",
group_id, bid, agents_id, resp)
results.append((group_id, True, "ok")) results.append((group_id, True, "ok"))
except IMServiceError as e: except IMServiceError as e:
logger.error("发送失败: group_id=%s, bot_id=%s, err=%s", group_id, bot_id, e) logger.error("发送失败: group_id=%s, bot_id=%s, agents_id=%s, err=%s",
group_id, bid, agents_id, e)
results.append((group_id, False, str(e))) results.append((group_id, False, str(e)))
success_count = sum(1 for _, ok, _ in results if ok) success_count = sum(1 for _, ok, _ in results if ok)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!