通过钉钉机器人发送群消息

(1)进入钉钉群聊

  • 打开 钉钉 App网页版(https://im.dingtalk.com)。
  • 进入 需要发送消息的群聊
  • 点击右侧上方设置

通过钉钉机器人发送群消息_第1张图片

(2)添加机器人

  • 点击 群设置 > 智能群助手 > 添加机器人
  • 选择 自定义机器人,然后点击 添加

通过钉钉机器人发送群消息_第2张图片

(3)配置机器人

  • 选择“自定义关键词”或者“加签”(推荐加签,安全性更高)。
  • 复制 Webhook 地址,稍后需要用到。
  • 点击确定,之后保存URL

通过钉钉机器人发送群消息_第3张图片

(4)发送消息实现代码

import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

def generate_dingtalk_url(webhook, secret):
    """
    根据 webhook 和 secret 生成完整的钉钉机器人 URL。
    """
    # 获取当前时间戳
    timestamp = str(round(time.time() * 1000))
    # 计算签名
    # 钉钉签名算法
    string_to_sign = f'{timestamp}\n{secret}'
    # 使用 HMAC-SHA256 签名
    hmac_code = hmac.new(secret.encode('utf-8'), 
                         string_to_sign.encode('utf-8'), 
                         digestmod=hashlib.sha256).digest()
    # 对签名进行 Base64 编码
    # 并进行 URL 编码
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    # 拼接完整的 URL
    # 注意:这里的 webhook 是钉钉机器人的 URL,secret 是加密密钥
    return f"{webhook}×tamp={timestamp}&sign={sign}"

# 发送钉钉消息
# 这里的 webhook 是钉钉机器人的 URL,secret 是加密密钥
def send_dingtalk_message(webhook, secret, message):
    """
    发送钉钉机器人消息。
    """
    # 生成完整的钉钉机器人 URL
    url = generate_dingtalk_url(webhook, secret)
    # 设置请求头
    headers = {
        "Content-Type": "application/json"
    }
    # 设置消息内容
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    # 发送 POST 请求
    # 使用 requests 库发送 POST 请求
    response = requests.post(url, json=data, headers=headers)
    # 检查响应状态
    if response.status_code == 200:
        print("消息发送成功:", response.json())
    else:
        print("消息发送失败:", response.status_code, response.text)
# 示例 webhook 和 secret
# 请替换为实际的 webhook 和 secret
webhook = "钉钉机器人的URL"
secret = "钉钉机器人的密钥或签名"
message = "你好,这是通过钉钉机器人发送的测试消息!"
send_dingtalk_message(webhook, secret, message)

你可能感兴趣的:(钉钉,机器人,python)