博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python自定义钉钉机器人发送自动化结果报告
阅读量:6648 次
发布时间:2019-06-25

本文共 5094 字,大约阅读时间需要 16 分钟。

环境python3.5+jenkins

# coding:utf-8import urllib.requestimport jsonimport sysimport timeimport reclass dingHook(object):    def __init__(self,sys):        self.msg = sys.argv[1:]        self.url = "https://oapi.dingtalk.com/robot/send?access_token=30eee8d20287b0051d7c25cc6e468dcdd01XXXX"    def request(self, url, method, data=None, head={}):        request = urllib.request.Request(url=url, headers=head)        request.get_method = lambda: method        httpRes = urllib.request.urlopen(request, data)        content = httpRes.read()        httpRes.close()        return content    def post_start(self):        data = {}        data["msgtype"] = "text"        data["text"] = {}        data["text"]["content"] = " jenkins:开始执行{}自动化......".format(self.msg[0])        data = json.dumps(data).encode(encoding='UTF8')        head = {"Content-Type": "application/json"}        content = self.request(self.url, "POST", data, head)        print(content)        return content    def post_link(self, text, title, picurl="", messageurl=""):        data = {}        data["msgtype"] = "link"        data["link"] = {}        data["link"]["text"] = text        data["link"]["title"] = title        data["link"]["picUrl"] = picurl        data["link"]["messageUrl"] = messageurl        data = json.dumps(data).encode(encoding='UTF8')        head = {"Content-Type": "application/json"}        content = self.request(self.url, "POST", data, head)        print(content)        return content    def post_result(self):        i = 0        result = "FAILURE"        # 获取当前jenkins构建版本号        get_buildnum = r"C:\Users\ASUS\.jenkins\jobs\{}\nextBuildNumber".format(self.msg[0])        with open(get_buildnum, encoding='utf-8')  as fd:             num = fd.read()        buildNumber = str(int(num)-1)        print(buildNumber)        # 获取jenkins自动化执行结果        get_buildresult = r"C:\Users\ASUS\.jenkins\jobs\{}\builds\{}\log".format(self.msg[0], buildNumber)        # with open(get_buildresult)  as output_result:        #      print("result:",output_result.name)        #      build_result = output_result.read()        #获取结果报告中的返回结果        name_re = r'\\Report\\report\\(.*?.html)'        with open(get_buildresult )  as fd:             log_content = fd.read()        html_name = re.findall(name_re, log_content)        get_RF_result = r'C:\Users\ASUS\.jenkins\jobs\{}\htmlreports\HTML_Report\{}'.format(self.msg[0], html_name[0])        print(get_RF_result)        # jenkins自动化结果报告地址        messageurl = "http://localhost:8080/job/{}/HTML_Report" .format(self.msg[0])        # 钉钉结果报告消息图片        picurl = "D:/work/ClTest/pased.jpg"        picurl = "http://localhost:8080/job/{}/HTML_Report/pased.jpg".format(self.msg[0])         # 钉钉结果报告标题        title = "【%s】执行结果" % self.msg[0]        print(title)        try:            with open(get_buildresult )  as fd:                build_result = fd.read()                #防止生成报告没这么快,报错时先等待5s                if "No such file or directory" in build_result:                    time.sleep(5)                #判断jenkins自动化是否执行结束                if  "Finished" in build_result:                    with open(get_RF_result,encoding='UTF-8' )  as fd:                            output_rf_result = fd.read()                    result = r'

Results

' failure_index = output_rf_result.find(result) result_content = output_rf_result[failure_index:] print(result_content) failure_api = re.findall(r'
]*>(.*?)', result_content,re.I|re.M) print(failure_api) failure_api = ["- " + a + '\n\n' for a in failure_api] for a in failure_api: if 'Failed' in a: result = " {}自动化执行失败!\n".format(self.msg[0]) print(a) content = self.post_link(text=result, title=title, messageurl=messageurl, picurl=picurl) return content result = "{}自动化执行成功!\n".format(self.msg[0]) content = self.post_link(text=result, title=title, messageurl=messageurl, picurl=picurl) return content # fail_case = int(case_count_list[1]) # suc_case = int(case_count_list[3]) # if fail_case == 0: # result = "SUCCESS-成功:%d-失败:%d" % (suc_case,fail_case) # else: # result = "FAILURE-成功:%d-失败:%d" % (suc_case,fail_case) except Exception as e: print(e) time.sleep(10) def ding_hook(self, itype="start"): if itype == "start": self.post_start() elif itype == "end": self.post_result()if __name__ == '__main__': dh = dingHook(sys) print(dh.ding_hook(sys.argv[2]))

  运行命令:python urllib-test.py 工程名 end

问题:TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

data = json.dumps(data)这行后加个.encode(encoding='UTF8')

 

转载于:https://www.cnblogs.com/dieyaxianju/p/8321452.html

你可能感兴趣的文章
Sql server在另一台服务器,在Visual Studio 中没问题,IIS中 提示“在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。。。。”...
查看>>
Zookeeper
查看>>
linux 系统备份还原
查看>>
动态生成Menu
查看>>
插入排序
查看>>
JDBC的封装
查看>>
记录Html+Css流程表格
查看>>
webform 复合控件
查看>>
硬盘分区后丢失的文件怎么恢复
查看>>
Codevs 1021 (玛丽卡)
查看>>
C# 程序性能提升篇-1、装箱和拆箱,枚举的ToString浅析
查看>>
电梯模拟系统——BUAA OO第二单元作业总结
查看>>
V3 微信支付-预支付C#
查看>>
legend2---开发日志6(后端和前端如何相互配合(比如php,js,元素状态和数据改变))...
查看>>
关于宏的一点注意
查看>>
CentOS7.0使用Yum安装Nginx
查看>>
laravel获取checkbox值的小技巧
查看>>
安装DotNetCore.1.0.1-VS2015Tools.Preview2.0.2出现0x80072f8a未指定的错误
查看>>
Java关于String类的赋值符号一些验证
查看>>
android OTA更新
查看>>