Commit 9c33950b by 黄南光

改成群发

1 parent 990ca862
......@@ -52,6 +52,7 @@ chmod +x start.sh
- 换环境:`.env` 换成对应那一块(`.env.example` 里两块都写好了),取数端改 `env`;`edge_token` 与 `.env` 的 `EDGE_TOKEN` 一致。
- 开发机实盘演示:双击项目根目录 `start_cloud.bat`(端口、地址、DMS_MODE 都读 `.env`)。`start_cloud_demo.bat` 是本机模拟演示(强制 `DMS_MODE=mock`)。
- 开发机和测试服务器连同一个 MySQL:同时开着时只有一个实例处理企业微信(租约 `rsk_sys_leases`,另一个在总览页显示「待命」,前者停掉 30 秒后自动接手);每个实例只把自己创建的任务派给连着自己的取数端。
- 企业微信会话:`config.toml` 的 `[im]` 里 `contact_id` / `contact_type` 决定交互对象(当前是外部群 `ww_group_external`;改回 1v1 单聊用注释里的 `ww_customer`)。**群聊**只有消息里 `@机器人昵称` 才回复(`bot_name`,逗号分隔可写多个别名,必须填,空则群里不回复;`require_at=false` 可关掉这个限制),交给智能体的文本已去掉 `@昵称`;`allow_senders` 留空表示群内任何人都能触发,填了就只听这些 sender_id。回复不 @ 提问人。
- nginx 反代注意:取数端长轮询 `GET /api/edge/tasks/next?wait=25`,`proxy_read_timeout` 要大于 40 秒(默认 60 秒可以);
截图上传走 `POST /api/edge/tasks/<id>/file`,`client_max_body_size` 建议 ≥ 20m。
- 域名的 HTTPS 证书必须包含对应域名(取数端默认校验证书;菜单 9 网络诊断能看到证书是否匹配)。
......
......@@ -26,12 +26,19 @@ enabled = true
api_base = "https://imhub.glsx.com.cn/api"
channel = "yjy_ww"
bot_id = "5c16a716f61e4b4989efce9c295b964b"
# 要交互的联系人(1v1 单聊)
contact_id = "7881301499187840"
contact_type = "ww_customer"
contact_name = "计划员"
# 只处理这些 sender_id 发来的消息(逗号分隔;留空 = 只处理 contact_id 本人)
# 要交互的会话:外部群演示
contact_id = "R:10944282164186146"
contact_type = "ww_group_external"
contact_name = "补货群"
# 改回 1v1 单聊时用下面两行替换上面的 contact_id / contact_type:
# contact_id = "7881301499187840"
# contact_type = "ww_customer"
# 只处理这些 sender_id 发来的消息(逗号分隔;留空 = 单聊只处理 contact_id 本人 / 群聊不限发言人)
allow_senders = ""
# 群聊:机器人在群里的昵称(消息里出现 @昵称 才算 @ 到自己;逗号分隔可写多个别名)。留空则群里不会回复
bot_name = ""
# 群聊是否必须 @ 机器人才回复(单聊不受影响)
require_at = true
poll_seconds = 3
# 截图发送方式:upload = 先传网关 OSS 拿公网地址再发(云端无公网时必须用这个);url = 直接发云端截图地址
image_mode = "upload"
......
......@@ -8,6 +8,7 @@
"""
from __future__ import annotations
import re
import threading
import time
from pathlib import Path
......@@ -68,6 +69,28 @@ def configured() -> tuple[bool, str]:
return True, ""
def is_group() -> bool:
return "group" in str(S.get("im.contact_type") or "").lower()
def needs_at() -> bool:
"""群聊且要求 @ 机器人才回复。"""
return is_group() and bool(S.get("im.require_at"))
def strip_at_bot(text: str) -> str | None:
"""文本里 @ 了机器人(im.bot_name,多个别名逗号分隔)→ 返回去掉 @昵称 后的正文;没 @ 到返回 None。
企微 @ 后面跟的是特殊空格(U+2005 / U+00A0),一并去掉。"""
names = S.list("im.bot_name")
if not names:
return None
pat = re.compile("@(?:" + "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True)) + r")[\s   ]*",
re.IGNORECASE)
if not pat.search(text):
return None
return pat.sub("", text).strip()
def send_text(text: str) -> tuple[bool, str]:
ok, why = configured()
if not ok:
......@@ -117,7 +140,7 @@ def send_image(path: Path, public_url: str = "") -> tuple[bool, str]:
def fetch_msgs(start: str, end: str) -> list[dict] | None:
url = (f"{_api()}/core/msgs?channel={S.get('im.channel')}&bot_id={S.get('im.bot_id')}"
f"&contact_id={S.get('im.contact_id')}&start_time={quote(start)}&end_time={quote(end)}&limit=50&offset=0")
f"&contact_id={quote(str(S.get('im.contact_id')), safe='')}&start_time={quote(start)}&end_time={quote(end)}&limit=50&offset=0")
try:
r = requests.get(url, headers=_headers(), timeout=TIMEOUT)
if r.status_code != 200:
......
......@@ -2,8 +2,9 @@
过滤规则(来自 demo/im_server/compat.parse_msg,已实测 yjy_ww 数据):
* sender_type 必须为 0(1 = 机器人自己发的 / 发送回执 robot.msg.send.confirm)
* sender_id 必须在白名单(默认只有联系人本人 contact_id)
* sender_id 必须在白名单(单聊默认只有联系人本人 contact_id;群聊没填白名单则不限发言人)
* 只处理文字;msg_time 超过 5 分钟的旧消息不处理
* 群聊(contact_type 含 group)且 im.require_at:文本里必须有 @机器人昵称(im.bot_name)才处理,并去掉 @昵称 再交给 Agent
首次启动时把现有历史全部标成已读、不触发,避免把旧消息当新指令。
多个云端连同一个 MySQL(开发机 + 测试服务器)时,只有持有租约 im-poller 的实例拉消息,
......@@ -33,6 +34,8 @@ class Poller(threading.Thread):
self.loop = loop
self._halt = threading.Event()
self._seeded = False
self._logged_raw = False
self._warned_name = False
self.status = {"last_poll": "", "last_error": "", "received": 0, "fails": 0, "standby": ""}
def stop(self) -> None:
......@@ -63,9 +66,12 @@ class Poller(threading.Thread):
events.log.error("[im] 轮询异常(下轮继续):%s", e)
self._halt.wait(max(1.0, float(S.get("im.poll_seconds") or 3)))
def _allowed(self) -> set[str]:
def _allowed(self) -> set[str] | None:
"""None = 不限发言人(群聊且没填白名单)。"""
allow = set(S.list("im.allow_senders"))
return allow or {str(S.get("im.contact_id"))}
if allow:
return allow
return None if gateway.is_group() else {str(S.get("im.contact_id"))}
def poll_once(self) -> int:
if not gateway.configured()[0]:
......@@ -106,12 +112,30 @@ class Poller(threading.Thread):
continue
sid = str(m.get("sender_id") or "")
text = (m.get("text") or "").strip()
if sid not in allow:
if allow is not None and sid not in allow:
events.emit(f"忽略白名单外的发言人 {m.get('sender')}({sid})", "warn", source="im")
continue
if (m.get("msg_type") or "text").lower() != "text" or not text:
events.emit(f"忽略非文字消息({m.get('msg_type')})", "warn", source="im")
if not gateway.needs_at(): # 群里的图片、表情很多,不逐条提示
events.emit(f"忽略非文字消息({m.get('msg_type')})", "warn", source="im")
continue
if gateway.is_group() and not self._logged_raw:
self._logged_raw = True
events.log.info("[im] 首条群消息原始数据(核对 @ 格式用):%s", m)
if gateway.needs_at():
if not S.list("im.bot_name"):
if not self._warned_name:
self._warned_name = True
events.emit("群聊需要 @ 机器人才回复,但没配置机器人群昵称(设置 im.bot_name),暂不回复", "warn", source="im")
continue
stripped = gateway.strip_at_bot(text)
if stripped is None:
events.log.debug("[im] 群消息未 @ 机器人,忽略:%s", text[:60])
continue
if not stripped:
events.log.debug("[im] 只 @ 了机器人没有内容,忽略")
continue
text = stripped
try:
t = dt.datetime.fromisoformat(str(m.get("msg_time")).replace("Z", "+00:00")).timestamp()
if abs(time.time() - t) > LOOKBACK:
......
......@@ -24,7 +24,7 @@ DEFAULTS = {
"edge.timeout_screenshot_po": 240, "edge.timeout_sync_stock_full": 3600, "edge.timeout_check": 300,
"im.enabled": True, "im.api_base": "https://imhub.glsx.com.cn/api", "im.channel": "yjy_ww", "im.bot_id": "",
"im.contact_id": "", "im.contact_type": "ww_customer", "im.contact_name": "计划员", "im.allow_senders": "",
"im.poll_seconds": 3, "im.image_mode": "upload",
"im.bot_name": "", "im.require_at": True, "im.poll_seconds": 3, "im.image_mode": "upload",
"llm.model": "qwen-plus", "llm.base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"llm.temperature": 0.1, "llm.fallback_rules": True,
"business.warehouses": "GTMC广州,华南GTMC", "business.supplier_code": "APC40", "business.order_type": "S", "business.in_transit_field": "trans_shipped",
......@@ -45,7 +45,9 @@ EDITABLE = [
("im.contact_id", "交互联系人 contact_id"),
("im.contact_type", "联系人类型"),
("im.contact_name", "联系人称呼"),
("im.allow_senders", "只听这些 sender_id(逗号分隔,空=只听联系人本人)"),
("im.allow_senders", "只听这些 sender_id(逗号分隔,空=单聊只听联系人本人 / 群聊不限发言人)"),
("im.bot_name", "机器人在群里的昵称(群聊判断是否被 @;逗号分隔可写多个别名)"),
("im.require_at", "群聊是否必须 @ 机器人才回复 true/false"),
("im.poll_seconds", "收消息轮询间隔(秒)"),
("im.image_mode", "截图发送方式 upload / url"),
("server.public_base_url", "对外地址(单据链接;空=自动局域网 IP)"),
......
......@@ -9,6 +9,8 @@ import tempfile
import unittest
from pathlib import Path
from sqlalchemy import event
TMP = tempfile.mkdtemp(prefix="cloud_test_")
os.environ["DB_URL"] = f"sqlite:///{Path(TMP) / 't.db'}"
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
......@@ -267,6 +269,81 @@ class LeaseSeedTests(unittest.TestCase):
[("019990A115", "用户手册", 10), ("0400007516", "卡子", 10)])
def _sqlite_insert_ignore(conn, cursor, statement, parameters, context, executemany):
return statement.replace("INSERT IGNORE", "INSERT OR IGNORE"), parameters # poller 用的是 MySQL 语法
class GroupAtTests(unittest.IsolatedAsyncioTestCase):
KEYS = ("im.enabled", "im.bot_id", "im.contact_id", "im.contact_type", "im.bot_name", "im.require_at",
"im.allow_senders")
def setUp(self):
S.overrides.update({"im.enabled": "true", "im.bot_id": "b1", "im.contact_id": "R:1",
"im.contact_type": "ww_group_external", "im.bot_name": "补货助手,小补", "im.require_at": "true",
"im.allow_senders": ""})
self.n = 0
event.listen(db.engine, "before_cursor_execute", _sqlite_insert_ignore, retval=True)
def tearDown(self):
event.remove(db.engine, "before_cursor_execute", _sqlite_insert_ignore)
for k in self.KEYS:
S.overrides.pop(k, None)
def test_strip_at_bot(self):
f = workflow.gateway.strip_at_bot
self.assertEqual(f("@补货助手 帮我查库存"), "帮我查库存")
self.assertEqual(f("@补货助手 帮我查库存"), "帮我查库存")
self.assertEqual(f("帮我查库存 @小补"), "帮我查库存")
self.assertEqual(f("@补货助手"), "")
self.assertIsNone(f("帮我查库存"))
self.assertIsNone(f("@别人 帮我查库存"))
S.overrides["im.bot_name"] = ""
self.assertIsNone(f("@补货助手 帮我查库存"))
async def test_poll_group_only_when_at(self):
from replenish_cloud.im import gateway
from replenish_cloud.im.poller import Poller
got = []
async def on_text(text, sender):
got.append((text, sender))
def msg(text, sid="u1"):
self.n += 1
return {"msg_id": f"g{self.n}-{text}", "sender_type": 0, "sender_id": sid, "sender": "张三", "text": text,
"msg_type": "text"}
batch = [msg("大家好"), msg("@补货助手 帮我查库存"), msg("@补货助手 "), msg("@小补 确认", sid="u2")]
old = gateway.fetch_msgs
gateway.fetch_msgs = lambda s, e: batch
try:
p = Poller(on_text, asyncio.get_running_loop())
p._seeded = True
self.assertEqual(p.poll_once(), 2)
await asyncio.sleep(0.05)
self.assertEqual(got, [("帮我查库存", "张三"), ("确认", "张三")])
S.overrides["im.allow_senders"] = "u2" # 填了白名单就只听白名单
batch[:] = [msg("@补货助手 状态", sid="u1"), msg("@补货助手 进度", sid="u2")]
self.assertEqual(p.poll_once(), 1)
finally:
gateway.fetch_msgs = old
async def test_single_chat_unchanged(self):
from replenish_cloud.im import gateway
from replenish_cloud.im.poller import Poller
S.overrides.update({"im.contact_type": "ww_customer", "im.contact_id": "7881"})
old = gateway.fetch_msgs
gateway.fetch_msgs = lambda s, e: [
{"msg_id": "s1", "sender_type": 0, "sender_id": "7881", "sender": "计划员", "text": "补货", "msg_type": "text"},
{"msg_id": "s2", "sender_type": 0, "sender_id": "other", "sender": "路人", "text": "补货", "msg_type": "text"}]
try:
p = Poller(lambda t, s: asyncio.sleep(0), asyncio.get_running_loop())
p._seeded = True
self.assertEqual(p.poll_once(), 1)
finally:
gateway.fetch_msgs = old
class SchemaTests(unittest.TestCase):
def test_every_table_and_column_has_comment(self):
for t in db.md.sorted_tables:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!