本文實例講述了Python微信企業號文本消息推送功能。分享給大家供大家參考,具體如下:
企業號的創建、企業號應用的創建、組、tag、part就不贅述了,一搜一大堆,但是網上拿的那些個腳本好多都不好使,所以自己修了一個
坦率的講,這個腳本是用來作為zabbix的通知媒介腳本的,本人是個菜鳥,如果哪里不對,大神們不要笑話,python也處于學習階段,如果有哪些地方不合理,很希望可以不吝賜教,廢話不多說,腳本奉上:
#!/usr/bin/python# _*_coding:utf-8 _*_import urllib2import jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def gettoken(corpid, corpsecret): gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret try: token_file = urllib2.urlopen(gettoken_url) except urllib2.HTTPError as e: print e.code print e.read().decode("utf8") sys.exit() token_data = token_file.read().decode('utf-8') token_json = json.loads(token_data) token_json.keys() token = token_json['access_token'] return tokendef senddata(access_token, user, party, agent, subject, content): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token send_values = "{/"touser/":/"" + user + "/",/"toparty/":/"" + party + "/",/"totag/":/"/",/"msgtype/":/"text/",/"agentid/":/"" + agent + "/",/"text/":{/"content/":/"" + subject + "/n" + content + "/"},/"safe/":/"0/"}" send_request = urllib2.Request(send_url, send_values) response = json.loads(urllib2.urlopen(send_request).read()) print str(response)if __name__ == '__main__': user = str(sys.argv[1]) # 參數1:發送給用戶的賬號,必須關注企業號,并對企業號有發消息權限 party = str(sys.argv[2]) # 參數2:發送給組的id號,必須對企業號有權限 agent = str(sys.argv[3]) # 參數3:企業號中的應用id subject = str(sys.argv[4]) # 參數4:標題【消息內容的一部分】 content = str(sys.argv[5]) # 參數5:文本具體內容 corpid = 'CorpID' # CorpID是企業號的標識 corpsecret = 'corpsecretSecret' # corpsecretSecret是管理組憑證密鑰 try: accesstoken = gettoken(corpid, corpsecret) senddata(accesstoken, user, party, agent, subject, content) except Exception, e: print str(e) + "Error Please Check /"corpid/" or /"corpsecret/" Config"希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答