# -*- coding: utf-8 -*-
"""
@Module: utils.dingtalk_robot
@FileName: dingtalk_robot.py
@Author: 小布丁
@CreateTime: 2026-08-14
@Description: 钉钉群机器人消息推送模块(自定义机器人 Webhook 方式)——项目级通用推送能力,
供请假/加班/考勤/雇主险等所有业务模块复用,不绑定任何具体业务。
提供统一通知方法 send_notification(标题按状态着色 + 内容代码块 + 页脚署名带时间),
样式参照 DingTalkBot.send_notification。
与 dingtalk_sender(桌面客户端模拟)不同,本模块走 HTTP 推送,无需登录钉钉桌面端。
推送地址、加签密钥、页脚平台署名可通过环境变量配置:
DINGTALK_ROBOT_WEBHOOK = https://oapi.dingtalk.com/robot/send?access_token=xxx
DINGTALK_ROBOT_SECRET = 加签密钥(未配置则不加签)
DINGTALK_ROBOT_NAME = 页脚平台署名,默认 "37du 任务调度平台"
注意:钉钉机器人若配置了"自定义关键词"安全校验,
页脚署名需包含该关键词(如 37du)才会被接受。
失败自动重试 3 次,成功/失败均有日志;响应细节仅 DEBUG 级别输出,避免大 JSON 刷屏。
@Version: 2.0.0
使用示例:
from app.utils.dingtalk_robot import DingTalkRobot, send_robot_notification
# 统一通知(推荐):标题按 status 着色,内容多行用 ```text 代码块包裹,自动追加页脚署名+时间
robot = DingTalkRobot()
robot.send_notification(
"任务执行失败",
"订单同步失败\n错误原因:接口超时",
status="error",
)
# 底部带按钮的 ActionCard(如报表下载)
robot.send_action_card(
"报表已生成",
"7 月考勤报表已生成,点击下方按钮下载",
single_title="点击下载报表",
single_url="https://xxx/download",
)
# 纯文本
robot.send_text("测试消息")
"""
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.parse
import urllib.request
from datetime import datetime
from typing import List, Optional
from app.utils.intelligent_retry import retry
from app.utils.logger import get_logger
logger = get_logger(__name__)
# ==================== 环境变量加载 ====================
from app.common.env import load_app_env
def _load_env_file():
"""
加载 app/.env(不覆盖已存在的环境变量,始终定位 app 根,与 cwd 无关)。
"""
load_app_env()
_load_env_file()
# ==================== 默认参数 ====================
DEFAULT_WEBHOOK = os.getenv("DINGTALK_ROBOT_WEBHOOK", "").strip()
DEFAULT_SECRET = os.getenv("DINGTALK_ROBOT_SECRET", "").strip()
DEFAULT_SERVER_NAME = os.getenv("DINGTALK_ROBOT_NAME", "").strip() or "37du 任务调度平台"
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
DINGTALK_ROBOT_ENDPOINT = "https://oapi.dingtalk.com/robot/send"
# 通知状态 → 标题颜色(与 aa.md 中 DingTalkBot.send_notification 色板一致)
_STATUS_COLORS = {
"info": "#0077ff", # 蓝色
"success": "#00b300", # 绿色
"warning": "#ff9900", # 橙色
"error": "#ff0000", # 红色
}
def _build_sign(secret: str, timestamp_ms: int) -> str:
"""按钉钉加签规则计算签名(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: str, secret: str = "") -> str:
"""拼接最终推送地址:配置了 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: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> dict:
"""构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 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 地址;缺省时读取环境变量 DINGTALK_ROBOT_WEBHOOK
secret: 加签密钥;缺省时读取环境变量 DINGTALK_ROBOT_SECRET
server_name: 页脚平台署名;缺省时读取环境变量 DINGTALK_ROBOT_NAME,
默认 "37du 任务调度平台"(含关键词"37du",可满足机器人自定义关键词校验)
timeout: HTTP 请求超时秒数
Raises:
ValueError: webhook 为空
"""
def __init__(
self,
webhook: str = "",
secret: str = "",
server_name: str = "",
timeout: int = 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 不能为空,请通过参数传入或配置环境变量 DINGTALK_ROBOT_WEBHOOK"
)
@retry(max_attempts=DEFAULT_RETRY_TIMES)
def _post(self, payload: dict):
"""推送 payload 到机器人,errcode != 0 视为失败(重试由装饰器负责)。"""
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")
data = json.loads(body)
if data.get("errcode") != 0:
raise RuntimeError(
f"钉钉机器人返回错误 errcode={data.get('errcode')}, "
f"errmsg={data.get('errmsg')}"
)
logger.debug("钉钉机器人推送成功,响应: %s", data)
def _build_footer(self, server_name: str = "") -> str:
"""构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 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: str,
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> bool:
"""
发送文本消息。
Args:
content: 文本内容
at_mobiles: 需要 @ 的手机号列表
at_user_ids: 需要 @ 的用户 userid 列表
is_at_all: 是否 @所有人
Returns:
是否推送成功
Raises:
ValueError: content 为空
"""
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: str,
text: str,
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> bool:
"""
发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。
Args:
title: 消息标题(显示在会话中)
text: Markdown 正文
at_mobiles: 需要 @ 的手机号列表
at_user_ids: 需要 @ 的用户 userid 列表
is_at_all: 是否 @所有人
Returns:
是否推送成功
Raises:
ValueError: title 或 text 为空
"""
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: str,
content: str,
status: str = "info",
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
server_name: str = "",
append_footer: bool = True,
raw: bool = False,
) -> bool:
"""
统一通知方法(推荐业务方使用),默认固定格式(代码块包裹),支持自定义 Markdown 格式:
默认格式(raw=False):
**任务执行失败** ← 标题按 status 着色
内容详情:
```text
订单同步失败 ← 内容整体用 ```text 代码块包裹
错误原因:接口超时 (按纯文本渲染,不再做 Markdown 解析)
```
---
###### 小芒 任务调度平台 | 2026-08-14 14:30:00
自定义格式(raw=True):
**请假审批** ← 标题按 status 着色
# 【请假审批】需人工复核 共2条 ← 内容直接渲染 Markdown
---
> **【单据1】** ← 引用块、加粗、超链接等均可渲染
> 姓名:张三
> [查看详情](https://...)
---
###### 小芒 任务调度平台 | 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
raw: 是否直接渲染 Markdown(默认 False)。
- False: 内容包裹在 ```text 代码块中,钉钉按纯文本渲染(原行为,向后兼容);
- True: 内容直接作为 Markdown 发送,钉钉会渲染引用块、加粗、超链接、列表等。
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"])
if raw:
# 自定义 Markdown 格式:内容直接渲染
text = f"**{title}**\n\n"
text += content.strip() + "\n"
else:
# 固定格式:内容包裹在 ```text 代码块中
text = f"**{title}**\n\n"
text += "内容详情:\n"
text += "```text\n"
text += content.strip() + "\n"
text += "```\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
fmt = "Markdown" if raw else "text"
logger.info("钉钉机器人推送通知 [%s/%s]: %s", status, fmt, title)
self._post(payload)
return True
def send_in_batches(
self,
title: str,
content: str,
status: str = "info",
server_name: str = "",
raw: bool = False,
max_chars: int = 15000,
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> bool:
"""
分批发送长内容(按行智能拆分,避免切断单行数据)。
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
每批带「第 N/M 批」标题前缀,便于接收方识别。
Args:
title: 消息标题
content: 消息正文(长文本)
status: 状态类型,决定标题颜色
server_name: 页脚署名
raw: 是否直接渲染 Markdown
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
at_mobiles: 需要 @ 的手机号列表
at_user_ids: 需要 @ 的用户 userid 列表
is_at_all: 是否 @所有人
Returns:
是否推送成功
"""
lines = content.strip().split('\n')
batches: list = []
current_batch: list = []
current_len = 0
for line in lines:
line_len = len(line) + 1 # +1 for newline
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_notification(
batch_title, batch_content, status=status,
server_name=server_name, raw=raw,
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
)
return True
def send_action_card(
self,
title: str,
content: str,
single_title: str,
single_url: str,
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
server_name: str = "",
) -> bool:
"""
发送 ActionCard 消息(底部带按钮,如"点击下载报表")。
Args:
title: 消息标题
content: 卡片正文(支持多行)
single_title: 按钮文字
single_url: 按钮跳转链接
at_mobiles: 需要 @ 的手机号列表
at_user_ids: 需要 @ 的用户 userid 列表
is_at_all: 是否 @所有人
server_name: 页脚署名,缺省用实例的 server_name
Returns:
是否推送成功
Raises:
ValueError: title / content / single_title / single_url 任一为空
"""
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_action_card_in_batches(
self,
title: str,
content_lines: list,
single_title: str,
single_url: str,
server_name: str = "",
batch_size: int = 15,
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> bool:
"""分批发送 ActionCard(按条目分组,每批一张卡片)。
Args:
title: 卡片标题(会自动加「第N/M批」后缀)
content_lines: 每条内容的列表,每个元素是一条完整的 Markdown 条目
single_title: 底部按钮文字
single_url: 底部按钮跳转链接
server_name: 页脚署名
batch_size: 每批最多包含的条目数(默认 15)
"""
total = len(content_lines)
num_batches = (total + batch_size - 1) // batch_size
for batch_idx in range(num_batches):
start = batch_idx * batch_size
end = min(start + batch_size, total)
sub_items = content_lines[start:end]
current = batch_idx + 1
md_parts = [f"# {title}"]
md_parts.append(f"第{current}/{num_batches}批(共{total}条)")
md_parts.append("")
for item in sub_items:
md_parts.append("---")
md_parts.append(item)
md_content = "\n".join(md_parts)
batch_title = f"{title} 第{current}/{num_batches}批"
logger.info("ActionCard 分批推送 %d/%d: %s", current, num_batches, batch_title)
self.send_action_card(
batch_title, md_content, single_title, single_url,
server_name=server_name,
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
)
return True
# ==================== 一次性便捷函数 ====================
def send_robot_text(
content: str,
webhook: str = "",
secret: str = "",
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
) -> bool:
"""一键发送文本到群机器人(webhook 缺省取环境变量 DINGTALK_ROBOT_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: str,
content: str,
status: str = "info",
webhook: str = "",
secret: str = "",
at_mobiles: Optional[List[str]] = None,
at_user_ids: Optional[List[str]] = None,
is_at_all: bool = False,
server_name: str = "",
raw: bool = False,
batch: bool = False,
max_chars: int = 15000,
mode: str = "markdown",
single_title: str = "查看详情",
single_url: str = "",
batch_size: int = 15,
) -> bool:
"""一键发送统一通知(样式与 send_notification 一致)。
Args:
batch: 是否启用分批发送(默认 False)。True 时调用 send_in_batches。
max_chars: 单批最大字符数,仅在 batch=True 时生效。
mode: 推送模式:
'markdown' - 标准 Markdown 消息(引用块/加粗/超链接)
'action_card' - ActionCard 卡片消息(底部带按钮跳转)
single_title: ActionCard 底部按钮文字(仅 mode='action_card' 时生效)
single_url: ActionCard 底部按钮跳转链接(仅 mode='action_card' 时生效)
batch_size: ActionCard 每批最多包含的条目数(仅 mode='action_card' 时生效)
"""
robot = DingTalkRobot(webhook=webhook, secret=secret)
if mode == "action_card":
lines = [content] if isinstance(content, str) else list(content)
return robot.send_action_card_in_batches(
title, lines, single_title, single_url,
server_name=server_name, batch_size=batch_size,
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
)
if batch:
return robot.send_in_batches(
title, content, status=status,
server_name=server_name, raw=raw, max_chars=max_chars,
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
)
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, raw=raw,
)
# ==================== 命令行入口(便于手动测试) ====================
def main():
import argparse
parser = argparse.ArgumentParser(description="钉钉群机器人消息推送工具")
parser.add_argument("content", help="消息内容(多行可用换行分隔)")
parser.add_argument("-t", "--title", default="消息通知", help="消息标题")
parser.add_argument("--status", default="info",
choices=["info", "success", "warning", "error"], 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="@所有人")
args = parser.parse_args()
send_robot_notification(
args.title, args.content, status=args.status,
webhook=args.webhook, secret=args.secret,
server_name=args.name, is_at_all=args.all,
)
if __name__ == "__main__":
main()