基於python實現微信模板訊息

來源:互聯網
上載者:User
我的風格,廢話不多說了,直接給大家貼代碼了,並在一些痛點上給大家附了注釋,具體代碼如下所示:

#!/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):    # 傳入appid    self.appid = appid    # 傳入密碼    self.secrect = secrect    # 傳入記錄token和到期時間的檔案名稱    self.file_name=file_name  def build_timestamp(self,interval):    # 傳入時間間隔,得到指定interval後的時間 格式為"2015-07-01 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):    # 判斷token是否到期    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‘)    # 如果到期返回false    if curr_time>expires_time:      return token,"false"    # 沒到期返回true    else:      return token,"true"  def getToken(self):    # 擷取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()      # 讀取json資料      j = json.loads(s)      j.keys()      # 從json中擷取token      token = j[‘access_token‘]      # 從json中擷取到期時間長度      expires_in =j[‘expires_in‘]      # 將得到的到期時間長度減去300秒然後與目前時間做相加計算然後寫入到到期檔案      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)    except Exception,e:      print e    return token  def post_data(self,url,para_dct):    """觸發post請求發送最終的模板訊息"""    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):    ‘‘‘推送訊息 ‘‘‘    #擷取存入到到期檔案中的token,同時判斷是否到期    token,if_token_expires=self.check_token_expires()    #如果到期了就重新擷取token    if if_token_expires=="false":      token=self.getToken()    # 背景色設定,貌似不生效      if topcolor.strip()==‘‘:      topcolor = "#7B68EE"    #最紅post的求情資料    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)    #讀取json資料    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):    """警示函數"""    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):    """恢複函數"""    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("測試的警示訊息","8.8.8.8",time.ctime(),"最進階別","然並卵","掛了","大傻路趕緊處理")  # 執行個體化類  webchart=WechatPush(appid,secrect,file_name)  url="http://www.xiaoniu88.com"  print len(sys.argv)  # 發送警示訊息  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)  #發送恢複訊息  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)

好了,代碼到此結束了,希望以上所述關於python模板訊息的相關敘述能夠給大家帶來協助。哪裡寫的不好,還請各位大俠多多見諒,提出寶貴意見,謝謝。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.