Implement WeChat template message based on python

Source: Internet
Author: User
This article uses a piece of code example to introduce you to the python-based template message-related information. If you are interested in the python template message, let's learn about it. I don't need to talk about it anymore, the code is directly pasted and comments are provided on some difficulties. The specific code is as follows:

#! /Usr/bin/env python #-*-coding: UTF-8-*-import urllib2, jsonimport datetime, timefrom config import * import sysreload (sys) sys. setdefaultencoding ("UTF-8") class WechatPush (): def _ init _ (self, appid, secrect, file_name): # Pass in appid self. appid = appid # input password self. secrect = secrect # Name of the token and expiration time of the input record self. file_name = file_name def build_timestamp (self, interval): # input time interval. The time format after the specified interval is "14:41:40" now = datetime. datetime. now () delta = datetime. timedelta (seconds = interval) now_interval = now + delta return now_interval.strftime ('% Y-% m-% d % H: % M: % s') def check_token_expires (self ): # determine whether the token expires with open (self. file_name, 'R') as f: line = f. read () if len (line)> 0: expires_time = line. split (",") [1] token = line. split (",") [0] else: return "", "true" curr_time = time. strftime ('% Y-% m-% d % H: % M: % s') # returns false if curr_time> expires_time: return token if it expires, "false" # return true else: return token if no expiration occurs, "true" def getToken (self): # Get accessToken url =' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= '+ Self. appid + "& secret =" + self. secrect try: f = urllib2.urlopen (url) s = f. read () # read json data j = json. loads (s) j. keys () # obtain the token from json = j ['Access _ token'] # obtain the expiration duration from json: expires_in = j ['expires _ in'] # obtain the expiration time the length is less than 300 seconds, then the sum is calculated with the current time, and then written to the expired file write_expires = self. build_timestamp (int (expires_in-300) content = "% s, % s" % (token, write_expires) with open (self. file_name, 'w') as f: f. write (content) failed t Exception, e: print e return token def post_data (self, url, para_dct ): "trigger the post request to send the final template message" "para_data = para_dct f = urllib2.urlopen (url, para_data) content = f. read () return content def do_push (self, touser, template_id, url, topcolor, data): '''push message' # Get the token saved to the expired file, determine whether token expires. if_token_expires = self. check_token_expires () # if it expires, obtain the token again. if if_token_expires = "false": token = self. getToken () # specifies the background color. if topcolor does not take effect. strip () = '': topcolor =" # 7B68EE "# dict_arr = {'touser': touser, 'template _ id': template_id, 'url': url, 'topcolor': topcolor, 'data': data} json_template = json. dumps (dict_arr) requst_url =" https://api.weixin.qq.com/cgi-bin/message/template/send?access_token= "+ Token content = self. post_data (requst_url, json_template) # Read json data j = json. loads (content) j. keys () errcode = j ['errcode'] errmsg = j ['errmsg '] # print errmsgif _ name _ = "_ main __": def alarm (title, hostname, timestap, level, message, state, tail): "alarm function" color = "# FF0000" data = {"first ": {"value": title}, "keyword1": {"value": hostname, "color": color}, "keyword2": {"value": timestap, "color": color}, "keyword3": {"value": level, "color": color}, "keyword4": {"value": message, "color ": color}, "keyword5": {"value": state, "color": color}, "remark": {"value": tail} return data def recover (title, message, alarm_time, recover_time, continue_time, tail): "restoration function" re_color = "#228B22" data = {"first": {"value": title }, "content": {"value": message, "color": re_color}, "occurtime": {"value": alarm_time, "color": re_color}, "recovertime ": {"value": recover_time, "color": re_color}, "lasttime": {"value": continue_time, "color": re_color}, "remark ": {"value": tail} return data # data = alarm ("test alarm message", "8.8.8.8", time. ctime (), "maximum level", "ran Dan", "hung up", "Da Silly road to hurry") # instantiation class webchart = WechatPush (appid, secrect, file_name) url =" http://www.xiaoniu88.com "Print len (sys. argv) # Send the alarm message if len (sys. argv) = 9: title = sys. argv [1] hostname = sys. argv [2] timestap = sys. argv [3] level = sys. argv [4] message = sys. argv [5] state = sys. argv [6] tail = sys. argv [7] print "sys. argv [1] "+ sys. argv [1] print "sys. argv [2] "+ sys. argv [2] print "sys. argv [3] "+ sys. argv [3] print "sys. argv [4] "+ sys. argv [4] print "sys. argv [5] "+ sys. argv [5] print "sys. argv [6] "+ sys. argv [6] print "sys. argv [7] "+ sys. argv [7] print "sys. argv [8] "+ sys. argv [8] with open ("/etc/zabbix/moniter_scripts/test. log ", 'a + ') as f: f. write (title + "\ n") f. write (hostname + "\ n") f. write (timestap + "\ n") f. write (level + "\ n") f. write (message + "\ n") f. write (state + "\ n") f. write (tail + "\ n") f. write ("% s _ % s" % ("group", sys. argv [8]) + "\ n") data = alarm (title, hostname, timestap, level, message, state, tail) group_name = "% s _ % s" % ("group", sys. argv [8]) for touser in eval ("% s _ % s" % ("group", sys. argv [8]): webchart. do_push (touser, alarm_id, url, "", data) for touser in group_super: webchart. do_push (touser, alarm_id, url, "", data) # Send the recovery message elif len (sys. argv) = 8: title = sys. argv [1] message = sys. argv [2] alarm_time = sys. argv [3] recover_time = sys. argv [4] continue_time = sys. argv [5] tail = sys. argv [6] print "sys. argv [1] "+ sys. argv [1] print "sys. argv [2] "+ sys. argv [2] print "sys. argv [3] "+ sys. argv [3] print "sys. argv [4] "+ sys. argv [4] print "sys. argv [5] "+ sys. argv [5] print "sys. argv [6] "+ sys. argv [6] print "sys. argv [7] "+ sys. argv [7] data = recover (title, message, alarm_time, recover_time, continue_time, tail) for touser in eval ("% s _ % s" % ("group", sys. argv [7]): webchart. do_push (touser, recover_id, url, "", data) for touser in group_super: webchart. do_push (touser, recover_id, url, "", data)

Now, the code is over. I hope the above descriptions about the python template message can help you. I would like to thank you for your patience and comments.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.