0%

python控制钉钉Bot

钉钉的群组可以构建自定义机器人, 机器人添加成功之后会返回一个token, 你也可以在配置机器人的时候加签, 就会额外再返回一个secret, 提高通讯的安全性

但是这样操作会复杂不少, 下面先给出不配置加签的代码:

import requests
import json

# 钉钉机器人的webhook
webhook = "https://oapi.dingtalk.com/robot/send?access_token=your_token"

# 构建请求头部
header = {
    "Content-Type": "application/json",
    "Charset": "UTF-8"
}

# 构建请求数据,此处为发送文本信息
message ={
    "msgtype": "text",
    "text": {
        "content": "你想要发送的消息"
    },
    "at": {
        "isAtAll": True
    }
}

# 对请求数据进行json封装
message_json = json.dumps(message)

# 发送HTTP POST请求到钉钉webhook
info = requests.post(url=webhook, data=message_json, headers=header)

# 打印请求结果
print(info.text)

quite simple and beautiful!

如果你的钉钉机器人启用了加签安全设置,那么在发送消息时,你需要在URL中添加一个签名参数(sign)。

下面是如何生成签名的步骤:

  1. 获取当前时间戳和Secret
  2. 拼接成字符串并用HmacSHA256算法加密
  3. 将加密后的字符串进行Base64编码,得到签名
import requests
import json
import hmac
import hashlib
import base64
import urllib.parse
import time

# 钉钉机器人的access_token
access_token = "your_token"

# 钉钉机器人的Secret
secret = "your_secret"

# 获取当前时间戳(毫秒级),转换为字符串
timestamp = str(round(time.time() * 1000))

# 拼接需要加密的字符串
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')

# 使用HmacSHA256算法计算签名,并进行Base64编码
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

# 构建请求头部
header = {
    "Content-Type": "application/json",
    "Charset": "UTF-8"
}

# 构建请求数据,此处为发送文本信息
message ={
    "msgtype": "text",
    "text": {
        "content": "你想要发送的消息"
    },
    "at": {
        "isAtAll": True
    }
}

# 对请求数据进行json封装
message_json = json.dumps(message)

# 构建请求的URL,包含签名和时间戳
webhook = "https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}".format(access_token, timestamp, sign)

# 发送HTTP POST请求到钉钉webhook
info = requests.post(url=webhook, data=message_json, headers=header)

# 打印请求结果
print(info.text)