From 30a237829b542e21040aa99a4c23320ea118db98 Mon Sep 17 00:00:00 2001 From: aszerW Date: Sun, 12 Oct 2025 15:43:30 +0800 Subject: [PATCH] =?UTF-8?q?=E9=92=89=E9=92=89=E6=9C=BA=E5=99=A8=E4=BA=BA?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0markdown?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dingtalk.py | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/dingtalk.py b/dingtalk.py index 9318a05..a4264fe 100644 --- a/dingtalk.py +++ b/dingtalk.py @@ -34,6 +34,7 @@ class DingTalkBot: url = f"{self.webhook}×tamp={timestamp}&sign={sign}" return url + def send_text(self, content: str, at_mobiles=None, is_at_all=False): """ 发送文本消息 @@ -65,9 +66,55 @@ class DingTalkBot: except Exception as e: logger.error(f"钉钉消息发送异常: {e}") + def send_markdown(self, title: str, text: str, at_mobiles=None, is_at_all=False): + """ + 发送markdown消息 + + :param title: 消息标题 + :param text: markdown格式的消息内容 + :param at_mobiles: 需要@的手机号组成的列表,可选 + :param is_at_all: 是否@所有人,默认False + """ + at_mobiles = at_mobiles or [] + data = { + "msgtype": "markdown", + "markdown": { + "title": title, + "text": text + }, + "at": { + "atMobiles": at_mobiles, + "isAtAll": is_at_all + } + } + + url = self._gen_signed_url() if self.secret else self.webhook + + try: + response = requests.post(url, json=data, timeout=5) + response.raise_for_status() + result = response.json() + if result.get("errcode", -1) != 0: + logger.error(f"钉钉markdown消息发送失败: {result}") + else: + logger.info("钉钉markdown消息发送成功") + except Exception as e: + logger.error(f"钉钉markdown消息发送异常: {e}") + if __name__ == "__main__": webhook = "https://oapi.dingtalk.com/robot/send?access_token=fb70c1561d8beba94b4f11568f4bb15e3ae07ccbdc8ac19676434a9d1cd17546" # 填写你的webhook secret = "SEC1ae7cd2f1a6f9da3611af37da3e7d954c1e8533fc073c6c8cc5e5af3b6e5926b" # 填写你的加签token(如果有),否则留空 dingtalk = DingTalkBot(webhook, secret) - dingtalk.send_text("测试消息") \ No newline at end of file + dingtalk.send_text("测试消息") + + # 测试markdown消息 + markdown_content = """ +## 系统通知 +- **状态**: 正常运行 +- **CPU使用率**: 65% +- **内存使用率**: 78% + +> 详细信息请查看监控面板 + """ + dingtalk.send_markdown("系统状态报告", markdown_content) \ No newline at end of file