以前公司用的企业QQ,没有对应的webapi接口可以发送一些群消息方便发布成功后通知,现在换了钉钉里面有个群机器人,可以接收POST消息发送消息,分享下方法
1 群设置添加机器人》只能群助手
2 添加一个标签 用于发送验证
3 我用的是python脚本
token 从这里复制出来
# -*- coding: utf-8 -*-
#@
import time
import hmac
import hashlib
import base64
import urllib2
import urllib
import json
#https://ding-doc.dingtalk.com/doc#/bgb96b/ok9au2 参考API文档
# 一个POST事件 post_string 是发送的数据内容
def dingtalk_bot_text(url, post_string, at_mobiles=None):
data = {
'msgtype': 'text', 'text': {'content': '%s' % post_string},"at": {"atMobiles": at_mobiles,"isAtAll": 'false'}
}
json_str = json.dumps(data)
req = urllib2.Request(url, json_str)
req.add_header('Content-type', 'application/json')
response = urllib2.urlopen(req, timeout=120)
return response.read()
# 一个POST事件 post_string 是发送的数据内容
def dingtalk_bot_link(url, title,linkurl,post_string, at_mobiles=None):
data = {
'msgtype': 'link',
"link": {
"text": post_string,
"title": title,
"picUrl": "",
"messageUrl": linkurl
},
"at": {"atMobiles": at_mobiles,
"isAtAll": 'false'
}
}
json_str = json.dumps(data)
req = urllib2.Request(url, json_str)
req.add_header('Content-type', 'application/json')
response = urllib2.urlopen(req, timeout=120)
return response.read()
#获取机器人签名 再群机器上查找 secret
def getdingTalkSign(secret):
timestamp = long(round(time.time() * 1000))
secret_enc = bytes(secret).encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = bytes(string_to_sign).encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.quote_plus(base64.b64encode(hmac_code))
return sign,timestamp
# 文字内容
def SendDingTalk_text(msg):
token="xxxxx"
secret = 'xxx'
sign,timestamp= getdingTalkSign(secret);
s = "https://oapi.dingtalk.com/robot/send?access_token={0}×tamp={1}&sign={2}".format(token,timestamp,sign)
print(s)
request=dingtalk_bot_text(s, msg)
print(request)
# 发布带连接地址 url:连接 title:标题 msg:显示内容
def SendDingTalk_url(url,title,msg):
token="xxx"
secret = 'xxx'
sign,timestamp= getdingTalkSign(secret);
s = "https://oapi.dingtalk.com/robot/send?access_token={0}×tamp={1}&sign={2}".format(token,timestamp,sign)
print(s)
# request=dingtalk_bot_text(s, msg)
# print(request)
request=dingtalk_bot_link(s,title,url,msg)
print(request)
#SendDingTalk("xxxxxxx");
# token="xxx"
# timestamp = long(round(time.time() * 1000))
# secret = 'xxx'
# sign = getdingTalkSign(secret);
# s = "https://oapi.dingtalk.com/robot/send?access_token={0}×tamp={1}&sign={2}".format(token,timestamp,sign)
# print(s)
# request=dingtalk_bot(s, "test2")
# print(request)
测试内容 可配合jenkins 发布后成功后 调用下这个脚本即可