Files
37duAutomation/plugins/XQ0001-0100/XQ0009 门店上月请休假异常人员名单梳理/data/dingtalk_group.py
T
puddy e70722abeb fix(xq0009): 修复收银月份格式致技师整体漏判;新增钉钉群文件推送(1.0.15)
- 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 直跑
2026-11-10 14:26:35 +08:00

111 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""钉钉群聊推送(dws 通道):群名校验 + 名单文件推送。
自定义群机器人(webhook)只能发文本/Markdown,发不了本地文件,推 Excel 必须走
``dingtalk_sdk.dws`` 的群聊 file 消息(SDK 由执行机按 plugin.json.requires.sdks 挂载)。
使用约定:
- 只有配置了「钉钉群名」才走本模块;留空 = 不推送文件;
- 群名校验放在 run() 最前(``check_group``),识别不到直接抛错并列出候选群,
不进入取数分析流程(避免跑完整套流程才发现推不出去);
- 推送失败按项目级重试(最多 3 次),三次仍失败抛错,由调用方决定是否影响本次结果。
"""
from __future__ import annotations
import os
import time
from .. import config
try: # SDK 由执行机挂载;开发机未挂载时给出清晰提示
from dingtalk_sdk import Dws
from dingtalk_sdk.config import resolve_dws_bin
except ImportError as exc: # pragma: no cover - 仅开发/未挂载环境触发
Dws = None # type: ignore[assignment]
resolve_dws_bin = None # type: ignore[assignment]
_SDK_ERROR = str(exc)
else:
_SDK_ERROR = ""
MAX_ATTEMPTS = config.MAX_REQUEST_RETRY # 项目级重试:最多 3 次
RETRY_WAIT = 3 # 每次重试前等待秒数
def _dws_log(msg):
"""dws 输出转发到插件日志(WARN 前缀降级为 WARNING)。"""
level = "WARNING" if "[WARN]" in str(msg) else "INFO"
config.log(msg, level)
def _require_sdk():
if Dws is None:
raise RuntimeError(
"未挂载钉钉 SDK(dingtalk_sdk),无法校验群名与推送文件;"
"请联系管理员下发 SDK 后重试,或清空「钉钉群名」跳过推送"
f"({_SDK_ERROR})")
bin_path = resolve_dws_bin()
if not bin_path:
raise RuntimeError(
"未找到 dws 命令行工具(DINGTALK_DWS_BIN / ~/.local/bin/dws.exe / PATH 均未命中),"
"无法校验群名与推送文件;请安装 dws 后重试,或清空「钉钉群名」跳过推送")
return bin_path
def check_group(group_name):
"""按群全称精确解析 openConversationId;识别不到抛 RuntimeError(含候选群名)。"""
name = str(group_name or "").strip()
if not name:
raise RuntimeError("钉钉群名为空(请填群全称,或在界面清空以跳过推送)")
bin_path = _require_sdk()
client = Dws(bin=bin_path, log=_dws_log)
try:
conv_id = client.resolve_group_id(name)
except Exception as exc: # noqa: BLE001 - 统一转成插件可读的错误
# SDK 错误里候选群是逐行列的,界面横幅只有一行,这里压成单行便于直接看
detail = " / ".join(p.strip() for p in str(exc).splitlines() if p.strip())
raise RuntimeError(
f"钉钉群「{name}」未识别:{detail}"
"(群名需与钉钉群全称完全一致,可在钉钉里复制群名称;留空则跳过推送)") from exc
config.log(f"[INFO] 钉钉群校验通过:{name} | openConversationId={conv_id}")
return conv_id
def push_file(conversation_id, group_name, file_path, text="", record_dir=""):
"""把文件推到群(先发文件、再发一句说明);失败重试 MAX_ATTEMPTS 次,最终失败抛错。"""
name = str(group_name or "").strip()
path = str(file_path or "").strip()
conv_id = str(conversation_id or "").strip()
if not conv_id:
raise RuntimeError(f"钉钉群「{name}」缺少会话 ID,无法推送")
if not path or not os.path.exists(path):
raise RuntimeError(f"待推送文件不存在:{path}")
bin_path = _require_sdk()
client = Dws(bin=bin_path, record_dir=record_dir, log=_dws_log)
last = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
client.send_group_file(conv_id, path) # 文件是主交付物,先发
break
except Exception as exc: # noqa: BLE001 - 重试后仍失败再抛
last = exc
text = str(exc)
if "超时" in text or "timeout" in text.lower():
# 命令超时=发送状态未知(dws 侧可能已经发出),重试只会重复发文件
raise RuntimeError(
f"钉钉群「{name}」推送超时,发送状态未知(为避免重复发送未重试,"
f"请到群里确认是否已收到):{text}") from exc
config.log(f"[WARN] 群文件推送失败(第 {attempt}/{MAX_ATTEMPTS} 次):{text}", "WARNING")
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT)
else:
raise RuntimeError(f"钉钉群「{name}」推送失败(已重试 {MAX_ATTEMPTS} 次):{last}")
if str(text or "").strip():
try:
client.send_group_text(conv_id, str(text).strip())
except Exception as exc: # noqa: BLE001 - 说明文字失败不影响文件送达
config.log(f"[WARN] 群说明文字发送失败(文件已送达):{exc}", "WARNING")
config.log(f"[INFO] 已推送钉钉群「{name}」:{os.path.basename(path)}")
return True