#!/usr/bin/env python
# encoding: utf8
# Author: zepinglai
#python 3.8
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
def send_msg_text(access_token,secret,content):
secret_enc = secret.encode('utf-8')
timestamp = str(round(time.time() * 1000))
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))
webhook = "https://oapi.dingtalk.com/robot/send?access_token=%s×tamp=%s&sign=%s" %(access_token,timestamp,sign)
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
message = {
"msgtype": "text",
"text": {
"content": content
},
"at": {
"atMobiles": [""],
"isAtAll": False
}
}
message_json = json.dumps(message)
res = requests.post(url=webhook,data=message_json,headers=header)
return res.text
def send_msg_markdown(access_token,secret,title,text):
secret_enc = secret.encode('utf-8')
timestamp = str(round(time.time() * 1000))
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))
webhook = "https://oapi.dingtalk.com/robot/send?access_token=%s×tamp=%s&sign=%s" %(access_token,timestamp,sign)
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
message = {
"msgtype": "markdown",
"markdown": {
"title": title ,
"text": text
},
"at": {
"atMobiles": [""],
"isAtAll": False
}
}
message_json = json.dumps(message)
res = requests.post(url=webhook,data=message_json,headers=header)
return res.text
if __name__=="__main__":
# 钉钉机器人信息
access_token = 'ze938fcf8f80a90464b26b25d43e99fe7c291c9b8320f360c8e83wwwlinxuhubcn'
secret = 'SECzz525afc9bb354d424f2361b4d563e26bd9e564bd095ca5a4wwwlinxuhubcn'
# text
content = '你好, 泽泽!'
print(send_msg_text(access_token,secret,content))
# markdown
title = "项目发布通知"
text = "### 发布成功 \n\n>项目: java-demo\n\n>环境: prd\n\n>日期时间: 2020-09-05 11:56"
print(send_msg_markdown(access_token,secret,title,text))