为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人; 本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。 群与身份: - 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、 @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。 - 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。 - 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。 - 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。 - 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存), 否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。 - 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。 报价单: - 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出; 多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。 - 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。 - 空运舱位只回一条时直接出该条报价,不再发选择卡。 字段与金额: - 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。 - 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重); TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。 - 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费, 燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。 - 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。 - 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress), 禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。 - 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。 - 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。 主账与后台: - 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。 - 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。 - 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。 - 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。 文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。 Co-authored-by: Cursor <cursoragent@cursor.com>
639 lines
25 KiB
Python
639 lines
25 KiB
Python
"""
|
||
协同群 BOT 模式与「当前工单关联」短协调(对齐 prompt/14)。
|
||
|
||
为什么需要:
|
||
- 陆运/海运/空运产品协同群里,智价通应用只负责拉群、解散群;
|
||
报价识别、发报价单、工单状态跟进等对话事务由智价通BOT负责。
|
||
- 群里没有 @BOT 的文字,BOT 不回应;并且要「断开当前工单关联」,
|
||
这样下一条 @BOT 但没有带工单号的消息,才会提示销售重新下达任务。
|
||
- 工单号关联是短生命周期协调数据,不是六态;六态只存主账。
|
||
因此这里只放 Redis(带环境前缀)+进程内兜底,不写 MySQL、不写 PG checkpoint。
|
||
|
||
存储:
|
||
- group_bot:rooms 已由 BOT 接管的群,值形如 "chat1:SEA,chat2:AIR"。
|
||
- group_bot:active_wo:<chat_id> 该群当前关联的工单号,24 小时过期。
|
||
- group_bot:at_burst:<chat_id> 「@BOT 指令窗口」起点时间戳(30 分钟),
|
||
群里 @BOT 之后到下一句普通文字之前算同一次指令,
|
||
窗口内的图片/Excel/PDF 才当这次询价的材料。
|
||
- group_bot:pending_media:<chat_id> 窗口外先到的群图片/附件(10 分钟),
|
||
等紧接着的 @BOT 认领后补办(企微里附件不能被 @)。
|
||
- group_bot:aibot_text:<chat_id> AIBOT 刚办过的群文字指纹(5 分钟),
|
||
只用来挡住会话存档把同一句再办一遍。
|
||
|
||
线程:
|
||
- 进程内 set/dict 用一把小锁只保护这两个字典,不串行任何工单业务。
|
||
- Redis 客户端本身是连接池,可被 HTTP/Worker 多线程共用。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import threading
|
||
import time
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_ROOM_KEY = "group_bot:room"
|
||
_ROOMS_KEY = "group_bot:rooms" # 兼容早期集合写法,只读不写
|
||
_ACTIVE_KEY = "group_bot:active_wo"
|
||
_ACTIVE_TTL_SECONDS = 24 * 3600
|
||
# AIBOT 已办过的群文字指纹:只覆盖存档延迟窗口,过期即失效。
|
||
_HANDLED_KEY = "group_bot:aibot_text"
|
||
_HANDLED_TTL_SECONDS = 300
|
||
# 去重放行标记后缀:AIBOT 那条身份不可信(加密 ID 换不出明文)时,允许存档补办。
|
||
_RETRY_SUFFIX = "#retry"
|
||
# 群标记跟着群走,给 180 天;到期后旧群再被 @ 会按主账工单自动补回。
|
||
_ROOM_TTL_SECONDS = 180 * 24 * 3600
|
||
# 「这个群真的收到过 AIBOT 回调」——等同于「智价通BOT 已在本群」。
|
||
# 用途:@会话存档账号的兜底触发只在 BOT 不在本群时生效,避免两套回话并存。
|
||
# 30 天过期:BOT 被移出群后,30 天后兜底会重新接管这个群。
|
||
_BOT_SEEN_KEY = "group_bot:bot_seen"
|
||
_BOT_SEEN_TTL_SECONDS = 30 * 24 * 3600
|
||
# 「@BOT 指令窗口」:群里 @BOT 之后、到下一句普通文字之前这段时间。
|
||
# 产品口径(2026-11-21):群附件(Excel/PDF)和图片本身无法 @,
|
||
# 只能靠这个窗口判断「是不是这次 @BOT 指令要发的材料」;窗口外一律静默。
|
||
_AT_BURST_KEY = "group_bot:at_burst"
|
||
_AT_BURST_TTL_SECONDS = 30 * 60
|
||
# 「待归属的群附件」:窗口外先到、还没遇到 @ 的图片/Excel/PDF。
|
||
# 为什么必须缓冲而不是直接丢:企微里群附件根本不能被 @,销售的真实习惯是
|
||
# 「先发文件、再 @ 机器人说你要干什么」;只按「先 @ 后发」判断会把真业务全部丢掉
|
||
# (2026-11-21 真机:两个报价 Excel + @会话存档机器人,BOT 一声不吭)。
|
||
_PENDING_KEY = "group_bot:pending_media"
|
||
# 缓冲只等「紧接着的那次 @」;10 分钟没等到就过期,避免十几分钟前的旧文件被误认。
|
||
_PENDING_TTL_SECONDS = 600
|
||
# 单群最多记 5 条:一次指令不会发几十个附件,超出的按最新保留。
|
||
_PENDING_MAX = 5
|
||
|
||
# 进程内兜底:Redis 不可用(本地单测、memory 后端)时也能表达「BOT 已接管」。
|
||
_local_rooms: dict[str, str] = {}
|
||
_local_active: dict[str, str] = {}
|
||
# 同群最近一条已由 AIBOT 办过的文字指纹(只留最后一条,够挡存档重复)。
|
||
_local_handled: dict[str, str] = {}
|
||
# 进程内「BOT 已在本群出现」兜底标记,语义同 _BOT_SEEN_KEY。
|
||
_local_bot_seen: set[str] = set()
|
||
# 进程内「@BOT 指令窗口」兜底:值是写入时的 epoch 秒,读侧自行判过期。
|
||
_local_at_burst: dict[str, int] = {}
|
||
# 进程内「待归属群附件」兜底:值是 (写入 epoch 秒, InboundMessage.to_dict() 列表)。
|
||
_local_pending: dict[str, tuple[int, list[dict]]] = {}
|
||
_guard = threading.Lock()
|
||
|
||
|
||
def _client():
|
||
"""懒取 Redis 门面;连不上返回 None,让调用方走进程内兜底。"""
|
||
try:
|
||
from agent.redis_coord.runtime import get_redis_runtime
|
||
|
||
return get_redis_runtime().client
|
||
except Exception: # noqa: BLE001 - 协调数据不可用不能阻断业务
|
||
logger.warning("group_bot: Redis 不可用,使用进程内兜底", exc_info=True)
|
||
return None
|
||
|
||
|
||
def _parse_rooms(raw: object) -> dict[str, str]:
|
||
"""把 "chat1:SEA,chat2:AIR" 解析成 dict;坏数据直接跳过。"""
|
||
rooms: dict[str, str] = {}
|
||
for item in str(raw or "").split(","):
|
||
text = item.strip()
|
||
if not text:
|
||
continue
|
||
chat_id, _, line = text.partition(":")
|
||
chat_id = chat_id.strip()
|
||
if chat_id:
|
||
rooms[chat_id] = (line or "").strip().upper()
|
||
return rooms
|
||
|
||
|
||
def mark_group_bot(
|
||
chat_id: str, business_line: str = "", work_order_no: str = ""
|
||
) -> None:
|
||
"""
|
||
标记某个协同群由智价通BOT接管。
|
||
|
||
参数:
|
||
- chat_id:企微群 chat_id。
|
||
- business_line:AIR / SEA / LAND / MULTI,用于把群消息路由到对应 handler。
|
||
- work_order_no:建群/绑群时已知的工单号。带了就同时建立「当前单关联」,
|
||
这样建群后第一条 @BOT(可能只说「成交」)不用重新带号;
|
||
之后群里出现非 @BOT 文字才断开。
|
||
副作用:写进程内 dict 与 Redis 短键;失败只告警,不影响建群/回执。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return
|
||
line = (business_line or "").strip().upper()
|
||
with _guard:
|
||
_local_rooms[room] = line or _local_rooms.get(room, "")
|
||
if (work_order_no or "").strip():
|
||
# 建群/绑群即建立当前单关联;之后非 @BOT 文字才断开。
|
||
set_active_work_order(room, work_order_no)
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
# 一个群一个键:并发建两个群不会互相覆盖。
|
||
client.raw.set(client.key(_ROOM_KEY, room), line, ex=_ROOM_TTL_SECONDS)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 标记群失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def group_bot_line(chat_id: str) -> str:
|
||
"""
|
||
返回该群的业务线(AIR/SEA/LAND/MULTI);空串表示还没标记为 BOT 群。
|
||
|
||
注意:空串不等于「非 BOT 群」,旧群第一次收到 BOT 消息时由
|
||
`ensure_group_bot_line` 按主账工单补齐。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return ""
|
||
with _guard:
|
||
cached = _local_rooms.get(room)
|
||
if cached is not None:
|
||
return cached
|
||
client = _client()
|
||
if client is None:
|
||
return ""
|
||
try:
|
||
line = str(client.raw.get(client.key(_ROOM_KEY, room)) or "").strip().upper()
|
||
if not line:
|
||
# 兼容早期集合写法(只读);新写入一律用 per-group 键。
|
||
line = _parse_rooms(client.raw.get(client.key(_ROOMS_KEY))).get(room, "")
|
||
if line:
|
||
with _guard:
|
||
_local_rooms[room] = line
|
||
return line
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读群标记失败 chat=%s", room, exc_info=True)
|
||
return ""
|
||
|
||
|
||
def is_group_bot(chat_id: str) -> bool:
|
||
"""该群是否已由 BOT 接管;空串视为未接管(兼容旧 appchat 群)。"""
|
||
return bool(group_bot_line(chat_id))
|
||
|
||
|
||
def ensure_group_bot_line(chat_id: str, fallback: str = "AIR") -> str:
|
||
"""
|
||
旧群第一次收到 BOT 消息时补齐业务线。
|
||
|
||
优先按主账 `find_by_collab_chat` 查真实业务线;查不到用 fallback(空运)。
|
||
副作用:可能调用一次主账 HTTP;只在首次发生。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
existing = group_bot_line(room)
|
||
if existing:
|
||
return existing
|
||
line = ""
|
||
try:
|
||
from agent.policy.air_text_flow import get_air_text_flow
|
||
|
||
ledger = get_air_text_flow().ledger
|
||
finder = getattr(ledger, "find_by_collab_chat", None)
|
||
hit = finder(chat_id=room) if callable(finder) else None
|
||
if hit is not None:
|
||
from agent.policy.sea_group_ops import ticket_view
|
||
|
||
view = ticket_view(hit)
|
||
line = str(view.get("business_line") or "").strip().upper()
|
||
wo = str(view.get("work_order_no") or "").strip()
|
||
# 老群第一次被 BOT 接管:把已绑工单补成当前单,避免第一条没带号就被要求重发。
|
||
if wo and not get_active_work_order(room):
|
||
set_active_work_order(room, wo)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 查群业务线失败 chat=%s", room, exc_info=True)
|
||
line = line or (fallback or "").strip().upper()
|
||
mark_group_bot(room, line)
|
||
return line
|
||
|
||
|
||
def _text_fingerprint(text: str) -> str:
|
||
"""
|
||
群文字指纹:去空白后取 sha1 前 20 位。
|
||
|
||
为什么要去空白:同一句在 AIBOT 回调与会话存档里,换行/空格可能被平台改写,
|
||
原样比较会漏判,导致同一句被办两遍。
|
||
"""
|
||
compact = "".join(str(text or "").split())
|
||
return hashlib.sha1(compact.encode("utf-8")).hexdigest()[:20]
|
||
|
||
|
||
def mark_bot_text_handled(chat_id: str, text: str) -> None:
|
||
"""
|
||
记下「这条群文字已由 AIBOT 回调办过」。
|
||
|
||
用途:会话存档会旁听到同一句 @BOT(尤其空运),若再走一遍 handler
|
||
就会把同一份工单摘要/模板发两遍(2026-11-19 测服真机复现)。
|
||
TTL 5 分钟只覆盖存档延迟窗口,过期即失效,不当业务状态用。
|
||
"""
|
||
_write_handled(chat_id, text, retry_archive=False)
|
||
|
||
|
||
def allow_archive_retry(chat_id: str, text: str) -> None:
|
||
"""
|
||
撤销「这句已办过」的去重,允许会话存档那条(明文身份)再办一遍。
|
||
|
||
为什么需要(2026-11-19 真机 WO202611190016):
|
||
AIBOT 回调给的是加密 open_userid,被判「不是本单销售」而拒绝;约 15 秒后
|
||
会话存档带着明文 userid 到达,本该补办,却被上面那条去重直接丢掉 ——
|
||
结果是销售明明本人点成交,群里却一直回「只有负责该工单的销售可以确认成交状态」。
|
||
身份换不成明文时,AIBOT 那条的结论不可信,必须让存档补办。
|
||
"""
|
||
_write_handled(chat_id, text, retry_archive=True)
|
||
|
||
|
||
def _write_handled(chat_id: str, text: str, *, retry_archive: bool) -> None:
|
||
"""
|
||
写「已办」标记。retry_archive=True 时打上 `#retry` 后缀,读侧据此不再去重。
|
||
|
||
存储值形如 `abcdef0123456789ab`(去重生效)或 `abcdef0123456789ab#retry`(放行存档)。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
fingerprint = _text_fingerprint(text)
|
||
if not room or not fingerprint:
|
||
return
|
||
value = fingerprint + _RETRY_SUFFIX if retry_archive else fingerprint
|
||
with _guard:
|
||
_local_handled[room] = value
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.set(client.key(_HANDLED_KEY, room), value, ex=_HANDLED_TTL_SECONDS)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 记 AIBOT 已办文字失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def bot_text_handled(chat_id: str, text: str) -> bool:
|
||
"""
|
||
这条群文字是否已经被 AIBOT 回调办过(同群 5 分钟内同文)。
|
||
|
||
带 `#retry` 后缀表示「AIBOT 那条身份不可信,允许存档补办」,这里返回 False。
|
||
Redis 不可用时退回进程内记录;两者都没有就返回 False,让存档按老逻辑补听。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
fingerprint = _text_fingerprint(text)
|
||
if not room or not fingerprint:
|
||
return False
|
||
with _guard:
|
||
cached = str(_local_handled.get(room) or "")
|
||
if cached and _dedupe_on(cached, fingerprint):
|
||
return True
|
||
client = _client()
|
||
if client is None:
|
||
return False
|
||
try:
|
||
value = client.raw.get(client.key(_HANDLED_KEY, room))
|
||
text_value = str(value or "").strip()
|
||
if text_value and _dedupe_on(text_value, fingerprint):
|
||
with _guard:
|
||
_local_handled[room] = text_value
|
||
return True
|
||
return False
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读 AIBOT 已办文字失败 chat=%s", room, exc_info=True)
|
||
return False
|
||
|
||
|
||
def _dedupe_on(stored: str, fingerprint: str) -> bool:
|
||
"""
|
||
存的值是否代表「这句确实办成了、存档不用再来」。
|
||
|
||
只有指纹完全相等、且没打 `#retry` 后缀才算;后缀即「身份不可信,放行存档」。
|
||
"""
|
||
text = (stored or "").strip()
|
||
if not text or text.endswith(_RETRY_SUFFIX):
|
||
return False
|
||
return text == fingerprint
|
||
|
||
|
||
def handled_marker(chat_id: str) -> str:
|
||
"""
|
||
只读:取出该群当前「AIBOT 已办文字」标记,供排障日志使用。
|
||
|
||
为什么需要:会话存档那条被去重丢掉时,只有把标记值(指纹 / 是否带 #retry)
|
||
与存档那句的指纹放在一起看,才能判断是「真的重复」还是「错误挡住」。
|
||
不参与任何业务判断,验证完随探针一起删。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return ""
|
||
client = _client()
|
||
if client is None:
|
||
with _guard:
|
||
return str(_local_handled.get(room) or "")
|
||
try:
|
||
return str(client.raw.get(client.key(_HANDLED_KEY, room)) or "").strip()
|
||
except Exception: # noqa: BLE001
|
||
return ""
|
||
|
||
|
||
def set_active_work_order(chat_id: str, work_order_no: str) -> None:
|
||
"""记录该群当前关联的工单号(@BOT 且带号时调用)。"""
|
||
room = (chat_id or "").strip()
|
||
work_order_no = (work_order_no or "").strip()
|
||
if not room or not work_order_no:
|
||
return
|
||
with _guard:
|
||
_local_active[room] = work_order_no
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.set(
|
||
client.key(_ACTIVE_KEY, room), work_order_no, ex=_ACTIVE_TTL_SECONDS
|
||
)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 写当前工单失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def get_active_work_order(chat_id: str) -> str:
|
||
"""读该群当前关联的工单号;没有返回空串。"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return ""
|
||
with _guard:
|
||
cached = _local_active.get(room)
|
||
if cached:
|
||
return cached
|
||
client = _client()
|
||
if client is None:
|
||
return ""
|
||
try:
|
||
value = client.raw.get(client.key(_ACTIVE_KEY, room))
|
||
text = str(value or "").strip()
|
||
if text:
|
||
with _guard:
|
||
_local_active[room] = text
|
||
return text
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读当前工单失败 chat=%s", room, exc_info=True)
|
||
return ""
|
||
|
||
|
||
def mark_bot_seen(chat_id: str) -> None:
|
||
"""
|
||
记下「这个群真的收到过 AIBOT 回调」=智价通BOT 已在本群。
|
||
|
||
用途(2026-11-19 产品口径):
|
||
@会话存档账号只能当兜底唤醒,BOT 在群里时不该再用它,
|
||
否则同一个群会出现两套回话身份。30 天过期,BOT 被移出群后兜底能重新接管。
|
||
|
||
副作用:写进程内 set 与 Redis 短键;失败只告警,不影响本条消息处理。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return
|
||
with _guard:
|
||
_local_bot_seen.add(room)
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.set(client.key(_BOT_SEEN_KEY, room), "1", ex=_BOT_SEEN_TTL_SECONDS)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 记 BOT 在群失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def bot_seen(chat_id: str) -> bool:
|
||
"""
|
||
该群是否收到过 AIBOT 回调(即智价通BOT 在群里)。
|
||
|
||
Redis 不可用时只用进程内标记;两者都没有返回 False,
|
||
代表「可能没拉 BOT」,兜底唤醒才允许生效。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return False
|
||
with _guard:
|
||
if room in _local_bot_seen:
|
||
return True
|
||
client = _client()
|
||
if client is None:
|
||
return False
|
||
try:
|
||
value = client.raw.get(client.key(_BOT_SEEN_KEY, room))
|
||
if str(value or "").strip():
|
||
with _guard:
|
||
_local_bot_seen.add(room)
|
||
return True
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读 BOT 在群标记失败 chat=%s", room, exc_info=True)
|
||
return False
|
||
|
||
|
||
def clear_active_work_order(chat_id: str) -> None:
|
||
"""
|
||
断开该群的当前工单关联。
|
||
|
||
触发点:群里出现「没有 @BOT 的文字」——按产品口径,任何非 @ 对话都算打断。
|
||
文件/图片不带 @,不算文字打断,因此调用方只在文字消息时调用。
|
||
|
||
例外(2026-11-19):@会话存档账号的兜底唤醒是明确指令,调用方在走兜底分支时
|
||
不调用本函数,保持当前单关联。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return
|
||
with _guard:
|
||
_local_active.pop(room, None)
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.delete(client.key(_ACTIVE_KEY, room))
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 清除当前工单失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def mark_at_burst(chat_id: str) -> None:
|
||
"""
|
||
进入(或刷新)该群的「@BOT 指令窗口」。
|
||
|
||
为什么需要(2026-11-21 产品口径):
|
||
企微里群附件(Excel/PDF)和图片都不能被 @,只会以普通消息进会话存档;
|
||
所以「这次附件是不是要询价」只能靠上下文判断:同一次指令内 @ 过 BOT,
|
||
之后到下一句普通文字之前发来的附件/图片,才当成这次指令的材料。
|
||
|
||
语义:窗口是「按群」不是「按人」——同事 @BOT 后由另一个人代表发文件也算同一次指令。
|
||
过期:Redis 30 分钟;进程内兜底同样按时间判过期,避免 Redis 挂掉时窗口永久有效。
|
||
|
||
副作用:写进程内 dict 与 Redis 短键;失败只告警,不影响当前消息处理。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return
|
||
now = int(time.time())
|
||
with _guard:
|
||
_local_at_burst[room] = now
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.set(
|
||
client.key(_AT_BURST_KEY, room), str(now), ex=_AT_BURST_TTL_SECONDS
|
||
)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 记 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def in_at_burst(chat_id: str) -> bool:
|
||
"""
|
||
当前是否处在「@BOT 指令窗口」内(@ 之后、下一句普通文字之前)。
|
||
|
||
Redis 不可用时退回进程内时间戳;两者都读不到返回 False,
|
||
也就是「没 @ 过就按静默处理」,宁可少回一句也不主动搭话。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return False
|
||
now = int(time.time())
|
||
with _guard:
|
||
local_ts = int(_local_at_burst.get(room) or 0)
|
||
if local_ts and now - local_ts <= _AT_BURST_TTL_SECONDS:
|
||
return True
|
||
client = _client()
|
||
if client is None:
|
||
return False
|
||
try:
|
||
value = str(client.raw.get(client.key(_AT_BURST_KEY, room)) or "").strip()
|
||
ts = int(value or 0)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||
return False
|
||
if not ts or now - ts > _AT_BURST_TTL_SECONDS:
|
||
return False
|
||
with _guard:
|
||
_local_at_burst[room] = ts
|
||
return True
|
||
|
||
|
||
def clear_at_burst(chat_id: str) -> None:
|
||
"""
|
||
结束该群的「@BOT 指令窗口」。
|
||
|
||
触发点:群里出现「没有 @BOT 的普通文字」——产品口径是「@ 之后到下一句普通文字之前」,
|
||
所以任何非 @ 对话都算这次指令结束,后续附件必须重新 @BOT。
|
||
|
||
例外:AIBOT 已办过的同一句存档回声、解散群口令不算「普通文字」,
|
||
调用方须自行排除(见 dispatch)。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return
|
||
with _guard:
|
||
_local_at_burst.pop(room, None)
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.delete(client.key(_AT_BURST_KEY, room))
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 清除 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def add_pending_media(chat_id: str, payload: dict) -> None:
|
||
"""
|
||
记下一条「窗口外先到」的群图片/附件,等紧接着的 @BOT 认领。
|
||
|
||
为什么要有它(2026-11-21 产品口径「@ 前后」):
|
||
企微群里的 Excel/PDF/图片本身不能被 @,只能整条发出去;销售的习惯是
|
||
「先发文件,再 @机器人 说要干什么」。只按「先 @ 后发」判断会把这类真询价
|
||
全部静默丢掉。因此窗口外先到的附件先缓冲,等 @ 到来时补办一次。
|
||
|
||
参数:
|
||
- chat_id:群 id;空则不记。
|
||
- payload:InboundMessage.to_dict() 结果(含 sender/media/raw,够重放)。
|
||
|
||
副作用:写进程内 dict 与 Redis JSON 字符串键(10 分钟);失败只告警。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room or not isinstance(payload, dict) or not payload:
|
||
return
|
||
entries = _read_pending(room)
|
||
entries.append(payload)
|
||
if len(entries) > _PENDING_MAX:
|
||
entries = entries[-_PENDING_MAX:]
|
||
# 带上写入时间:进程内兜底没有 TTL 扫描,读侧只能靠自带时间戳判过期。
|
||
now = int(time.time())
|
||
with _guard:
|
||
_local_pending[room] = (now, entries)
|
||
client = _client()
|
||
if client is None:
|
||
return
|
||
try:
|
||
client.raw.set(
|
||
client.key(_PENDING_KEY, room),
|
||
json.dumps({"ts": now, "items": entries}, ensure_ascii=False, default=str),
|
||
ex=_PENDING_TTL_SECONDS,
|
||
)
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 记待归属附件失败 chat=%s", room, exc_info=True)
|
||
|
||
|
||
def drain_pending_media(chat_id: str) -> list[dict]:
|
||
"""
|
||
取出并清空该群「待归属的群附件」。
|
||
|
||
只在 @BOT 到来时调用:取到就把它们当成这次指令的材料补办,然后清掉,
|
||
避免同一个文件被下一次 @ 重复处理。两条来源(进程内 / Redis)一起清。
|
||
"""
|
||
room = (chat_id or "").strip()
|
||
if not room:
|
||
return []
|
||
entries = _read_pending(room)
|
||
with _guard:
|
||
_local_pending.pop(room, None)
|
||
client = _client()
|
||
if client is not None:
|
||
try:
|
||
client.raw.delete(client.key(_PENDING_KEY, room))
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 清待归属附件失败 chat=%s", room, exc_info=True)
|
||
return entries
|
||
|
||
|
||
def _read_pending(room: str) -> list[dict]:
|
||
"""
|
||
读该群待归属附件列表(只读,不清)。
|
||
|
||
优先级:进程内 → Redis。进程内没有 TTL 扫描,因此自带时间戳判过期:
|
||
超过 _PENDING_TTL_SECONDS 就当作没有,避免十几分钟前的旧文件被误认领。
|
||
"""
|
||
now = int(time.time())
|
||
with _guard:
|
||
cached = _local_pending.get(room)
|
||
if cached is not None:
|
||
ts, items = cached
|
||
if ts and now - int(ts) <= _PENDING_TTL_SECONDS:
|
||
return [dict(x) for x in items if isinstance(x, dict)]
|
||
with _guard:
|
||
_local_pending.pop(room, None)
|
||
return []
|
||
client = _client()
|
||
if client is None:
|
||
return []
|
||
try:
|
||
raw = client.raw.get(client.key(_PENDING_KEY, room))
|
||
except Exception: # noqa: BLE001
|
||
logger.warning("group_bot 读待归属附件失败 chat=%s", room, exc_info=True)
|
||
return []
|
||
if not raw:
|
||
return []
|
||
try:
|
||
data = json.loads(raw if isinstance(raw, str) else str(raw, "utf-8"))
|
||
except Exception: # noqa: BLE001
|
||
return []
|
||
if not isinstance(data, dict):
|
||
return []
|
||
ts = int(data.get("ts") or 0)
|
||
items = data.get("items")
|
||
if not ts or now - ts > _PENDING_TTL_SECONDS or not isinstance(items, list):
|
||
return []
|
||
entries = [x for x in items if isinstance(x, dict)]
|
||
if entries:
|
||
with _guard:
|
||
_local_pending[room] = (ts, [dict(x) for x in entries])
|
||
return entries
|