在钉钉 PC 端创建机器人

按照下面链接所述创建自定义机器人

https://open.dingtalk.com/document/robots/customize-robot-security-settings

基于 Python 将消息发送到钉钉群

使用关键字作为安全方式

以下代码”钉钉”为关键字,只需要复制 webhook

1
2
3
4
5
6
7
8
import requests

def send_msg(msg):
webhook='https://oapi.dingtalk.com/robot/send***' # url换成自己群机器人的
data={'msgtype':'text', 'text':{'content':msg}}
res=requests.post(webhook,json=data)

send_msg("钉钉-NNNNNCCCCBBB")

使用加签作为安全方式

需要依次复制密钥webhook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse

def sent_msg(webhook, secret, msg):
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')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
my_url = f"{webhook}&timestamp={timestamp}&sign={sign}"
message = { "msgtype": "text","text": {"content": msg},"at": {"isAtAll": False}}
message_json = json.dumps(message)
header = {"Content-Type": "application/json", "Charset": "UTF-8"}
info = requests.post(url=my_url, data=message_json, headers=header, verify=False)

if "__name__" == "__main__":
# 加签
secret = "SEC4ea8329b42ef4d99bfa4*****"
webhook = "https://oapi.dingtalk.com/robot/send?access_token*****"
msg = "xdd_lalalala_ooo"
sent_msg(webhook, secret, msg)