本文介绍如何使用Python3程序通过钉钉群机器人发送消息到群中。
钉钉群机器人有三种安全设置,本文使用加签方式,理论上兼容其他两种。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#钉钉群机器人 Python3版
import time,datetime
import hmac,hashlib,base64
import urllib.parse
import requests
import json
class DINGDING:
apiurl = "https://oapi.dingtalk.com"
def __init__(self, accesstoken, secret):
self.access_token = accesstoken
self.secret = secret
# 发送消息,群机器人
def send_message_group(self, type, data):
if type not in ["text", "link", "markdown", "actionCard", "feedCard"] or not data:
raise Exception("ERROR type %s or empty data"%(type))
return
msg = {
'msgtype' : type,
}
if type == "text":
msg[type] = {'content' : data}
elif type == "link":
msg[type] = data
elif type == "markdown":
msg[type] = data
elif type == "actionCard":
msg[type] = data
elif type == "feedCard":
msg[type] = {'links' : data}
else:
msg["msgtype"] = "text"
msg["text"] = {'content' : "不支持的消息类型 " + type}
params = {
'timestamp' :str(round(time.time() * 1000))
}
params['sign'] = self.signature(params)
url = self.apiurl + '/robot/send?access_token=%s×tamp=%s&sign=%s'%(self.access_token, params['timestamp'], params['sign'])
return self.http_request_v2(url, method = "POST", headers=self.header(params), params = msg)
# headers头
def header(self, params):
headers = {}
headers['Content-Type'] = "application/json"
return headers
# 签名函数
def signature(self, params):
string_to_sign = (params['timestamp'] + "\n" + self.secret)
hmac_code = hmac.new(self.secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()
return urllib.parse.quote((base64.b64encode(hmac_code)))
# 请求函数
def http_request_v2(self, url, method="GET", headers={}, params=None):
headers['User-Agent'] = 'Mozilla/5.0 \(Windows NT 6.1; WOW64\) AppleWebKit/537.36 \(KHTML, like Gecko\) Chrome/39.0.2171.71 Safari/537.36'
if method == "GET":
response = requests.get(url, headers=headers)
elif method == "POST":
data = bytes(json.dumps(params), 'utf-8')
response = requests.post(url, headers=headers, data=data)
elif method == "DELETE":
response = requests.delete(url, headers=headers, data=data)
result = response.json()
return result
调用方法
dingding = DINGDING("", "")
result = dingding.send_message_group("text", "https://blog.youkuaiyun.com/bitquant\n比特量化\n" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'));
link_card = {"title":"比特量化", "text":"今年中秋节公司有豪礼相送", "picUrl":"http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png", "messageUrl" :"https://www.baidu.com/"}
result = dingding.send_message_group("link", link_card);
markdown_card = {"title":"比特量化", "text":"#### 杭州天气 @150XXXXXXXX \n> 9度,西北风1级,空气良89,相对温度73%\n> \n> ###### 10点20分发布 [天气](https://www.dingtalk.com) \n"}
result = dingding.send_message_group("markdown", markdown_card);
card = {
"title": "乔布斯 20 年前想打造一间苹果咖啡厅,而它正是 Apple Store 的前身",
"text": ' ### 乔布斯 20 年前想打造的苹果咖啡厅 \n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划',
"btnOrientation": "0",
"singleTitle" : "阅读全文",
"singleURL" : "https://www.dingtalk.com/"
}
card = {
"title": "我 20 年前想打造一间苹果咖啡厅,而它正是 Apple Store 的前身",
"text": " \n\n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划",
"hideAvatar": "0",
"btnOrientation": "0",
"btns": [
{
"title": "内容不错",
"actionURL": "https://www.dingtalk.com/"
},
{
"title": "不感兴趣",
"actionURL": "https://www.dingtalk.com/"
}
]
}
result = dingding.send_message_group("actionCard", card);
data = [] #列表
data.append({"title":"中秋节礼品领取", "picURL":"http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png", "messageURL" :"https://www.baidu.com/"})
data.append({"title":"多图文2标题", "picURL":"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "messageURL" :"https://www.baidu.com/"})
data.append({"title":"多图文3标题", "picURL":"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "messageURL" :"https://www.baidu.com/"})
# # print(data)
result = dingding.send_message_group("feedCard", data);
print(result)
pass
效果图

1万+



被折叠的 条评论
为什么被折叠?



