def send_dingtalk_markdown(webhook, title, text): if (text is not None or text != ''): dingtalk = DingtalkChatbot(webhook) dingtalk.send_markdown( title=title, text=text, at_mobiles=['15257183801', '13738375762', '18310593253'])
def sendding(title, content): at_mobiles = ['186xxxx2487', '158xxxx3364'] Dingtalk_access_token = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxx' # 初始化机器人小丁 xiaoding = DingtalkChatbot(Dingtalk_access_token) # Markdown消息@指定用户 xiaoding.send_markdown(title=title, text=content, at_mobiles=at_mobiles)
def dingding(self, dic): # WebHook地址 webhook = 'https://oapi.dingtalk.com/robot/send?access_token=e5cc9f86eb85e5c9caef97638c6b92c36e09123c541f77289a7840071146a463' # 初始化机器人小丁 dingding = DingtalkChatbot(webhook) self.logger.info("开始发送钉钉.....") dic = dict(sorted(dic.items(), key=lambda x: x[0])) content = '[' + time.strftime('%Y-%m-%d', time.localtime()) + '日]Redis数据', data = '' for k, v in dic.items(): data += "> **" + str(k) + "** : " + "<font color=#FF0000>" + str( v) + "</font> \n\n" try: dingding.send_markdown( title='Redis数据', text='# ' + str(content[0]) + '\n\n' + data, ) self.logger.info("发送成功.....") except Exception as e: self.logger.info("发送失败.....") self.logger.info("失败原因:" + str(e)) sys.exit(1)
def sen(): if new != old: webhook = '' xiaoding = DingtalkChatbot(webhook) xiaoding.send_markdown(title='News', text='### ' + titl + '\n' 'ITNews:' + new + '\n\n' 'Link:' + link) pickle.dump(new, open('summary.txt', 'wb')) else: print('Nothing')
def dingding(self, content=None, mobiles=None): # 此处您可以改写下面的接口对接企业接口,消息会推送到个人的消息中心 key = NOTICE['DINGDING']['key'] xiaoding = DingtalkChatbot(NOTICE['DINGDING']['webhook']) content = '\n'.join(['\n\n'.join(content), key]) # 如果通知人mobile存在,at指定的用户,否则at all if mobiles: xiaoding.send_markdown(title='新的工单', text=content, at_mobiles=mobiles) else: xiaoding.send_markdown(title='新的工单', text=content, is_at_all=True)
def send_url_msg(title, url): """将登陆连接以Markdown发送至手机,点击后即可完成登陆""" # 获取钉钉消息信息 webhook = global_config.getRaw('messenger', 'webhook') secret = global_config.getRaw('messenger', 'secret') xiaoding = DingtalkChatbot(webhook, secret=secret) xiaoding.send_markdown( title=title, text="[%s](%s)" % (url, url) )
class Push(object): def __init__(self, token): self.d = DingtalkChatbot( 'https://oapi.dingtalk.com/robot/send?access_token=%s' % token) def sendImage(self, title, content, url, is_at_all=False): self.d.send_markdown(title=title, text=content + '\n![Giao](' + url + ')\n', is_at_all=is_at_all) def sendMessage(self, msg, is_at_all=False): self.d.send_text(msg=msg, is_at_all=is_at_all)
def send_merge_result_message(self, username, result, merge_url): get_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) sendInfoTitle = "发送工单合并结果信息!" sendInfoText = "## **{}发起了mr通知** \n" \ "+ 审批人: {} {}\n" \ "+ 执行结果: {}\n" \ "+ [点击查看]({}) {}".format(username, "shijf", "shijf", result, merge_url, get_time) at_mobiles = ['18365597692'] xiaoding = DingtalkChatbot(WEEBHOOK) xiaoding.send_markdown(title=sendInfoTitle, text=sendInfoText, at_mobiles=at_mobiles)
def dd_send(novel_name, novel_title, novel_content): from dingtalkchatbot.chatbot import DingtalkChatbot, is_not_null_and_blank_str, ActionCard, FeedLink, CardItem webhook_token = '' webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' + webhook_token secret = '' # 可选:创建机器人勾选“加签”选项时使用 xiaoding = DingtalkChatbot(webhook, secret=secret) # 方式二:勾选“加签”选项时使用(v1.5以上新功能) now = datetime.now() now_time = now.strftime("%Y年%m月%d日 %H:%M:%S") dd_content = '''%s \n %s \n %s \n %s ''' % (novel_name, novel_title, novel_content, now_time) send_title = novel_name + " " + novel_title xiaoding.send_markdown(title=send_title, text=dd_content)
def send_merge_message(self, data, target_url): get_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) sendInfoTitle = "发送工单提交信息!" sendInfoText = "## **{}发起了mr通知** \n" \ "+ 审批人: {} {}\n" \ "+ [点击查看]({}) {}".format( data['user']['username'], "shijf", "shijf", target_url, get_time) print("sendInfoText=================>", sendInfoText) at_mobiles = [] xiaoding = DingtalkChatbot(WEEBHOOK) xiaoding.send_markdown(title=sendInfoTitle, text=sendInfoText, at_mobiles=at_mobiles)
def ding_message(): '''初始化钉钉对象''' xiaoding = DingtalkChatbot(webhook) at_mobiles = ['1373633366'] '''获取所有服务的app名和服务类型,并存到字典中''' applicationLists = get_applications() # print(applicationLists) '''轮询application,查询每个application在过去五分钟内的总错误数,并通过钉钉报警''' for app in applicationLists: application_name = app['applicationName'] service_type = app['serviceType'] error_count = update_servermap(application_name, from_time=From_TimeStamp, to_time=To_TimeStamp, serviceType=service_type)[0] slow_count = update_servermap(application_name, from_time=From_TimeStamp, to_time=To_TimeStamp, serviceType=service_type)[1] threes_count = update_servermap(application_name, from_time=From_TimeStamp, to_time=To_TimeStamp, serviceType=service_type)[2] fives_count = update_servermap(application_name, from_time=From_TimeStamp, to_time=To_TimeStamp, serviceType=service_type)[3] error_text = message_text("ERROR", error_count, service_type, application_name) slow_text = message_text("SLOW", error_count, service_type, application_name) threes_text = message_text("3s", error_count, service_type, application_name) fives_text = message_text("5s", error_count, service_type, application_name) '''如果总调用错误数超过阈值5(根据实际需求进行设置),则报警''' if error_count >= 1: xiaoding.send_markdown(title='pinpoint报警', text=error_text, at_mobiles=at_mobiles) if slow_count >= 3: xiaoding.send_markdown(title='pinpoint报警', text=slow_text, at_mobiles=at_mobiles) if threes_count >= 60: xiaoding.send_markdown(title='pinpoint报警', text=threes_text, at_mobiles=at_mobiles) if fives_count >= 30: xiaoding.send_markdown(title='pinpoint报警', text=fives_text, at_mobiles=at_mobiles)
def execute(): params = parse_params(request) key = str(params['key']) content = str(params['content']) atAll = bool(params['atAll']) robot = find_robot_by_key(config['robots'], key) if not robot: return {'status': 'error', 'msg': '未找到机器人'} try: from dingtalkchatbot.chatbot import DingtalkChatbot, ActionCard, FeedLink, CardItem new_webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' + robot.access_token xiaoding = DingtalkChatbot(new_webhook, secret=robot.access_secret, pc_slide=True, fail_notice=False) xiaoding.send_markdown(title=robot.push_title, text=content, is_at_all=atAll) return {'status': 'ok', 'msg': '发送成功'} except ImportError: return {'status': 'error', 'msg': '请引入 dingtalkchatbot 模块'} except Exception as error: return {'status': 'error', 'msg': '发送失败' + str(error)}
class Push(object): def __init__(self, token=None, keyWord=None, weiboRef=None, weiboCookie=None, weiboSCF=None, weixinToken=None): self.useDingTalk = False self.useWeibo = False self.useSCF = False self.useWeixin = False if token and keyWord: self.useDingTalk = True self.d = DingtalkChatbot( 'https://oapi.dingtalk.com/robot/send?access_token=%s' % token) self.keyWord = keyWord if weiboRef and weiboCookie: self.useWeibo = True self.weibo = Weibo(weiboRef, weiboCookie) if weiboSCF: self.useSCF = True self.weiboSCF = weiboSCF if weixinToken: self.useWeixin = True self.wxurl = 'https://sc.ftqq.com/%s.send' % weixinToken def sendMsg(self, title, msg, is_at_all=False): if self.useDingTalk: self.d.send_markdown(title=self.keyWord + title, text=msg, is_at_all=is_at_all) if self.useWeibo: self.weibo.send(msg) if self.useSCF: requests.post(self.weiboSCF, data=msg.encode("utf-8")) if self.useWeixin: data = {'text': title, 'desp': msg} requests.post(self.wxurl, data=data)
def transpond_link_to_dingding(title, info, message_url): # Webhook地址 webhook = 'https://oapi.dingtalk.com/robot/send?access_token=7398bd6b0ec02211bb818c92836c8aa3bd7442de56bad7a029c4245aa41bf79b' # 初始化机器人Eva Eva = DingtalkChatbot(webhook) # 消息@列表 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") text = '''#### %s\n > 详情: %s\n > 详情链接: %s\n > ###### 报警时间:%s\n''' % (title, info, message_url, current_time) # at_mobiles = [15313900930] # Eva.send_markdown(title=title,text=text,at_mobiles=at_mobiles) Eva.send_markdown( title='氧气文字', text='#### 广州天气\n' '> 9度,西北风1级,空气良89,相对温度73%\n\n' '> ![美景](http://www.sinaimg.cn/dy/slidenews/5_img/2013_28/453_28488_469248.jpg)\n' '> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n', is_at_all=True)
def dingding(notice, mstype, title, token): webhook = 'https://oapi.dingtalk.com/robot/send?access_token=%s' % (token) xiaoding = DingtalkChatbot(webhook) try: if mstype == 'markdown': dingres = xiaoding.send_markdown(title, text=notice) else: dingres = xiaoding.send_text(msg=notice, is_at_all=True) if dingres['errcode'] == 0: logging.info('钉钉消息发送成功, response message: %s' % (dingres)) else: logging.error('钉钉消息发送失败, error message: %s' % (dingres)) except Exception as err: logging.error('钉钉消息发送失败, error message: %s' % (err))
class DingMessage: """ 调用钉钉机器人发送测试结果 """ def __init__(self, run_type): self.run_type = run_type if run_type == 'auto': webhook = 'https://oapi.dingtalk.com/robot/send?access_token=998422738ca7d32f8641e9369da7f1b5545aa09c8fcec5ae17324e609c5d1af0' # webhook = 'https://oapi.dingtalk.com/robot/send?access_token=cb1ece248f594144a11bc0cf467ae4fd0f73beb3133f6a79b16d07ef23da0a59' # 调试机器人 elif run_type == 'deploy': webhook = 'https://oapi.dingtalk.com/robot/send?access_token=16c4dbf613c5f1f288bbf695c1997ad41d37ad580d94ff1a0b7ceae6797bbc70' # webhook = 'https://oapi.dingtalk.com/robot/send?access_token=cb1ece248f594144a11bc0cf467ae4fd0f73beb3133f6a79b16d07ef23da0a59' # 调试机器人 self.robot = DingtalkChatbot(webhook) def send_ding_msg(self, summary, report_name=None): msg_and_fail_count = format_summary_to_ding('markdown', summary, report_name=report_name) msg = msg_and_fail_count[0] fail_count = msg_and_fail_count[1] title = 'FasterRunner自动化测试报告' if fail_count == 0: if self.run_type == 'deploy': print("deploy_success") elif self.run_type == 'auto': self.robot.send_markdown(title=title, text=msg) else: if self.run_type == 'deploy': self.robot.send_markdown(title=title, text=msg, is_at_all=True) elif self.run_type == 'auto': receive_msg_mobiles = [18666126234, 18122118571, 13763312220, 15989041619, 18665742877, 13512756535] # 接收钉钉消息的列表 at_phone = '' for phone in [f'@{phone} ' for phone in receive_msg_mobiles]: at_phone += phone msg += at_phone self.robot.send_markdown(title=title, text=msg, at_mobiles=receive_msg_mobiles)
def result_to_dingding(case_name, case_path, file_name, dingding_conect, port, test_name): ''' 送钉钉消息,目前支持三种格式 :param case_name: 本次测试用例名称 :param case_path: 测试用例脚本路径,用于脚本下载 :param file_name: 测试报告路径,用于测试报告浏览 :param dingding_conect: 测试报告结果,字典形式用于钉钉发送内容 :param port: web服务器端口,按模块分配不同的商品,用于web端服务器启动 :param test_name: 测试人员名字 :return: ''' #判断是为空 nowtime = strftime("%Y-%m-%d %H:%M:%S") # 获取测试时间 if file_name is None or file_name == '': pass logger.info(file_name) # 初始化机器人小丁 xiaoding = DingtalkChatbot(config.config['webhook']) # jmeter报告发布目录 jmeter_path = 'https://four.gicdev.com/DmTest/jmeter/' # 获取测试人员手机号 test_mobile = eval(config.config['test_mobile']) # 图片加文本样式(3) request_url = f'{jmeter_path}html/request/{file_name}' detail_url = f'{jmeter_path}html/detail/{file_name}' failure_url = f'{jmeter_path}html/failure/{file_name}' case_url = f'{jmeter_path}{case_path}' send_info = f"<font color=\'#FFA500\'>[通知] </font>[{case_name}接口测试结果..]({request_url}) \n\n --- \n\n " \ f"<font color=\'#708090\' size=2>脚本下载:</font><font color=\'#708090\' size=3>[{dingding_conect['脚本']}]({case_url})</font> \n\n " \ f"<font color=\'#708090\' size=2>脚本更新:</font><font color=\'#708090\' size=3>[点击更新脚本](http://10.105.220.75:{port}/)</font> \n\n " \ f"<font color=\'#708090\' size=2>更新模块:</font><font color=\'#708090\' size=3>{dingding_conect['模块']}</font> \n\n " \ f"<font color=\'#708090\' size=2>用例数量:</font><font color=\'#708090\' size=3>{dingding_conect['请求数量']}</font> \n\n " \ f"<font color=\'#FF0000\' size=2>失败数量:</font><font color=\'#708090\' size=3>[{dingding_conect['失败']}]({failure_url})</font> \n\n " \ f"<font color=\'#708090\' size=2>成 功 率:</font><font color=\'#708090\' size=3>{dingding_conect['成功率']}</font> \n\n " \ f"<font color=\'#708090\' size=2>平均响应时间:</font><font color=\'#708090\' size=3>{dingding_conect['平均响应时间']}</font> \n\n " \ f"<font color=\'#708090\' size=2>测试人员:</font><font color=\'#708090\' size=2>{test_name}</font> \n\n " \ f"</font><font color=\'#708090\' size=2>测试时间:</font><font color=\'#708090\' size=2>{nowtime}</font> \n\n " \ f"--- \n\n @{test_mobile[test_name]} <font color=\'#888888\' size=2>[查看详细报告]({detail_url}) </font>" #逻辑有错误的列表,将error字段拼接msg taplink = '' # try: # for i in range(len(errorlist)): # dinglink = f"<font color=\'#708090\' size=2>失败用例{str(i+1)}:</font><font color=\'#708090\' size=3>[失败名称]({testcase_url})</font> \n\n " # dinglink = dinglink.replace( '失败名称', str(errorlist[i][2:5]) ) # taplink += dinglink # except Exception as e: # logger.info(e) # send_info = send_info.replace( '问题链接', taplink ) message_data = xiaoding.send_markdown(title=f'{case_name}接口测试结果..', text=send_info, at_mobiles=[{test_mobile[test_name]} ]) logger.info(f'钉钉发送:--> {message_data}') # if '__name__' == '__main__': # sendmessage( 'apitest' ) # '#### 接口自动化执行结果... \n' # '> %s \n' % (msg) + '\n' # '> \n' # '> ###### 测试报告详情: @13989812663 [查看](%s) \n' % (message_url),
def dingding(mobile, text): webhook = 'https://oapi.dingtalk.com/robot/send?' \ 'access_token=da5e3827feba9cb2eed57dfb2a4d6272d92c6a331f377931f6e801a97b3f55ae' xiaoding = DingtalkChatbot(webhook) xiaoding.send_markdown(title='禅道通知', text=text, at_mobiles=[mobile])
if not row: continue else: ts = row.TIMESTAMP.strftime("%Y-%m-%d %H:%M:%S") k = len(row.alarm_id) for alist in alertlist: if alist in row.alarm_message: if len(theyare) > 0 and row.alarm_id in theyare: i = theyare.index(row.alarm_id) j = round((row.TIMESTAMP - thendid[i]).total_seconds()) if j > dly_rpt: alert_msg = '### 报警信息:\n > %s \n\n > %s \n\n' % ( ts, row.alarm_message[k:]) xiaoding.send_markdown(title='报警信息', text=alert_msg, is_at_all=True) print(ts, row.alarm_message[k:]) thendid[i] = row.TIMESTAMP else: theyare.append(row.alarm_id) thendid.append(row.TIMESTAMP) break if haltflag in row.alarm_message and ( row.TIMESTAMP - lasthalt).total_seconds() > dly_hlt: alert_msg = '### 报警信息:\n > %s \n\n > %s \n\n' % ( ts, row.alarm_message[k:]) xiaoding.send_markdown(title='报警信息', text=alert_msg, is_at_all=True)
def pusher(*args): msg = args[0] othermsg = "" for i in range(1, len(args)): othermsg += args[i] othermsg += "\n" SCKEY = os.environ.get('SCKEY') # http://sc.ftqq.com/ SCTKEY = os.environ.get('SCTKEY') # http://sct.ftqq.com/ Skey = os.environ.get('Skey') # https://cp.xuthus.cc/ Smode = os.environ.get('Smode') # send, group, psend, pgroup, wx, tg, ww, ding(no send email) pushplus_token = os.environ.get('pushplus_token') # http://pushplus.hxtrip.com/ pushplus_topic = os.environ.get('pushplus_topic') # pushplus一对多推送需要的"群组编码",一对一推送不用管 dingding_token = os.environ.get('dingding_token') # dingding robot webhook token dingding_secret = os.environ.get('dingding_secret') # dingding rebot webhook secret if dingding_token: sendurl = f"https://oapi.dingtalk.com/robot/send?access_token={dingding_token}" ding_bot = DingtalkChatbot(sendurl,secret=dingding_secret) ding_bot.send_markdown(title=msg,text=f'#### {msg}\n' f'> {othermsg}\n\n', is_at_all=False) if SCKEY: sendurl = f"https://sc.ftqq.com/{SCKEY}.send" data = { "text" : msg, "desp" : othermsg } requests.post(sendurl, data=data) if SCTKEY: sendurl = f"https://sctapi.ftqq.com/{SCTKEY}.send" data = { "title" : msg, "desp" : othermsg } requests.post(sendurl, data=data) if pushplus_token: sendurl = f"http://pushplus.hxtrip.com/send" if not othermsg: othermsg = msg if pushplus_topic: params = { "token" : pushplus_token, "title" : msg, "content" : othermsg, "template" : "html", "topic" : pushplus_topic } else: params = { "token" : pushplus_token, "title" : msg, "content" : othermsg, "template" : "html" } r = requests.post(sendurl, params=params) print(r.json()) if r.json()["code"] != 200: print(f"pushplus推送失败!{r.json()['msg']}") if Skey: if not Smode: Smode = 'send' if othermsg: msg = msg + "\n" + othermsg sendurl = f"https://push.xuthus.cc/{Smode}/{Skey}" params = {"c" : msg} requests.post(sendurl, params=params)
from dingtalkchatbot.chatbot import DingtalkChatbot mark_down_data = """ {color} *{color}* **{color}** ***{color}*** ****{color}**** *****{color}***** <font color=#FF0000>纯红</font> <font color=#FF0000>纯红</font> <font color=#008000>纯绿</font> """ markdown_file = mark_down_data.format(color='mark_down格式调试') # 测试群 webhook = "https://oapi.dingtalk.com/robot/send?access_token=2606c23eaf70851235a10785081a8fedcc72d210c9379c9b960c32d571372b8a" secret = "SEC2fe3fce80cc0a5b2de41423c540b8f58c2f2c393a7c2ec28c75d9bdd0062939e" xiaoding = DingtalkChatbot(webhook, secret=secret) xiaoding.send_markdown(title='太空杀数据播报', text=markdown_file, is_at_all=False) print("播报已发送")
from dingtalkchatbot.chatbot import DingtalkChatbot import sys sys.path.append("../") import config webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' + config.dingTalkWebhookAccessToken xiaoding = DingtalkChatbot(webhook) # Text MSG and at all # xiaoding.send_text(msg='Giao!看我头像') xiaoding.send_markdown(title='x', text='![Giao](http://xxx/20191205/11:08:13.jpg)\n', is_at_all=True)
xiaoding.send_text(msg='我就是小丁,小丁就是我!', at_mobiles=at_mobiles) # link xiaoding.send_link( title='万万没想到,某小璐竟然...', text='故事是这样子的...', message_url= 'http://www.kwongwah.com.my/?p=454748", pic_url="https://pbs.twimg.com/media/CEwj7EDWgAE5eIF.jpg' ) # markdown # 1、提醒所有人 xiaoding.send_markdown( title='氧气文字', text='#### 广州天气\n' '> 9度,西北风1级,空气良89,相对温度73%\n\n' '> ![美景](http://www.sinaimg.cn/dy/slidenews/5_img/2013_28/453_28488_469248.jpg)\n' '> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n', is_at_all=True) # 2、提醒指定手机用户,需要在text参数中@用户 xiaoding.send_markdown( title='氧气文字', text='#### 广州天气\n' '> 9度,西北风1级,空气良89,相对温度73%\n\n' '> ![美景](http://www.sinaimg.cn/dy/slidenews/5_img/2013_28/453_28488_469248.jpg)\n' '> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n', at_mobiles=at_mobiles) # 整体跳转ActionCard btns1 = [{"title": "查看详情", "actionURL": "https://www.dingtalk.com/"}] actioncard1 = ActionCard(
def ding_message(message_text): xiaoding = DingtalkChatbot(webhook) at_mobiles = ['1373633366'] xiaoding.send_markdown(title="micro server 报警", text=message_text, at_mobiles=at_mobiles)
WHEN 'push' THEN '推送' WHEN 'banner' THEN '资源位' WHEN 'abTest' THEN '测试弹窗' WHEN 'webhook' THEN 'WebHook' END message_type, count(1) as cnt FROM messages_data t1 JOIN projects t2 ON t1.project_id = t2."id" WHERE t1.project_id NOT IN {str(tuple(conf.project.exclude)).replace(',)', ')')} GROUP BY t1.project_id, t2."name", t1.message_type ORDER BY t1.project_id; ''' messages_data = pd.read_sql_query(messages_sql, growing_conn) growing_conn.close() # 数据透视 messages_data = messages_data.rename(columns={"project_name": "项目名称", "message_type": "任务类型"}) result = messages_data.pivot_table('cnt', index='项目名称', columns='任务类型').fillna(0).sort_values(by='普通弹窗', ascending=0) # 追加总计 result = result.reset_index().append(result.sum(axis=0).to_dict(), ignore_index=True).fillna('总计').set_index('项目名称') image = tools.dataframe_to_image(result) url = tools.upload_image(conf, image) xiaoding = DingtalkChatbot(webhook=conf.dingding.webhook, secret=conf.dingding.secret) xiaoding.send_markdown(title='昨日用户运营使用情况\n', text='#### 数据详情\n\n' f'![报告]({url})\n', is_at_all=False)
xiaoding.send_text(msg='我就是小丁,小丁就是我!', at_mobiles=at_mobiles) # # image xiaoding.send_image(pic_url='http://pic1.win4000.com/wallpaper/2020-03-11/5e68b0557f3a6.jpg') # link xiaoding.send_link(title='万万没想到,某小璐竟然...', text='故事是这样子的...', message_url='http://www.kwongwah.com.my/?p=454748', pic_url='https://pbs.twimg.com/media/CEwj7EDWgAE5eIF.jpg') # markdown # 1、提醒所有人 xiaoding.send_markdown(title='氧气文字', text='#### 广州天气\n' '> 9度,西北风1级,空气良89,相对温度73%\n\n' '> ![美景](http://www.sinaimg.cn/dy/slidenews/5_img/2013_28/453_28488_469248.jpg)\n' '> ###### 10点20分发布 [天气](https://www.seniverse.com/) \n', is_at_all=True) # 2、提醒指定手机用户,并在text内容中自定义”@用户“的位置 xiaoding.send_markdown(title='氧气文字', text='#### 广州天气 @18825166XXX\n' '> 9度,西北风1级,空气良89,相对温度73%\n\n' '> ![美景](http://www.sinaimg.cn/dy/slidenews/5_img/2013_28/453_28488_469248.jpg)\n' '> ###### 10点20分发布 [天气信息](https://www.seniverse.com/)\n', at_mobiles=at_mobiles, is_auto_at=False) # 整体跳转ActionCard btns1 = [CardItem(title="查看详情", url="https://www.dingtalk.com/")] actioncard1 = ActionCard(title='万万没想到,竟然...', text='![markdown](http://www.songshan.es/wp-content/uploads/2016/01/Yin-Yang.png) \n### 故事是这样子的...', btns=btns1, btn_orientation=1,
def check_mysql_slowlog(): # 定义阈值参数 # 指定时间范围内执行次数大于100 cnt_value = 200 # 指定时间范围内SQL的平均响应时间,单位:ms avg_value = 100 # 忽略的库或参数 ignore_values = ['information_schema', 'performance_schema', 'THROTTLE'] # webhook webhook = "https://oapi.dingtalk.com/robot/send?access_token=8469850b137b308" \ "b24151fe136dc128ab471bc782e8f2e735abab6eac175ad10" # 初始化requests会话 s = requests.Session() s.auth = ('pmm_user', 'pmm@yunniao_monitor') uuid_url = "http://pmm.ops.xunhuji.me:8888/qan-api/instances?deleted=no" r_uuid = s.get(uuid_url) # 使用UTC时间,统计区间为1小时 local_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') local_before_one_hours = ( datetime.datetime.now() - datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S') utc_now = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') utc_before_one_hours = ( datetime.datetime.utcnow() - datetime.timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%S') result = [] for i in r_uuid.json(): if i.get('Subsystem') == 'mysql': uuid = i.get('UUID') query_url = f"http://pmm.ops.xunhuji.me:8888/qan-api/qan/profile" \ f"/{uuid}?begin={utc_before_one_hours}&end={utc_now}&offset=0" r_query = s.get(query_url) query = r_query.json().get('Query') if isinstance(query, list): for line in query: timerange = f"{local_before_one_hours} -> {local_now}" name = i.get('Name') qps = round(line.get('QPS'), 2) cnt = line.get('Stats').get('Cnt') avg = round(line.get('Stats').get('Avg') * 1000, 2) abstract = line.get('Abstract') fingerprint = line.get('Fingerprint') md5sum = hashlib.md5( fingerprint.encode('utf8')).hexdigest() version = '-'.join(([i.get('Subsystem'), i.get('Version')])) if all( check_rules(abstract, rule) for rule in ignore_values): if cnt > cnt_value and avg > avg_value: result.append({ 'timerange': timerange, 'name': name, 'version': version, 'abstract': abstract, 'fingerprint': fingerprint, 'qps': qps, 'cnt': cnt, 'avg': avg, 'md5sum': md5sum }) MysqlSlowLog.objects.get_or_create( md5sum=md5sum, defaults={ 'hostname': name, 'version': version, 'qps': qps, 'cnt': cnt, 'avg': avg, 'fingerprint': fingerprint, 'timerange': timerange }) xiaoding = DingtalkChatbot(webhook) text = [] if result: for p in result: obj = MysqlSlowLog.objects.filter(md5sum=p.get('md5sum')).first() is_pull = obj.is_pull if obj else 0 if is_pull == 0: text.append(f"- 主机名:{p.get('name')}\n" f"- MySQL版本:{p.get('version')}\n" f"- 区间内每秒查询数(QPS):{p.get('qps')}\n" f"- 区间内总查询次数:{p.get('cnt')}\n" f"- 区间内平均响应时间:{p.get('avg')}ms\n" f"- MD5:{p.get('md5sum')}\n" f"- SQL摘要:{p.get('abstract')}\n" f"- SQL指纹:\n" f"> {p.get('fingerprint')}\n\n\n") title = f"#### 探测到新的慢查询,总数:{len(text)}条\n#### 开始时间:{local_before_one_hours}\n#### 结束时间:{local_now}\n" xiaoding.send_markdown(title='SQL慢查询', text=title + ' '.join(text))
def dinghtml(title, msg): webhook = "https://oapi.dingtalk.com/robot/send?access_token=6376792f2ca10ab2e9222220477ccd0a095b9e6849438761779e4ddaef2b5e00" xiaoding = DingtalkChatbot(webhook) # 方式一:通常初始化方式 xiaoding.send_markdown(title=title, text=msg, is_at_all=False)
dash_rate_lastweek=compare(dash_today_total, dash_lastweek_total), # 画猜 # draw_today_total=round(draw_today_total, 2), # draw_rate_yesterday=compare(draw_today_total, draw_yesterday_total), # draw_rate_lastweek=compare(draw_today_total, draw_lastweek_total), # # # 乌诺 # uno_today_total=round(uno_today_total, 2), # uno_rate_yesterday=compare(uno_today_total, uno_yesterday_total), # uno_rate_lastweek=compare(uno_today_total, uno_lastweek_total), # 其他游戏(扫雷、阿瓦隆、剧本杀、怼球、台球、五子棋、画猜、乌诺) other_today_total=round(other_today_total, 2), other_rate_yesterday=compare(other_today_total, other_yesterday_total), other_rate_lastweek=compare(other_today_total, other_lastweek_total)) from dingtalkchatbot.chatbot import DingtalkChatbot # 播报群 # webhook = "https://oapi.dingtalk.com/robot/send?access_token=732ceae762f83b1f37500af5df4016de5741e5251c0a49f62c5c824173fb4121" # secret = "SECfa31e7be280d10eb497754f02087759cc9f71dc3c391f27b47bf8967139bea6b" # 测试群 webhook = "https://oapi.dingtalk.com/robot/send?access_token=2606c23eaf70851235a10785081a8fedcc72d210c9379c9b960c32d571372b8a" secret = "SEC2fe3fce80cc0a5b2de41423c540b8f58c2f2c393a7c2ec28c75d9bdd0062939e" xiaoding = DingtalkChatbot(webhook, secret=secret) xiaoding.send_markdown(title='killer工作室收入播报', text=markdown_file, is_at_all=True) print("播报已发送")