文章目录
前言
一、Python安装
1.1 进入官网
1.2 下载
1.3 安装
二、PyCharm开发工具使用
2.1 PyCharm 下载
2.2 PyCharm安装
三、发送告警通知到微信
3.1.新建应用
3.2 获取秘钥
3.3 Python源码
前言
本文介绍了如何用 Python 发送告警通知到微信的方法
私信小编01即可获取大量Python学习资源
一、Python安装
1.1 进入官网
https://www.python.org/downloads/
1.2 下载
1.3 安装
详细安装步骤参考博客:
https://blog.csdn.net/weixin_41645135/article/details/115275353
二、PyCharm开发工具使用
比较流行的IDE 是 PyCharm。当然,还有其他 IDE 可供我们使用:
IDLE
PyCharm
wingIDE
Eclipse
IPython
2.1 PyCharm 下载
官网下载地址:
https://www.jetbrains.com/pycharm/download/#section=windows
2.2 PyCharm安装
和安装普通软件一致,点击下一步即可,只有几个画面需要单独关注。
根据 win 系统是 64 还是 32 位,选择不同的类型。
详细安装步骤参考博客:
https://blog.csdn.net/weixin_41645135/article/details/115339098
三、发送告警通知到微信
3.1.新建应用
登陆网页版企业微信
https://work.weixin.qq.com/
点击 应用管理 -> 应用 -> 创建应用
注意:你首先的申请注册一个企业微信
上传应用的 logo,输入应用名称,再选择可见范围,成功创建一个告警应用
3.2 获取秘钥
使用 Python 发送告警请求,其实就只使用到两个接口
获取 Token :
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}
发送请求:
https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}
可以看到,最重要的是 corpid 和 secret:
corpid:唯一标识你的企业
secret:应用级的密钥,有了它程序才知道你要发送该企业的哪个应用
corpid 可以通过 我的企业 -> 企业信息 获取
最后将 corpid 和 secret 填入下面的常量中。
而secret获取相对麻烦一点,点击前面创建应用,点击查看secret
然后再点击发送就会发送到你的企业微信上
3.3 Python源码
import json
import datetime
import requests
CORP_ID = ""
SECRET = ""
class WeChatPub:
s = requests.session()
def __init__(self):
self.token = self.get_token()
def get_token(self):
url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORP_ID}&corpsecret={SECRET}"
rep = self.s.get(url)
if rep.status_code != 200:
print("request failed.")
return
return json.loads(rep.content)['access_token']
def send_msg(self, content):
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token
header = {
"Content-Type": "application/json"
}
form_data = {
"touser": "@all",
"toparty": " PartyID1 | PartyID2 ",
"totag": " TagID1 | TagID2 ",
"msgtype": "textcard",
"agentid": 1000002,
"textcard": {
"title": "服务异常告警",
"description": content,
"url": "URL",
"btntxt": "更多"
},
"safe": 0
}
rep = self.s.post(url, data=json.dumps(form_data).encode('utf-8'), headers=header)
if rep.status_code != 200:
print("request failed.")
return
return json.loads(rep.content)
wechat = WeChatPub()
now = datetime.datetime.now()
timenow = now.strftime('%Y%m%d %H:%M:%S')
wechat.send_msg(f"{timenow} 服务cpu超过80%请尽快排查!")
下载所需要的模块
pip install requests
只要你的企业微信没有关闭通知的权限,
那你的手机立马就会弹出这个告警信息,后期只要设置可见人员即可