本文介绍如何使用钉钉内部机器人webhook发送群聊消息。


一、获取机器人webhook

群设置->群管理->机器人->webhook-> 复制url

image.png

二、消息类型

webhook 和 api 发送支持的消息类型参考链接: 消息类型和数据格式


三、编写脚本

import requests
import json
import logging

logging.basicConfig(level=logging.INFO,  # 设置日志级别
                    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
                    datefmt='%Y-%m-%d %H:%M:%S',  # 设置时间格式
                    filename='dingtalk_webhook.log',  # 设置日志文件名
                    filemode='a')  # 设置文件模式为追加


class DingTalkWebhook:
    def __init__(self,webhook_url):
        self.webhook_url = webhook_url
        self.logger = logging.getLogger('DingTalkWebhook')

    def sendmessage(self, message):
        """
        发送钉钉消息
        """
        headers = {'Content-Type': 'application/json;charset=utf-8'}
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": "自我介绍",
                "text": message
            }
        }
        try:
            res = requests.post(url=self.webhook_url, headers=headers, data=json.dumps(data))
            if res.status_code == 200:
                self.logger.info("Message sent sucessfully")
            else:
                self.logger.error("Failed to  send message: {res.text}")
        except Exception as e:
            self.logger.exception("Exception occurred while sending message")


if __name__ == "__main__":
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=4f5x2f9sad339axx3ds8b'
    messgae = '**我是张三**\n\n **我35岁**\n\n 我想发财\n\n'
    sendbywebhook = DingTalkWebhook(webhook_url)
    sendbywebhook.sendmessage(messgae)

发送效果: image.png