#!/usr/bin/env python3 import requests import json import sys import os def access_token(Corpid,Secret): url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" values = {"corpid":Corpid,"corpsecret":Secret} r = requests.get(url,params=values) data = json.loads(r.text) token = data['access_token'] with open('/tmp/access.token','w') as f: f.write(token) def send_msg(toparty,agentid,token,content): url = "https://qyapi.weixin.qq.com/cgi-bin/message/send" values = {"access_token": token} data = { "toparty" : toparty, "msgtype" : "text", "agentid" : agentid, "text" : { "content" : content }, "safe":0 } r = requests.post(url,params=values,json=data) data = json.loads(r.text) code = data['errcode'] return code def token(): with open("/tmp/access.token",'r') as f: token = f.read() return token if __name__ == "__main__": Corpid = "wwc67c4ff3846c4f6a" Secret = "-OWfdtJu8g4hbYWdb4hPn4rxN8o7_iTlpnnUxBLt-RY" agentid = 1000002 toparty = sys.argv[1] content = sys.argv[2] if not os.path.exists("/tmp/access.token"): access_token(Corpid, Secret) token = token() send_msg(toparty, agentid, token, content) else: token = token() code = send_msg(toparty, agentid, token, content) if code != 0: access_token(Corpid, Secret) token = token() send_msg(toparty, agentid, token, content)