- xq0009 收银技师考勤月份归一(202610 被取成 0 月、202611 会错拉 1 月),统计月拉取失败改为中止,不再静默导出缺技师名单 - xq0009 新增「钉钉群名」字段:导出后把名单推到群(dingtalk_sdk.dws),执行前按群全称精确校验,识别不到直接报错并列出候选群 - xq0009 技师月末仍在休(HR 无请假单)时备注补「截至 X 仍在病假」;推送超时不再重试(避免重复发文件) - dingtalk_sdk 0.1.2:兼容 dws 异步任务返回(outcome=pending 视为已受理并轮询 query-send-status),修复误判失败导致同一条消息重复发送 - 文档:SDK 发版直发正式(--prod),插件仍走测试通道→人工转正;xq0001 自测兼容门禁 runpy 直跑
676 lines
32 KiB
Python
676 lines
32 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""钉钉单聊 / 群聊推送(基于 ``dws`` 命令行,零第三方依赖)。
|
||
|
||
能力(与原 ``workflows/share/dingtalk_dws_push.py`` 一致):
|
||
- 单聊:按姓名 + 工号解析 openDingTalkId,发送文本 / 文件(自动建会话、上传钉盘);
|
||
- 群聊:按群名解析 openconversationId,发送文本 / 文件,支持标题、@所有人、@指定成员;
|
||
- 防风控限流:滑动窗口默认 50 条/分钟,窗口满时等待不丢消息;
|
||
- 推送记录:``<record_dir>/YYYY-MM-DD/推送记录.csv``(best-effort)。
|
||
|
||
两种调用风格:
|
||
- ``Dws(...).send_message(...)``:失败抛 ``DwsError`` / ``ConfigError``;
|
||
- ``push(...)``:逐条吞异常并返回 ``{"success", "message", "results"}``,与旧 ``main()`` 兼容。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import time
|
||
from datetime import datetime
|
||
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple
|
||
|
||
from .config import get_settings, resolve_dws_bin
|
||
from .errors import ConfigError, DwsError
|
||
from .http import mask
|
||
|
||
RECORD_COLUMNS = ["推送时间", "工号", "姓名", "结果", "消息摘要"]
|
||
RECORD_SUMMARY_MAX_CHARS = 200
|
||
RECORD_PATH_GLV = "push_record_path" # 影刀全局变量名(非影刀环境自动跳过)
|
||
|
||
DEFAULT_TIMEOUT = 300.0 # 单条 dws 命令超时秒(大文件上传留足时间)
|
||
CODE_NO_CONVERSATION = "11056"
|
||
TASK_WAIT = 20.0 # 异步任务(outcome=pending)查询终态的最长等待秒
|
||
TASK_POLL = 1.0 # 异步任务状态查询间隔秒
|
||
|
||
# dws 任务状态:受理中 / 已成功 / 已失败(取值大小写不一,统一小写比较)
|
||
_ACCEPTED_STATES = ("pending", "processing", "accepted", "queued", "running", "in_progress")
|
||
_DONE_STATES = ("done", "success", "succeeded", "completed", "finished", "sent")
|
||
_FAILED_STATES = ("failed", "error", "cancelled", "canceled", "timeout", "expired")
|
||
|
||
|
||
# ==================== 工具 ====================
|
||
|
||
def _extract_error_code(text: str) -> str:
|
||
"""从 dws 错误输出里尽量提取 server_error_code。"""
|
||
try:
|
||
data = json.loads(text[text.find("{"):])
|
||
return str(data.get("error", {}).get("server_error_code") or "")
|
||
except Exception: # noqa: BLE001
|
||
return ""
|
||
|
||
|
||
def _set_glv(name: str, value) -> None:
|
||
"""写影刀全局变量(非影刀环境静默跳过)。"""
|
||
try:
|
||
glv[name] = value # noqa: F821 - 影刀注入的全局变量
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
|
||
def normalize_msg_type(msg_type: str) -> str:
|
||
"""消息类型归一:``文本/text`` → ``text``;``文件/file`` → ``file``。"""
|
||
key = str(msg_type or "").strip().lower()
|
||
if key in ("text", "文本", "txt", "文字"):
|
||
return "text"
|
||
if key in ("file", "文件"):
|
||
return "file"
|
||
raise ValueError(f"未知消息类型「{msg_type}」,仅支持:文本 / 文件")
|
||
|
||
|
||
def normalize_chat_type(chat_type: str) -> str:
|
||
"""通道归一:``single/单聊`` → ``single``;``group/群聊`` → ``group``。"""
|
||
key = str(chat_type or "").strip().lower()
|
||
if key in ("single", "单聊", "single_chat", "person", "个人", "私聊"):
|
||
return "single"
|
||
if key in ("group", "群聊", "group_chat", "群"):
|
||
return "group"
|
||
raise ValueError(f"未知推送通道「{chat_type}」,仅支持:single/单聊、group/群聊")
|
||
|
||
|
||
def record_csv_path(record_dir: str) -> str:
|
||
"""推送记录文件路径:``<record_dir>/YYYY-MM-DD/推送记录.csv``。"""
|
||
return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
|
||
|
||
|
||
def _truthy(value) -> bool:
|
||
"""宽松布尔:True/1/"true"/"ok"/"success"/"done" 都算真。"""
|
||
if isinstance(value, bool):
|
||
return value
|
||
if isinstance(value, (int, float)):
|
||
return value != 0
|
||
return str(value or "").strip().lower() in ("true", "1", "ok", "success", "done")
|
||
|
||
|
||
def is_success(data) -> bool:
|
||
"""dws 返回体是否代表「已成功 / 已受理」(同步与异步两种形态都认)。
|
||
|
||
- 同步:``{"success": true, ...}``(旧版 dws)或 ``{"ok": true, ...}``;
|
||
- 异步受理:``{"ok": true, "outcome": "pending", "data": {"success": true,
|
||
"result": {"openTaskId": ...}}, "meta": {"operation": {"state": "processing",
|
||
"next_command": "dws chat message query-send-status --open-task-id ..."}}}``
|
||
—— 这是**发送任务已进队列**,不是失败;旧实现只认顶层 ``success``,
|
||
于是把成功当失败、上层重试导致同一条消息重复发送多次。
|
||
"""
|
||
if not isinstance(data, dict):
|
||
return False
|
||
if _truthy(data.get("success")):
|
||
return True
|
||
inner = data.get("data")
|
||
if isinstance(inner, dict) and _truthy(inner.get("success")):
|
||
return True
|
||
outcome = str(data.get("outcome") or "").strip().lower()
|
||
return outcome in _ACCEPTED_STATES or outcome in _DONE_STATES
|
||
|
||
|
||
def operation_of(data) -> dict:
|
||
"""取异步任务信息 ``meta.operation``(没有则返回空 dict)。"""
|
||
meta = data.get("meta") if isinstance(data, dict) else None
|
||
op = meta.get("operation") if isinstance(meta, dict) else None
|
||
return op if isinstance(op, dict) else {}
|
||
|
||
|
||
# ==================== 客户端 ====================
|
||
|
||
class Dws:
|
||
"""dws 命令行封装。
|
||
|
||
Args:
|
||
bin: dws 可执行文件路径(缺省按 ``DINGTALK_DWS_BIN`` / 用户目录 / PATH 解析)
|
||
rate_limit: 窗口内最大发送条数(默认 50)
|
||
rate_window: 限流窗口秒(默认 60)
|
||
record_dir: 默认推送记录目录(可在每次调用时覆盖)
|
||
timeout: 单条命令超时秒
|
||
task_wait: 异步任务(outcome=pending)查询终态的最长等待秒,默认 20
|
||
task_poll: 异步任务状态查询间隔秒,默认 1
|
||
log: 日志回调
|
||
"""
|
||
|
||
def __init__(self, bin: str = "", rate_limit: Optional[int] = None,
|
||
rate_window: Optional[float] = None, record_dir: str = "",
|
||
timeout: Optional[float] = None,
|
||
task_wait: Optional[float] = None,
|
||
task_poll: Optional[float] = None,
|
||
log: Optional[Callable[[str], None]] = None) -> None:
|
||
cfg = get_settings()
|
||
self._bin = (bin or "").strip()
|
||
self.rate_limit = max(1, int(rate_limit if rate_limit is not None else cfg.rate_limit))
|
||
self.rate_window = float(rate_window if rate_window is not None
|
||
else cfg.rate_window)
|
||
self.record_dir = record_dir or ""
|
||
self.timeout = float(timeout if timeout is not None else DEFAULT_TIMEOUT)
|
||
self.task_wait = float(task_wait if task_wait is not None else TASK_WAIT)
|
||
self.task_poll = float(task_poll if task_poll is not None else TASK_POLL)
|
||
self.log = log or (lambda msg: None)
|
||
self._open_id_cache: Dict[Tuple[str, str], str] = {}
|
||
self._rate_history: List[float] = []
|
||
|
||
# ---- 基础 ----
|
||
@property
|
||
def bin(self) -> str:
|
||
"""dws 可执行文件路径(惰性解析;找不到返回空串)。"""
|
||
if not self._bin:
|
||
self._bin = resolve_dws_bin()
|
||
return self._bin
|
||
|
||
def require_bin(self) -> str:
|
||
path = self.bin
|
||
if not path:
|
||
raise ConfigError(
|
||
"未找到 dws 命令行工具:请安装 dws 并加入 PATH,"
|
||
"或设置 DINGTALK_DWS_BIN / 构造 Dws(bin=...)")
|
||
return path
|
||
|
||
def run(self, args: Sequence[str]) -> dict:
|
||
"""执行 dws 子命令并返回完整 JSON。
|
||
|
||
返回值兼容两种形态:同步 ``{"success": true}`` 与**异步受理**
|
||
``{"ok": true, "outcome": "pending", "meta": {"operation": {...}}}``。
|
||
异步受理会按 ``meta.operation.next_command`` 轮询发送结果(最多 ``task_wait`` 秒),
|
||
查不到终态时按「已受理」返回,避免上层重试导致重复发送。
|
||
"""
|
||
data = self._exec(args)
|
||
if not is_success(data):
|
||
raise DwsError(f"命令未成功: {mask(data)}",
|
||
code=_extract_error_code(json.dumps(data, ensure_ascii=False)))
|
||
return self._await_task(data)
|
||
|
||
def _exec(self, args: Sequence[str]) -> dict:
|
||
"""真正执行 dws 并解析 JSON(不做成功判定,供轮询复用)。"""
|
||
cmd = [self.require_bin(), *[str(a) for a in args]]
|
||
try:
|
||
proc = subprocess.run(cmd, capture_output=True, text=True,
|
||
encoding="utf-8", errors="replace",
|
||
timeout=self.timeout)
|
||
except subprocess.TimeoutExpired as exc:
|
||
raise DwsError(f"命令超时({self.timeout:.0f}s):{mask(exc)}") from None
|
||
except OSError as exc:
|
||
raise ConfigError(f"无法执行 dws:{mask(exc)}") from None
|
||
if proc.returncode != 0:
|
||
stderr = (proc.stderr or "").strip()
|
||
raise DwsError(f"命令失败: {mask(stderr)}", code=_extract_error_code(stderr))
|
||
raw = proc.stdout or ""
|
||
idx = raw.find("{")
|
||
if idx < 0:
|
||
raise DwsError(f"dws 输出无法解析:{mask(raw[:200])}")
|
||
return json.loads(raw[idx:])
|
||
|
||
def _await_task(self, data: dict) -> dict:
|
||
"""异步受理的发送任务:轮询 ``query-send-status`` 至终态,超时按已受理返回。"""
|
||
op = operation_of(data)
|
||
state = str(op.get("state") or "").strip().lower()
|
||
next_cmd = str(op.get("next_command") or "").strip()
|
||
if state not in _ACCEPTED_STATES or not next_cmd.startswith("dws "):
|
||
return data
|
||
args = next_cmd.split()[1:] # 去掉命令名 dws 本身
|
||
if not args:
|
||
return data
|
||
self.log(f"[INFO] dws 任务已受理(state={state}),查询发送结果…")
|
||
deadline = time.time() + self.task_wait
|
||
while time.time() < deadline:
|
||
time.sleep(self.task_poll)
|
||
try:
|
||
st = self._exec(args)
|
||
except (DwsError, ConfigError) as exc:
|
||
# 查询失败不等于发送失败:消息已进队列,按成功处理,绝不重发
|
||
self.log(f"[WARN] 查询发送状态失败(消息已受理,按成功处理):{mask(exc)}")
|
||
return data
|
||
st_state = str(operation_of(st).get("state")
|
||
or st.get("outcome") or "").strip().lower()
|
||
if st_state in _DONE_STATES:
|
||
self.log("[INFO] dws 发送任务完成")
|
||
return st
|
||
if st_state in _FAILED_STATES:
|
||
raise DwsError(f"发送任务失败(state={st_state}):{mask(st)}")
|
||
if st_state not in _ACCEPTED_STATES:
|
||
# 状态字段换了/无法识别:按已受理处理,别为一条消息卡满 task_wait
|
||
self.log(f"[WARN] 发送状态无法识别({st_state or '空'}),按已受理处理")
|
||
return data
|
||
self.log(f"[WARN] dws 发送任务 {self.task_wait:.0f}s 内未返回终态,按已受理处理(勿重复发送)")
|
||
return data
|
||
|
||
# ---- 限流 ----
|
||
def _rate_wait(self) -> None:
|
||
"""滑动窗口限流:窗口内最多 ``rate_limit`` 次;满则等待最早一条滑出窗口。"""
|
||
while True:
|
||
now = time.time()
|
||
self._rate_history[:] = [t for t in self._rate_history
|
||
if now - t < self.rate_window]
|
||
if len(self._rate_history) < self.rate_limit:
|
||
break
|
||
sleep_sec = max(0.1, self._rate_history[0] + self.rate_window - now)
|
||
self.log(f"[WARN] 已达限流上限({self.rate_limit} 条/分钟),"
|
||
f"等待 {sleep_sec:.1f} 秒后继续…")
|
||
time.sleep(min(sleep_sec, 1.0))
|
||
self._rate_history.append(time.time())
|
||
|
||
# ---- 推送记录 ----
|
||
def record_push(self, user_id: str, name: str, result: str, summary: str = "",
|
||
record_dir: str = "") -> str:
|
||
"""追加一条推送记录(best-effort);返回记录文件路径,未记录返回空串。"""
|
||
target_dir = record_dir or self.record_dir
|
||
if not target_dir:
|
||
return ""
|
||
try:
|
||
path = record_csv_path(target_dir)
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
is_new = not os.path.exists(path)
|
||
text = str(summary or "").replace("\r\n", "\n").replace("\r", "\n")
|
||
if len(text) > RECORD_SUMMARY_MAX_CHARS:
|
||
text = text[:RECORD_SUMMARY_MAX_CHARS] + "..."
|
||
with open(path, "a", newline="", encoding="utf-8-sig") as fp:
|
||
writer = csv.DictWriter(fp, fieldnames=RECORD_COLUMNS)
|
||
if is_new:
|
||
writer.writeheader()
|
||
writer.writerow({
|
||
"推送时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||
"工号": user_id,
|
||
"姓名": name,
|
||
"结果": result,
|
||
"消息摘要": text,
|
||
})
|
||
self.log(f"[INFO] 推送记录已写入:{path}({result})")
|
||
return path
|
||
except Exception as exc: # noqa: BLE001 - 记录失败不影响推送
|
||
self.log(f"[WARN] 推送记录写入失败(不影响推送):{mask(exc)}")
|
||
return ""
|
||
|
||
def _recorded(self, result: dict, record_dir: str, name: str, user_id: str,
|
||
content: str = "", file_path: str = "") -> dict:
|
||
target = record_dir or self.record_dir
|
||
if target:
|
||
summary = str(content or "").strip() or os.path.basename(str(file_path or ""))
|
||
self.record_push(user_id, name, "成功" if result.get("success") else "失败",
|
||
summary, record_dir=target)
|
||
return result
|
||
|
||
# ---- 联系人 ----
|
||
def resolve_open_id(self, name: str, user_id: str = "") -> str:
|
||
"""按姓名(+工号消歧)解析 openDingTalkId;结果按 (姓名, 工号) 进程内缓存。"""
|
||
name = str(name or "").strip()
|
||
user_id = str(user_id or "").strip()
|
||
if not name:
|
||
raise ConfigError("姓名不能为空(解析 openDingTalkId 需要姓名)")
|
||
key = (name, user_id)
|
||
cached = self._open_id_cache.get(key)
|
||
if cached:
|
||
self.log(f"[INFO] 命中缓存: {name} | userId={user_id}")
|
||
return cached
|
||
|
||
data = self.run(["contact", "user", "search", "--query", name, "--format", "json"])
|
||
users = data.get("result") or []
|
||
if not users:
|
||
raise DwsError(f"未找到姓名为「{name}」的成员")
|
||
|
||
# search 是关键词模糊搜索(会误命中「陈杰顺」等近似名)且返回里没有工号;
|
||
# 工号只在 get 详情的 orgEmployeeModel.jobNumber,故按 userId 关联详情再匹配。
|
||
ids = ",".join(str(u["userId"]) for u in users)
|
||
detail = self.run(["contact", "user", "get", "--ids", ids, "--format", "json"])
|
||
info_map = {}
|
||
for item in detail.get("result") or []:
|
||
org = item.get("orgEmployeeModel") or {}
|
||
if org.get("orgUserId"):
|
||
info_map[org["orgUserId"]] = item
|
||
|
||
def _org(user: dict) -> dict:
|
||
return (info_map.get(user.get("userId"), {}) or {}).get("orgEmployeeModel") or {}
|
||
|
||
if user_id:
|
||
for user in users:
|
||
if str(_org(user).get("jobNumber") or "").strip() == user_id:
|
||
self.log(f"[INFO] 按工号锁定: {user['name']} | 工号={user_id}")
|
||
self._open_id_cache[key] = user["openDingTalkId"]
|
||
return user["openDingTalkId"]
|
||
hints = "\n".join(
|
||
f" {u.get('name')} | 工号={str(_org(u).get('jobNumber') or '').strip() or '未知'}"
|
||
for u in users)
|
||
raise DwsError(f"按姓名「{name}」搜索的候选中未找到工号 {user_id},"
|
||
f"请核对姓名与工号是否匹配:\n{hints}")
|
||
|
||
if len(users) == 1:
|
||
self._open_id_cache[key] = users[0]["openDingTalkId"]
|
||
return users[0]["openDingTalkId"]
|
||
|
||
exact = [u for u in users if (u.get("name") or "").strip() == name]
|
||
if len(exact) == 1:
|
||
self._open_id_cache[key] = exact[0]["openDingTalkId"]
|
||
return exact[0]["openDingTalkId"]
|
||
|
||
hints = []
|
||
for user in users:
|
||
org = _org(user)
|
||
depts = ",".join(str(d.get("deptName", "")) for d in (org.get("depts") or []))
|
||
hints.append(
|
||
f" {user.get('name')} | 工号={str(org.get('jobNumber') or '').strip() or '未知'}"
|
||
f" | 部门={depts or '未知'} | 职位={org.get('orgTitle') or user.get('title') or '未知'}")
|
||
raise DwsError(f"「{name}」有 {len(users)} 个同名,请核对工号后再调用:\n"
|
||
+ "\n".join(hints))
|
||
|
||
# ---- 单聊会话与文件 ----
|
||
def get_chat_space_id(self, open_id: str) -> str:
|
||
"""取单聊会话共享空间 ID;无会话(11056/缺字段)返回空串。"""
|
||
data = self.run(["chat", "conversation-info",
|
||
"--open-dingtalk-id", open_id, "--format", "json"])
|
||
try:
|
||
return data["result"]["conversationInfo"]["extension"].get("newCSpaceIdIM", "")
|
||
except (KeyError, TypeError, AttributeError):
|
||
return ""
|
||
|
||
def upload_file(self, space_id: str, file_path: str) -> dict:
|
||
data = self.run(["drive", "upload", "--file", file_path,
|
||
"--space-id", space_id, "--format", "json"])
|
||
return data["result"]
|
||
|
||
def get_dentry(self, file_id: str, space_id: str) -> dict:
|
||
data = self.run(["drive", "info", "--node", file_id,
|
||
"--space-id", space_id, "--format", "json"])
|
||
return data["result"]
|
||
|
||
# ---- 单聊发送 ----
|
||
def send_text(self, open_id: str, text: str) -> None:
|
||
"""向单聊发文本;遇 11056(会话不存在)等待 1s 重试一次(首条消息即自动建会话)。"""
|
||
def _do() -> None:
|
||
self._rate_wait()
|
||
self.run(["chat", "message", "send", "--open-dingtalk-id", open_id,
|
||
"--content", str(text), "--format", "json"])
|
||
|
||
try:
|
||
_do()
|
||
except DwsError as exc:
|
||
if exc.code != CODE_NO_CONVERSATION:
|
||
raise
|
||
self.log("[INFO] 会话不存在(11056),等待 1s 后重试一次…")
|
||
time.sleep(1)
|
||
_do()
|
||
self.log(f"[INFO] 文本已发送: {text}")
|
||
|
||
def send_file(self, open_id: str, file_path: str) -> None:
|
||
"""向单聊发文件:取会话空间 → 上传钉盘 → 发文件消息;无会话先发文本建会话。"""
|
||
if not file_path or not os.path.exists(str(file_path)):
|
||
raise ConfigError(f"文件不存在: {file_path}")
|
||
try:
|
||
space_id = self.get_chat_space_id(open_id)
|
||
except DwsError as exc:
|
||
if exc.code != CODE_NO_CONVERSATION:
|
||
raise
|
||
space_id = ""
|
||
if not space_id:
|
||
self.log("[INFO] 对方未建立会话,先发送一条文本建立会话…")
|
||
self.send_text(open_id, "建立会话")
|
||
space_id = self.get_chat_space_id(open_id)
|
||
if not space_id:
|
||
raise DwsError("建立会话后仍拿不到会话空间 ID(newCSpaceIdIM),请检查")
|
||
|
||
up = self.upload_file(space_id, str(file_path))
|
||
info = self.get_dentry(up["fileId"], up["spaceId"])
|
||
self._rate_wait()
|
||
self.run(["chat", "message", "send", "--open-dingtalk-id", open_id,
|
||
"--msg-type", "file",
|
||
"--dentry-id", info["dentryId"],
|
||
"--space-id", up["spaceId"],
|
||
"--file-name", info["name"],
|
||
"--file-type", info.get("extension", "file"),
|
||
"--file-path", info.get("path", "/" + str(info["name"])),
|
||
"--file-size", str(info["fileSize"]),
|
||
"--format", "json"])
|
||
self.log(f"[INFO] 文件已发送: {os.path.basename(str(file_path))}")
|
||
|
||
# ---- 群聊 ----
|
||
def search_group(self, query: str, limit: int = 20) -> List[dict]:
|
||
"""按群名关键词搜索群聊(query 用群名连续核心词,勿拆单字)。"""
|
||
data = self.run(["chat", "search", "--query", query,
|
||
"--limit", str(limit), "--format", "json"])
|
||
result = data.get("result") or {}
|
||
if isinstance(result, dict):
|
||
return result.get("groups") or []
|
||
return result or []
|
||
|
||
@staticmethod
|
||
def _group_conv_id(group: dict) -> str:
|
||
for key in ("openConversationId", "conversationId", "chatId", "id"):
|
||
val = (group or {}).get(key)
|
||
if val:
|
||
return str(val)
|
||
return ""
|
||
|
||
@staticmethod
|
||
def _group_title(group: dict) -> str:
|
||
for key in ("title", "name"):
|
||
val = (group or {}).get(key)
|
||
if val:
|
||
return str(val)
|
||
return ""
|
||
|
||
def resolve_group_id(self, group_name: str) -> str:
|
||
"""按群名全称精确解析 openconversationId;歧义/无匹配直接报错。"""
|
||
name = str(group_name or "").strip()
|
||
if not name:
|
||
raise ConfigError("群名不能为空(请传群全称)")
|
||
groups = self.search_group(name)
|
||
if not groups:
|
||
raise DwsError(f"未找到群「{name}」,请确认群全称后重试")
|
||
exact = [g for g in groups if self._group_title(g) == name]
|
||
if len(exact) == 1:
|
||
conv_id = self._group_conv_id(exact[0])
|
||
self.log(f"[INFO] 命中群: {name} | openConversationId={conv_id}")
|
||
return conv_id
|
||
if not exact:
|
||
hints = "\n".join(f" {self._group_title(g) or '未知群名'}" for g in groups)
|
||
raise DwsError(f"未找到与「{name}」全等匹配的群,附近候选:\n{hints}")
|
||
hints = "\n".join(f" {self._group_title(g) or '未知群名'} | {self._group_conv_id(g)}"
|
||
for g in exact)
|
||
raise DwsError(f"群名「{name}」匹配到 {len(exact)} 个同名候选,请确认后重试:\n{hints}")
|
||
|
||
def send_group_text(self, conversation_id: str, text: str, title: str = "",
|
||
at_all: bool = False, at_open_ids: str = "") -> None:
|
||
"""向群聊发文本;``at_all`` / ``at_open_ids`` 需在内容中放 ``<@all>`` / ``<@openId>``。"""
|
||
args = ["chat", "message", "send",
|
||
"--conversation-id", conversation_id, "--content", str(text)]
|
||
if title:
|
||
args += ["--title", str(title)]
|
||
if at_all:
|
||
args += ["--at-all"]
|
||
if at_open_ids:
|
||
args += ["--at-open-dingtalk-ids", str(at_open_ids)]
|
||
args += ["--format", "json"]
|
||
self._rate_wait()
|
||
self.run(args)
|
||
self.log(f"[INFO] 群文本已发送: {text}")
|
||
|
||
def send_group_file(self, conversation_id: str, file_path: str) -> None:
|
||
"""向群聊发本地文件(dws 自动上传并按 file 消息发送)。"""
|
||
if not file_path or not os.path.exists(str(file_path)):
|
||
raise ConfigError(f"文件不存在: {file_path}")
|
||
self._rate_wait()
|
||
self.run(["chat", "message", "send", "--conversation-id", conversation_id,
|
||
"--msg-type", "file", "--file", str(file_path), "--format", "json"])
|
||
self.log(f"[INFO] 群文件已发送: {os.path.basename(str(file_path))}")
|
||
|
||
# ---- 统一发送(单条) ----
|
||
def send_message(self, msg_type, name, user_id, content, file_path: str = "",
|
||
record_dir: str = "") -> dict:
|
||
"""单聊单条推送。返回 ``{"success": bool, "message": str}``(不抛异常)。"""
|
||
name = str(name or "").strip()
|
||
user_id = str(user_id or "").strip()
|
||
try:
|
||
mtype = normalize_msg_type(msg_type)
|
||
if mtype == "text":
|
||
if not str(content or "").strip():
|
||
return self._recorded({"success": False, "message": "文本消息内容不能为空"},
|
||
record_dir, name, user_id, content, file_path)
|
||
open_id = self.resolve_open_id(name, user_id)
|
||
self.log(f"[INFO] 接收人 openDingTalkId: {open_id}")
|
||
self.send_text(open_id, str(content))
|
||
return self._recorded({"success": True, "message": f"已向「{name}」发送文本"},
|
||
record_dir, name, user_id, content, file_path)
|
||
|
||
if not str(file_path or "").strip() or not os.path.exists(str(file_path)):
|
||
return self._recorded({"success": False, "message": f"文件不存在: {file_path}"},
|
||
record_dir, name, user_id, content, file_path)
|
||
open_id = self.resolve_open_id(name, user_id)
|
||
self.log(f"[INFO] 接收人 openDingTalkId: {open_id}")
|
||
self.send_file(open_id, str(file_path))
|
||
return self._recorded({"success": True, "message": f"已向「{name}」发送文件"},
|
||
record_dir, name, user_id, content, file_path)
|
||
except Exception as exc: # noqa: BLE001 - 单条失败不影响整批
|
||
return self._recorded({"success": False, "message": mask(exc)},
|
||
record_dir, name, user_id, content, file_path)
|
||
|
||
def send_group_message(self, group_name, content: str = "", file_path: str = "",
|
||
title: str = "", at_all: bool = False,
|
||
at_open_ids: str = "", record_dir: str = "") -> dict:
|
||
"""群聊推送(文本/文件可同时发)。返回 ``{"success": bool, "message": str}``。"""
|
||
name = str(group_name or "").strip()
|
||
try:
|
||
if not name:
|
||
return self._recorded({"success": False, "message": "群名不能为空"},
|
||
record_dir, name, "", content, file_path)
|
||
if not content and not file_path:
|
||
return self._recorded(
|
||
{"success": False, "message": "文本内容与文件地址至少传一个"},
|
||
record_dir, name, "", content, file_path)
|
||
conv_id = self.resolve_group_id(name)
|
||
if file_path:
|
||
self.send_group_file(conv_id, str(file_path).strip())
|
||
if content:
|
||
self.send_group_text(conv_id, content, title=title, at_all=at_all,
|
||
at_open_ids=at_open_ids)
|
||
return self._recorded({"success": True, "message": f"已向群「{name}」推送"},
|
||
record_dir, name, "", content, file_path)
|
||
except Exception as exc: # noqa: BLE001
|
||
return self._recorded({"success": False, "message": mask(exc)},
|
||
record_dir, name, "", content, file_path)
|
||
|
||
# ---- 批量入口(兼容旧 main) ----
|
||
def push(self, messages: Iterable, record_dir: str = "", chat_type: str = "") -> dict:
|
||
"""批量推送。``chat_type`` 留空时按每条消息结构自动识别单聊/群聊。
|
||
|
||
单聊元素:五元组 ``(消息类型, 姓名, 工号, 消息内容, 文件地址)`` 或 dict;
|
||
群聊元素:dict 含 ``group``(或元组 ``(群名, 文本, 文件, 标题, at_all, at_open_ids)``)。
|
||
|
||
Returns:
|
||
``{"success": bool, "message": str, "results": [...], "record_path": str}``
|
||
"""
|
||
forced = normalize_chat_type(chat_type) if chat_type else ""
|
||
target_dir = record_dir or self.record_dir
|
||
results = []
|
||
for item in messages or []:
|
||
is_group = forced == "group" or (not forced and isinstance(item, dict)
|
||
and bool(item.get("group") or item.get("群名")))
|
||
if is_group:
|
||
if isinstance(item, dict):
|
||
group = item.get("group") or item.get("群名") or ""
|
||
content = item.get("content") or item.get("文本内容") or ""
|
||
file_path = item.get("file_path") or item.get("文件地址") or ""
|
||
title = item.get("title") or item.get("标题") or ""
|
||
at_all = bool(item.get("at_all") or item.get("@所有人"))
|
||
at_open_ids = item.get("at_open_ids") or item.get("@成员") or ""
|
||
else:
|
||
seq = list(item) + [""] * 6
|
||
group, content, file_path, title = seq[0], seq[1], seq[2], seq[3]
|
||
at_all, at_open_ids = bool(seq[4]), seq[5]
|
||
results.append(self.send_group_message(
|
||
group, content, file_path, title, at_all, at_open_ids, target_dir))
|
||
else:
|
||
if isinstance(item, dict):
|
||
msg_type = item.get("msg_type") or item.get("消息类型") or ""
|
||
name = item.get("name") or item.get("姓名") or ""
|
||
user_id = item.get("user_id") or item.get("工号") or ""
|
||
content = item.get("content") or item.get("消息内容") or ""
|
||
file_path = item.get("file_path") or item.get("文件地址") or ""
|
||
else:
|
||
seq = list(item) + [""] * 5
|
||
msg_type, name, user_id, content, file_path = seq[:5]
|
||
results.append(self.send_message(msg_type, name, user_id, content,
|
||
file_path, target_dir))
|
||
ok = sum(1 for r in results if r.get("success"))
|
||
path = record_csv_path(target_dir) if target_dir else ""
|
||
_set_glv(RECORD_PATH_GLV, path)
|
||
if path:
|
||
self.log(f"[INFO] 推送记录文件路径已写入全局变量 {RECORD_PATH_GLV}:{path}")
|
||
return {
|
||
"success": ok == len(results),
|
||
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
|
||
"results": results,
|
||
"record_path": path,
|
||
}
|
||
|
||
|
||
# ==================== 默认实例 + 模块级兼容函数 ====================
|
||
|
||
_DEFAULT: Optional[Dws] = None
|
||
|
||
|
||
def get_default() -> Dws:
|
||
"""取进程内默认 Dws 实例(用于保持通讯录缓存与限流跨调用生效)。"""
|
||
global _DEFAULT
|
||
if _DEFAULT is None:
|
||
_DEFAULT = Dws()
|
||
return _DEFAULT
|
||
|
||
|
||
def set_default(client: Dws) -> None:
|
||
"""替换默认实例(测试或按场景配置时用)。"""
|
||
global _DEFAULT
|
||
_DEFAULT = client
|
||
|
||
|
||
def push(messages: Iterable, record_dir: str = "", chat_type: str = "") -> dict:
|
||
"""批量推送(兼容旧 ``dingtalk_dws_push.main`` 签名与返回)。"""
|
||
return get_default().push(messages, record_dir=record_dir, chat_type=chat_type)
|
||
|
||
|
||
main = push
|
||
|
||
|
||
def send_message(msg_type, name, user_id, content, file_path: str = "",
|
||
record_dir: str = "") -> dict:
|
||
return get_default().send_message(msg_type, name, user_id, content, file_path, record_dir)
|
||
|
||
|
||
def send_group_message(group_name, content: str = "", file_path: str = "", title: str = "",
|
||
at_all: bool = False, at_open_ids: str = "",
|
||
record_dir: str = "") -> dict:
|
||
return get_default().send_group_message(group_name, content, file_path, title,
|
||
at_all, at_open_ids, record_dir)
|
||
|
||
|
||
def resolve_open_id(name: str, user_id: str = "") -> str:
|
||
return get_default().resolve_open_id(name, user_id)
|
||
|
||
|
||
def resolve_group_id(group_name: str) -> str:
|
||
return get_default().resolve_group_id(group_name)
|
||
|
||
|
||
__all__ = [
|
||
"CODE_NO_CONVERSATION",
|
||
"DEFAULT_TIMEOUT",
|
||
"Dws",
|
||
"RECORD_COLUMNS",
|
||
"RECORD_PATH_GLV",
|
||
"get_default",
|
||
"main",
|
||
"normalize_chat_type",
|
||
"normalize_msg_type",
|
||
"push",
|
||
"record_csv_path",
|
||
"resolve_group_id",
|
||
"resolve_open_id",
|
||
"send_group_message",
|
||
"send_message",
|
||
"set_default",
|
||
]
|