python发送钉钉机器人消息
# --*--coding:utf-8 --*--
import requests
import time
import hashlib
import hmac
import base64
import re
import urllib3
from base.tools import Tools
class DingTalk():
def sendMessage(self,message = ''):
secret = '' #机器人配置
access_token = ''#机器人配置
timestamp = int(round(time.time() * 1000))
data = (str(timestamp) + '\n' + secret).encode('utf-8')
secret = secret.encode('utf-8')
signature = base64.b64encode(hmac.new(secret, data, digestmod=hashlib.sha256).digest())
reg = re.compile(r"'(.*)'")
signature = str(re.findall(reg,str(signature))[0])
url = 'https://oapi.dingtalk.com/robot/send?access_token=%s&sign=%s×tamp=%s' % (access_token,signature,timestamp)
headers = {"Content-Type": "application/json ;charset=utf-8 "}
try:
urllib3.disable_warnings()
response = requests.post(url, headers = headers, json = message, timeout = (3,60),verify=False)
response_msg = str(response.status_code) + ' ' + str(response.content)
print(response_msg)
except Exception as error_msg:
print('error_msg==='+str(error_msg))
response_msg = error_msg
return response_msg
def send_report_to_dingTalk(self):
msg = {"msgtype": "text", "text":
{
"content": 内容
},
"at": {'atMobiles': ['phone'],#要@的人
"isAtAll": False}}#是否要@所有人
self.sendMessage(msg)
print(msg)
self.sendMessage(msg)
if __name__ == "__main__":
DingTalk().send_report_to_dingTalk()
点赞,格式修改下。
改好了