231 lines
9.8 KiB
Python
231 lines
9.8 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0004 EHR系统加班流程审核 插件 - 钉钉群机器人推送(插件内单一真源)。
|
||
|
||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||
|
||
约定:
|
||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||
|
||
用法:
|
||
main("需要推送的通知文本");
|
||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||
返回: {"success": bool, "message": str}
|
||
"""
|
||
import base64
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
from datetime import datetime
|
||
|
||
from ..config import logger
|
||
|
||
# ==================== 默认配置 ====================
|
||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||
|
||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||
DEV_SECRET = ''
|
||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||
|
||
ENV_CONFIGS = {
|
||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||
}
|
||
|
||
DEFAULT_TIMEOUT = 10
|
||
DEFAULT_RETRY_TIMES = 3
|
||
|
||
_STATUS_COLORS = {
|
||
'info': '#0077ff',
|
||
'success': '#00b300',
|
||
'warning': '#ff9900',
|
||
'error': '#ff0000',
|
||
}
|
||
|
||
|
||
def _build_sign(secret, timestamp_ms):
|
||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||
hmac_code = hmac.new(
|
||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||
).digest()
|
||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||
|
||
|
||
def _build_url(webhook, secret=''):
|
||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||
if not secret:
|
||
return webhook
|
||
ts = int(round(time.time() * 1000))
|
||
separator = '&' if '?' in webhook else '?'
|
||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||
|
||
|
||
class DingTalkRobot:
|
||
"""钉钉群机器人推送器。"""
|
||
|
||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||
self.timeout = timeout
|
||
if not self.webhook:
|
||
raise ValueError('webhook 不能为空')
|
||
|
||
def _post(self, payload):
|
||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||
last_err = None
|
||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||
try:
|
||
url = _build_url(self.webhook, self.secret)
|
||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||
req = urllib.request.Request(
|
||
url,
|
||
data=data,
|
||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||
)
|
||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||
body = resp.read().decode('utf-8')
|
||
resp_data = json.loads(body)
|
||
if resp_data.get('errcode') != 0:
|
||
raise RuntimeError(
|
||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||
f"errmsg={resp_data.get('errmsg')}"
|
||
)
|
||
return
|
||
except Exception as e:
|
||
last_err = e
|
||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||
time.sleep(1)
|
||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||
|
||
def send(self, title, content, status='info', server_name=''):
|
||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||
display_name = (server_name or self.server_name).strip()
|
||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||
|
||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||
text += content.strip() + "\n"
|
||
text += footer
|
||
|
||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||
self._post(payload)
|
||
|
||
def send_in_batches(self, title, content, status='info', server_name='',
|
||
max_chars=15000):
|
||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||
lines = content.strip().split('\n')
|
||
batches = []
|
||
current_batch = []
|
||
current_len = 0
|
||
|
||
for line in lines:
|
||
line_len = len(line) + 1
|
||
if current_len + line_len > max_chars and current_batch:
|
||
batches.append('\n'.join(current_batch))
|
||
current_batch = [line]
|
||
current_len = line_len
|
||
else:
|
||
current_batch.append(line)
|
||
current_len += line_len
|
||
|
||
if current_batch:
|
||
batches.append('\n'.join(current_batch))
|
||
|
||
total = len(batches)
|
||
for i, batch_content in enumerate(batches, 1):
|
||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||
|
||
|
||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||
if not blocks:
|
||
return []
|
||
result = []
|
||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||
for bi in range(total_batches):
|
||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||
content = header + '\n\n'.join(batch) + footer
|
||
result.append(content)
|
||
return result
|
||
|
||
|
||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||
env='prod', batch=False, max_chars=15000):
|
||
"""钉钉群机器人推送入口。
|
||
|
||
text 支持:
|
||
- 纯文本:单条 Markdown 推送;
|
||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||
- 文本列表:按顺序逐条发送。
|
||
|
||
返回: {"success": bool, "message": str}
|
||
"""
|
||
try:
|
||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||
or (isinstance(text, list) and not text):
|
||
return {'success': False, 'message': '通知文本不能为空'}
|
||
env_key = (env or 'prod').strip().lower()
|
||
if env_key not in ENV_CONFIGS:
|
||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||
cfg = ENV_CONFIGS[env_key]
|
||
webhook = (webhook or '').strip() or cfg['webhook']
|
||
secret = (secret or '').strip() or cfg['secret']
|
||
server_name = server_name or cfg['server_name']
|
||
if not webhook:
|
||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||
|
||
items = text if isinstance(text, list) else [text]
|
||
sent = 0
|
||
last_title, last_status = title, status
|
||
for item in items:
|
||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||
ti = item.get('title', title)
|
||
st = item.get('status', status)
|
||
bs = int(item.get('batch_size', 10) or 10)
|
||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||
sent += 1
|
||
last_title, last_status = ti, st
|
||
continue
|
||
if isinstance(item, dict):
|
||
t = item.get('text')
|
||
ti = item.get('title', title)
|
||
st = item.get('status', status)
|
||
bc = item.get('batch', batch)
|
||
mc = item.get('max_chars', max_chars)
|
||
else:
|
||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||
if t is None or not str(t).strip():
|
||
continue
|
||
if bc:
|
||
robot.send_in_batches(str(ti), str(t), status=st,
|
||
server_name=server_name, max_chars=mc)
|
||
else:
|
||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||
sent += 1
|
||
last_title, last_status = ti, st
|
||
if sent == 0:
|
||
return {'success': False, 'message': '通知文本为空'}
|
||
if len(items) == 1:
|
||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||
except Exception as e:
|
||
return {'success': False, 'message': str(e)}
|