-
Notifications
You must be signed in to change notification settings - Fork 218
/
Copy pathwechat.py
executable file
·78 lines (66 loc) · 3.16 KB
/
wechat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/9/5 08:53
# @Author : X-Mars
# @Author : 火星小刘
# @Site : https://github.com/X-Mars
# @File : /wechat.py
# @Software : Pycharm
import requests, sys, json, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def GetTokenFromServer(Corpid, Secret):
Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
Data = {
"corpid": Corpid,
"corpsecret": Secret
}
r = requests.get(url=Url, params=Data, verify=False)
print(r.json())
if r.json()['errcode'] != 0:
return False
else:
Token = r.json()['access_token']
file = open('/tmp/zabbix_wechat_config.json', 'w')
file.write(r.text)
file.close()
return Token
def SendMessage(User, Agentid, Subject, Content):
try:
file = open('/tmp/zabbix_wechat_config.json', 'r')
Token = json.load(file)['access_token']
file.close()
except:
Token = GetTokenFromServer(Corpid, Secret)
n = 0
Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
Data = {
"touser": User, # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
# "totag": Tagid, # 企业号中的标签id,群发使用(推荐)
# "toparty": Partyid, # 企业号中的部门id,群发时使用。
"msgtype": "text", # 消息类型。
"agentid": Agentid, # 企业号中的应用id。
"text": {
"content": Subject + '\n' + Content
},
"safe": "0"
}
r = requests.post(url=Url, data=json.dumps(Data), verify=False)
while r.json()['errcode'] != 0 and n < 4:
n+=1
Token = GetTokenFromServer(Corpid, Secret)
if Token:
Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
r = requests.post(url=Url, data=json.dumps(Data), verify=False)
print(r.json())
return r.json()
if __name__ == '__main__':
User = sys.argv[1] # zabbix传过来的第一个参数
Subject = str(sys.argv[2]) # zabbix传过来的第二个参数
Content = str(sys.argv[3]) # zabbix传过来的第三个参数
Corpid = "xxx" # CorpID是企业号的标识
Secret = "xxxx" # Secret是管理组凭证密钥
#Tagid = "1" # 通讯录标签ID
Agentid = "1" # 应用ID
#Partyid = "1" # 部门ID
Status = SendMessage(User, Agentid, Subject, Content)
print(Status)