Python实现钉钉发送报警消息的方法实现钉钉发送报警消息的方法
今天小编就为大家分享一篇Python实现钉钉发送报警消息的方法,具有很好的参考价值,希望对大家有所帮
助。一起跟随小编过来看看吧
钉钉开放平台传送门:https://open.dingtalk.com
我司使用钉钉作为内部通讯工具,基本上大家在电脑和手机上都开着,消息可以第一时间查看,报警消息的即时性要求比较
高,所以适合用钉钉通知。
下面介绍如何用Python实现钉钉发送报警消息。
获取获取access token
要使用钉钉发送消息,首先需要获取access token,代码如下:
def get_access_token():
url = 'https://oapi.dingtalk.com/gettoken?corpid=%s&corpsecret=%s' % (corp_id, corp_secret)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
response_str = response.read()
response_dict = json.loads(response_str)
error_code_key = "errcode"
access_token_key = "access_token"
if response_dict.has_key(error_code_key) and response_dict[error_code_key] == 0 and response_dict.has_key(access_token_key):
return response_dict[access_token_key]
else:
return ''
access token在2小时内有效,有效期内重复获取返回相同结果,有效期会自动延长。corp_id和corp_secret是企业的id和
secret,在钉钉的管理后台可以找到。另外,上面用到了urllib2和json,需要import:
import urllib2
import json
消息类型消息类型
钉钉的消息类型分为:text,image,voice,file,link和OA,具体消息格式参见:https://open-
doc.dingtalk.com/docs/doc.htm?treeId=172&articleId=104972&docType=1 。
下面以发送文本,链接和文件消息为例进行说明。
给用户发送消息给用户发送消息
发送文本发送文本
def send_text_to_users(access_token, users, text):
msg_type, msg = _gen_text_msg(text)
return _send_msg_to_users(access_token, users, msg_type, msg)
def _gen_text_msg(text):
msg_type = 'text'
msg = { "content": text }
return msg_type, msg
def _send_msg_to_users(access_token, users, msg_type, msg):
to_users = '|'.join(users)
body_dict = {
"touser": to_users,
"agentid": agent_id,
"msgtype": msg_type
}
body_dict[msg_type] = msg
body = json.dumps(body_dict)
return _send_msg("https://oapi.dingtalk.com/message/send?access_token=", access_token, body)
其中agent_id是一个钉钉应用的id,以钉钉应用的名义给用户发送消息。users是用户id列表,每个用户id是一个字符串。
发送链接发送链接
def send_link_to_users(access_token, users, url, title, text):
msg_type, msg = _gen_link_msg(url, title, text)
return _send_msg_to_users(access_token, users, msg_type, msg)
def _gen_link_msg(url, title, text):
msg_type = 'link'
评论0