You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
python-project/api/wechat3.py

76 lines
2.4 KiB

#!/usr/bin/python3
#-*-coding: utf-8-*-
# by QianFeng.newrain
#
'''
Welcome QianFeng cloud computing
'''
import json
import sys
import time
import requests
# 此为企业的ID号
CorpID = 'wwa1dc8236066bab50'
# 应用的ID
Agentid = 1000005
# 认证信息,企业ID+认证信息可获取tokent,获取之后向此tokent发送内容
Secret = 'CRzsnYigkQy_9qoHErXG94am81AUuXabY0A8-N7LW_4'
localtime = time.strftime("[%H:%M:%S]", time.localtime())
class Tencent(object):
def __init__(self,user,title, msg):
# 格式化输出内容:标题+内容
self.MSG = f'{title}\n{msg}\n{localtime}'
self.User = user
self.url = 'https://qyapi.weixin.qq.com'
self.send_msg = json.dumps({
"touser": self.User,
"msgtype": 'text',
"agentid": Agentid,
"text": {'content': self.MSG},
"safe": 0
})
# 获取tokent
def get_token(self):
token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (self.url, CorpID, Secret)
if not os.path.isfile('./token.json'):
r = requests.get(token_url)
r = r.json()
token = r['access_token']
with open('./token.json', 'w') as f:
json.dump({'timestamp': time.time(), 'token': token}, f)
return token
else:
with open('./token.json', 'r') as f:
token_data = json.load(f)
print(time.time() - int(token_data.get('timestamp')))
if time.time() - int(token_data.get('timestamp')) > 7000:
r = requests.get(token_url)
r = r.json()
token = r['access_token']
with open('./token.json', 'w') as f:
json.dump({'timestamp': time.time(), 'token': token}, f)
return token
else:
return token_data['token']
# 发送信息
def send_message(self):
send_url = '%s/cgi-bin/message/send?access_token=%s' % (self.url,self.get_token())
respone = requests.post(url=send_url, data=self.send_msg)
respone = respone.json()
x = respone['errcode']
if x == 0:
print ('Succesfully')
else:
print ('Failed')
if __name__ == '__main__':
# 创建对象
send_obj = Tencent(sys.argv[1],str(sys.argv[2]), str(sys.argv[3]))
# 调用发送函数
send_obj.send_message()