一、添加钉钉机器人
步骤一,登录钉钉,在机器人管理页面选择“自定义”机器人,输入机器人名字并选择要发送消息的群。如果需要的话,可以为机器人设置一个头像。点击“完成添加”,完成后会生成Webhook地址
步骤二,点击“复制”按钮,即可获得这个机器人对应的Webhook地址,其格式如下:
https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx
二、获取timestamp与sign参数
# 获取timestamp参数
timestamp = str(round(time.time() * 1000))
# 获取sign参数
secret = 'this is secret'
secret_enc = secret.encode('utf-8')
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))
三、推送消息完整代码
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
from common.common_logger import Logger
'''
对接钉钉消息通知
'''
# 自己写的记录日志方法
basepagelog = Logger('logger', r'D:\po_test\outputs\\').getlog()
def dingding(test_report):
# 获取时间
timestamp = str(round(time.time() * 1000))
secret = 'this is secret'
secret_enc = secret.encode('utf-8')
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))
access_token = ''
url = 'https://oapi.dingtalk.com/robot/send?access_token={}×tamp={}&sign={}'.format(access_token,
timestamp, sign)
# 获取当前时间
str_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
# 发送的消息格式
data = {"msgtype": "markdown",
"markdown": {
"title": "测试已完成",
"text": r"#### {}测试报告生成成功 \n> 存放地址:\\192.168.1.80\share\TestFolder\自动化分享\测试文件夹\n> "
r"![微信截图_20200817153548.png](https://i.loli.net/2020/08/17/gKVw2qTXYf3aPRG.png)"
r"\n> ###### {}生成成功\n".format(test_report, str_time)
},
"at": {"atMobiles": ["15386174586"]}
}
headers = {'Content-Type': 'application/json'}
message = requests.post(url, json.dumps(data), headers=headers).json()
# 将操作的状态记录到日志中
if message['errmsg'] == 'ok':
return basepagelog.info('钉钉消息推送成功')
else:
return basepagelog.error('钉钉消息推送失败')