# -*- coding: utf-8 -*- """ @FileName: dingtalk_robot.py @Description: 钉钉群机器人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。 作为「37du钉钉群机器人推送」影刀自定义指令的模块源码, 供所有需要往钉钉群发通知的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等), 避免每个脚本各自内联 Webhook 加签与 Markdown 排版逻辑。 如何在影刀中创建指令: 1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块; 2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码); 3. 增加流程参数 params(字典类型,dict),或分别增加 msgtype/title/content/status 等参数; 4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装; 5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选): 方式A(推荐):流程中先拼一个字典变量(如 {"title": "任务执行失败", "content": "..."}), 作为 params 整体传入; 方式B:分别传 msgtype、title、content 等变量,指令内部自动拼成字典; 指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。 推送原理(HTTP Webhook 方式,与 app/utils/dingtalk_robot.py 一致): 按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名, 向机器人 Webhook 推送 JSON 消息,无需登录钉钉桌面端。 失败自动重试 3 次,成功/失败均有日志。 依赖: 仅使用 Python 标准库(urllib/hashlib/hmac/base64),零第三方依赖,无需 pip 安装。 约定(与项目 app 版一致,见 app/utils/dingtalk_robot.py): - 配置:影刀运行环境无 .env 文件读取,故推送地址/加签密钥/页脚署名 直接内联在下方「默认参数」区(单一真源),改推送目标时改常量即可; 也可在调用 main(args) 时通过 webhook/secret/server_name 参数覆盖; - 页脚署名默认 "小芒 任务调度平台": 注意:钉钉机器人若配置了"自定义关键词"安全校验, 页脚署名需包含该关键词(如 小芒)才会被接受。 入口: main(args) 影刀自定义指令调用入口 args = { "msgtype": "notification|text|markdown|actionCard(可选,默认 notification)", "title": "消息标题(notification/markdown/actionCard 使用)", "content": "消息正文,多行自动转引用块(notification 使用)", "text": "文本内容(msgtype=text 使用)", "status": "info|success|warning|error(可选,默认 info,决定标题颜色)", "at_mobiles": "需 @ 的手机号列表(可选;兼容逗号分隔字符串)", "at_user_ids":"需 @ 的用户 userid 列表(可选)", "is_at_all": "是否 @所有人(可选,默认 false)", "webhook": "机器人 webhook(可选,缺省用内联默认值)", "secret": "加签密钥(可选,缺省用内联默认值)", "server_name":"页脚署名(可选,缺省用内联默认值)", "single_title":"按钮文字(msgtype=actionCard 使用)", "single_url": "按钮跳转链接(msgtype=actionCard 使用)", } 通过流程参数传入(支持整字典 params 或分别传各字段) 返回 JSON 安全 dict:{"success": bool, "message": str} python dingtalk_robot.py 消息内容 [--title 标题] [--status info] [--webhook ...] [--secret ...] 独立运行(等价于 main({"title": ..., "content": ..., ...})) """ import base64 import hashlib import hmac import json import time import urllib.parse import urllib.request from datetime import datetime # ==================== 日志(print) ==================== class _PrintLogger: """影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。""" @staticmethod def debug(msg, *args): if args: msg = msg % args print(f"[DEBUG] {msg}") @staticmethod def info(msg, *args): if args: msg = msg % args print(f"[INFO] {msg}") @staticmethod def warning(msg, *args): if args: msg = msg % args print(f"[WARN] {msg}") @staticmethod def error(msg, *args): if args: msg = msg % args print(f"[ERROR] {msg}") logger = _PrintLogger() # ==================== 默认参数 ==================== # 影刀运行环境无 .env 文件读取,故 webhook/secret/署名直接内联在此(单一真源), # 需要调整推送目标时改这里即可;也可在调用 main(args) 时通过 webhook/secret/server_name 覆盖。 DEFAULT_WEBHOOK = ( 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66' ) DEFAULT_SECRET = '' # 加签密钥(未配置则不加签) DEFAULT_SERVER_NAME = '37du 任务调度平台' DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数 DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次) DINGTALK_ROBOT_ENDPOINT = 'https://oapi.dingtalk.com/robot/send' # 通知状态 → 标题颜色(与 app 版 dingtalk_robot.py 色板一致) _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)}" def _at_payload(at_mobiles=None, at_user_ids=None, is_at_all=False): """构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 dict。""" at = {} if at_mobiles: at['atMobiles'] = list(at_mobiles) if at_user_ids: at['atUserIds'] = list(at_user_ids) if is_at_all: at['isAtAll'] = True return at class DingTalkRobot: """ 钉钉群机器人推送器。 Args: webhook: 机器人 webhook 地址;缺省用内联默认值 DEFAULT_WEBHOOK secret: 加签密钥;缺省用内联默认值 DEFAULT_SECRET server_name: 页脚平台署名;缺省用内联默认值 DEFAULT_SERVER_NAME, 默认 "小芒 任务调度平台"(含关键词"小芒",可满足机器人自定义关键词校验) timeout: HTTP 请求超时秒数 Raises: ValueError: webhook 为空 """ 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 不能为空,请通过参数传入或修改模块内 DEFAULT_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')}" ) logger.debug('钉钉机器人推送成功,响应: %s', resp_data) 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 _build_footer(self, server_name=''): """构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 server_name。""" display_name = (server_name or self.server_name).strip() current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') return f"###### {display_name} | {current_time}" def send_text(self, content, at_mobiles=None, at_user_ids=None, is_at_all=False): """发送文本消息。""" if not content or not content.strip(): raise ValueError('content 不能为空') payload = {'msgtype': 'text', 'text': {'content': content}} at = _at_payload(at_mobiles, at_user_ids, is_at_all) if at: payload['at'] = at logger.info('钉钉机器人推送文本: %s', content[:50] + ('...' if len(content) > 50 else '')) self._post(payload) return True def send_markdown(self, title, text, at_mobiles=None, at_user_ids=None, is_at_all=False): """发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。""" if not title or not title.strip(): raise ValueError('title 不能为空') if not text or not text.strip(): raise ValueError('text 不能为空') payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}} at = _at_payload(at_mobiles, at_user_ids, is_at_all) if at: payload['at'] = at logger.info('钉钉机器人推送 Markdown: %s', title) self._post(payload) return True def send_notification( self, title, content, status='info', at_mobiles=None, at_user_ids=None, is_at_all=False, server_name='', append_footer=True, ): """ 统一通知方法(推荐业务方使用),样式与 app 版 dingtalk_robot.py 一致: **任务执行失败** ← 标题按 status 着色 内容详情: > 订单同步失败 ← 内容多行自动转引用块 > 错误原因:接口超时 --- ###### 小芒 任务调度平台 | 2026-08-14 14:30:00 ← 页脚:署名 + 当前时间 Args: title: 消息标题 content: 消息主体内容,支持多行(自动按行转引用块) status: 状态类型,决定标题颜色: info(蓝) | success(绿) | warning(橙) | error(红) at_mobiles: 需要 @ 的手机号列表 at_user_ids: 需要 @ 的用户 userid 列表 is_at_all: 是否 @所有人 server_name: 页脚署名,缺省用实例的 server_name append_footer: 是否自动追加页脚(署名 + 时间),默认 True Returns: 是否推送成功 Raises: ValueError: title 或 content 为空 """ if not title or not title.strip(): raise ValueError('title 不能为空') if not content or not content.strip(): raise ValueError('content 不能为空') color = _STATUS_COLORS.get(status, _STATUS_COLORS['info']) text = f"**{title}**\n\n" text += '内容详情:\n' for line in content.strip().splitlines(): line = line.strip() if line: # 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示 text += f"> {line} \n" if append_footer: text += f"\n\n---\n\n{self._build_footer(server_name)}" payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}} at = _at_payload(at_mobiles, at_user_ids, is_at_all) if at: payload['at'] = at logger.info('钉钉机器人推送通知 [%s]: %s', status, title) self._post(payload) return True def send_action_card( self, title, content, single_title, single_url, at_mobiles=None, at_user_ids=None, is_at_all=False, server_name='', ): """发送 ActionCard 消息(底部带按钮,如"点击下载报表")。""" if not title or not title.strip(): raise ValueError('title 不能为空') if not content or not content.strip(): raise ValueError('content 不能为空') if not single_title or not single_title.strip(): raise ValueError('single_title 不能为空') if not single_url or not single_url.strip(): raise ValueError('single_url 不能为空') text = f"**{title}**\n\n{content}\n\n---\n\n{self._build_footer(server_name)}" payload = { 'msgtype': 'actionCard', 'actionCard': { 'title': title, 'text': text, 'singleTitle': single_title, 'singleURL': single_url, }, } at = _at_payload(at_mobiles, at_user_ids, is_at_all) if at: payload['at'] = at logger.info('钉钉机器人推送 ActionCard: %s -> %s', title, single_url) self._post(payload) return True # ==================== 一次性便捷函数 ==================== def send_robot_text(content, webhook='', secret='', at_mobiles=None, at_user_ids=None, is_at_all=False): """一键发送文本到群机器人(webhook 缺省用内联默认值 DEFAULT_WEBHOOK)。""" robot = DingTalkRobot(webhook=webhook, secret=secret) return robot.send_text(content, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all) def send_robot_notification( title, content, status='info', webhook='', secret='', at_mobiles=None, at_user_ids=None, is_at_all=False, server_name='', ): """一键发送统一通知(样式与 send_notification 一致)。""" robot = DingTalkRobot(webhook=webhook, secret=secret) return robot.send_notification( title, content, status=status, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all, server_name=server_name, ) # ==================== 影刀自定义指令入口 ==================== def _to_list(value): """把 at_mobiles / at_user_ids 参数归一为 list:列表原样返回,字符串按逗号拆。""" if value is None: return None if isinstance(value, (list, tuple)): return [str(v).strip() for v in value if str(v).strip()] if isinstance(value, str): return [v.strip() for v in value.replace(',', ',').split(',') if v.strip()] return [str(value)] def _send_one(args): """按 args 字典发送一条消息,返回 {success: bool, message: str}。""" try: msgtype = str(args.get('msgtype', '') or 'notification').strip().lower() or 'notification' webhook = str(args.get('webhook', '') or '').strip() secret = str(args.get('secret', '') or '').strip() server_name = str(args.get('server_name', '') or '').strip() at_mobiles = _to_list(args.get('at_mobiles')) at_user_ids = _to_list(args.get('at_user_ids')) is_at_all = bool(args.get('is_at_all', False)) title = str(args.get('title', '') or '').strip() content = str(args.get('content', '') or '') text = str(args.get('text', '') or '').strip() status = str(args.get('status', '') or 'info').strip().lower() or 'info' robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name) if msgtype == 'text': if not text: return {'success': False, 'message': 'msgtype=text 时参数 text 不能为空'} robot.send_text(text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all) return {'success': True, 'message': f"已发送文本消息({len(text)} 字)"} if msgtype == 'markdown': if not title or not text: return {'success': False, 'message': 'msgtype=markdown 时参数 title/text 不能为空'} robot.send_markdown( title, text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all ) return {'success': True, 'message': f'已发送 Markdown 消息:{title}'} if msgtype == 'actioncard': single_title = str(args.get('single_title', '') or '').strip() single_url = str(args.get('single_url', '') or '').strip() if not title or not content or not single_title or not single_url: return { 'success': False, 'message': 'msgtype=actionCard 时参数 title/content/single_title/single_url 不能为空', } robot.send_action_card( title, content, single_title, single_url, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all, server_name=server_name, ) return {'success': True, 'message': f'已发送 ActionCard:{title}'} # 默认 notification if not title or not content.strip(): return {'success': False, 'message': '参数 title/content 不能为空'} robot.send_notification( title, content, status=status, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all, server_name=server_name, ) return {'success': True, 'message': f"已发送通知 [{status}]:{title}"} except Exception as e: return {'success': False, 'message': str(e)} def main(args): """ 影刀自定义指令「37du钉钉群机器人推送」调用入口。 args: dict,通过流程变量传入(影刀变量支持传字典/列表): 方式A(批量,推荐):args = {"messages": [{msgtype?, title?, content?, ...}, ...]} messages 为「字典列表」,逐条推送并返回汇总结果; 方式B(单条):args = {"params": {...}} 或直接 {"msgtype":..., "title":..., "content":...}; 返回: dict 单条: {success: bool, message: str} 批量: {success: bool, message: str, sent: int, failed: int, results: [...]} """ if not args: args = {} # 兼容「整个字典作为 params 传入」的用法 if isinstance(args.get('params'), dict): merged = dict(args) merged.update(args['params']) args = merged # 批量:messages 为字典列表,逐条推送 if isinstance(args.get('messages'), list): results = [_send_one(m) for m in args['messages']] ok = sum(1 for r in results if r.get('success')) return { 'success': ok == len(results), 'message': f'共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}', 'sent': ok, 'failed': len(results) - ok, 'results': results, } # 单条推送 return _send_one(args) if __name__ == '__main__': # 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。 # 批量测试:流程变量 messages = 字典列表,每条含 title/content,main 逐条推送并汇总。 import argparse parser = argparse.ArgumentParser(description='钉钉群机器人消息推送工具(影刀指令源码独立运行)') parser.add_argument('content', nargs='?', default='', help='消息正文/文本(多行可用换行分隔)') parser.add_argument('-t', '--title', default='消息通知', help='消息标题') parser.add_argument('--status', default='info', choices=['info', 'success', 'warning', 'error'], help='通知状态(决定标题颜色)') parser.add_argument('--msgtype', default='notification', choices=['notification', 'text', 'markdown', 'actionCard'], help='消息类型') parser.add_argument('-w', '--webhook', default='', help='机器人 webhook,缺省用内联默认值') parser.add_argument('-s', '--secret', default='', help='加签密钥,缺省用内联默认值') parser.add_argument('--name', default='', help='页脚平台署名,缺省用内联默认值') parser.add_argument('--all', action='store_true', help='@所有人') parser.add_argument('--text', default='', help='msgtype=text/markdown 时的文本内容') parser.add_argument('--single-title', default='点击查看', help='actionCard 按钮文字') parser.add_argument('--single-url', default='https://www.37du.co', help='actionCard 按钮链接') _cli = parser.parse_args() _params = { 'msgtype': _cli.msgtype, 'title': _cli.title, 'content': _cli.content, 'text': _cli.text, 'status': _cli.status, 'webhook': _cli.webhook, 'secret': _cli.secret, 'server_name': _cli.name, 'is_at_all': _cli.all, 'single_title': _cli.single_title, 'single_url': _cli.single_url, } result = main(_params) print('最终结果:', result)