基于python實(shí)現(xiàn)微信模板消息
我的風(fēng)格,廢話(huà)不多說(shuō)了,直接給大家貼代碼了,并在一些難點(diǎn)上給大家附了注釋?zhuān)唧w代碼如下所示:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib2,json
import datetime,time
from config import *
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class WechatPush():
def __init__(self,appid,secrect,file_name):
# 傳入appid
self.appid = appid
# 傳入密碼
self.secrect = secrect
# 傳入記錄token和過(guò)期時(shí)間的文件名
self.file_name=file_name
def build_timestamp(self,interval):
# 傳入時(shí)間間隔,得到指定interval后的時(shí)間 格式為"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是否過(guò)期
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‘)
# 如果過(guò)期返回false
if curr_time>expires_time:
return token,"false"
# 沒(méi)過(guò)期返回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數(shù)據(jù)
j = json.loads(s)
j.keys()
# 從json中獲取token
token = j[‘a(chǎn)ccess_token‘]
# 從json中獲取過(guò)期時(shí)長(zhǎng)
expires_in =j[‘expires_in‘]
# 將得到的過(guò)期時(shí)長(zhǎng)減去300秒然后與當(dāng)前時(shí)間做相加計(jì)算然后寫(xiě)入到過(guò)期文件
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):
"""觸發(fā)post請(qǐng)求微信發(fā)送最終的模板消息"""
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):
‘‘‘推送消息 ‘‘‘
#獲取存入到過(guò)期文件中的token,同時(shí)判斷是否過(guò)期
token,if_token_expires=self.check_token_expires()
#如果過(guò)期了就重新獲取token
if if_token_expires=="false":
token=self.getToken()
# 背景色設(shè)置,貌似不生效
if topcolor.strip()==‘‘:
topcolor = "#7B68EE"
#最紅post的求情數(shù)據(jù)
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數(shù)據(jù)
j = json.loads(content)
j.keys()
errcode = j[‘errcode‘]
errmsg = j[‘errmsg‘]
#print errmsg
if __name__ == "__main__":
def alarm(title,hostname,timestap,level,message,state,tail):
"""報(bào)警函數(shù)"""
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):
"""恢復(fù)函數(shù)"""
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("測(cè)試的報(bào)警消息","8.8.8.8",time.ctime(),"最高級(jí)別","然并卵","掛了","大傻路趕緊處理")
# 實(shí)例化類(lèi)
webchart=WechatPush(appid,secrect,file_name)
url="http://www.xiaoniu88.com"
print len(sys.argv)
# 發(fā)送報(bào)警消息
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(chǎn)+‘) 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)
#發(fā)送恢復(fù)消息
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)
好了,代碼到此結(jié)束了,希望以上所述關(guān)于python模板消息的相關(guān)敘述能夠給大家?guī)?lái)幫助。哪里寫(xiě)的不好,還請(qǐng)各位大俠多多見(jiàn)諒,提出寶貴意見(jiàn),謝謝。
- Python版微信紅包分配算法
- Python微信庫(kù):itchat的用法詳解
- python基于itchat實(shí)現(xiàn)微信群消息同步機(jī)器人
- Python+微信接口實(shí)現(xiàn)運(yùn)維報(bào)警
- python實(shí)現(xiàn)微信接口(itchat)詳細(xì)介紹
- python3操作微信itchat實(shí)現(xiàn)發(fā)送圖片
- Python使用微信SDK實(shí)現(xiàn)的微信支付功能示例
- 利用python微信庫(kù)itchat實(shí)現(xiàn)微信自動(dòng)回復(fù)功能
- 利用Python開(kāi)發(fā)微信支付的注意事項(xiàng)
- Python利用Nagios增加微信報(bào)警通知的功能
- python爬蟲(chóng)_微信公眾號(hào)推送信息爬取的實(shí)例
- Python實(shí)現(xiàn)的微信紅包提醒功能示例
相關(guān)文章
Python openpyxl模塊學(xué)習(xí)之輕松玩轉(zhuǎn)Excel
Python提供了許多操作Excel的模塊,能夠讓我們從繁瑣的工作中騰出雙手。本文主要為大家介紹的是openpyxl模塊,它的功能相對(duì)與其他模塊更為齊全,感興趣的小伙伴快來(lái)學(xué)習(xí)一下吧2021-12-12
Python 實(shí)現(xiàn)刪除某路徑下文件及文件夾的實(shí)例講解
下面小編就為大家分享一篇Python 實(shí)現(xiàn)刪除某路徑下文件及文件夾的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python實(shí)現(xiàn)給qq郵箱發(fā)送郵件的方法
這篇文章主要介紹了Python實(shí)現(xiàn)給qq郵箱發(fā)送郵件的方法,涉及Python郵件發(fā)送的相關(guān)技巧,需要的朋友可以參考下2015-05-05
如何使用Python設(shè)置和讀取config.ini文件
使用配置文件是一種常見(jiàn)的方法,而INI文件是一種簡(jiǎn)單而常見(jiàn)的配置文件格式,在本文中,我將介紹如何使用Python設(shè)置和讀取INI格式的配置文件,需要的朋友可以參考下2024-03-03
python中range和xrange的區(qū)別(python2和python3)
在Python中,range()?和?xrange()?函數(shù)在早期的Python版本(Python 2)中扮演著不同的角色,但在Python 3中,xrange()?已經(jīng)被移除,并被?range()?取代,下面就來(lái)介紹一下,感興趣的可以了解一下2025-04-04
Python使用SQLite和Excel操作進(jìn)行數(shù)據(jù)分析
這篇文章主要介紹了Python使用SQLite和Excel操作進(jìn)行數(shù)據(jù)分析,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Python語(yǔ)言中的重要函數(shù)對(duì)象用法小結(jié)
Python作為一種強(qiáng)大的編程語(yǔ)言,提供了多種高級(jí)函數(shù)對(duì)象,如lambda匿名函數(shù)、map()、reduce()函數(shù),以及迭代器和生成器的使用,本文給大家介紹Python語(yǔ)言中的重要函數(shù)對(duì)象用法,感興趣的朋友跟隨小編一起看看吧2024-09-09
Python將HTML快速轉(zhuǎn)換成PDF的方法實(shí)現(xiàn)
在Web開(kāi)發(fā)和報(bào)告任務(wù)中,將HTML內(nèi)容轉(zhuǎn)換為PDF是一種常見(jiàn)需求,本文主要介紹了Python將HTML快速轉(zhuǎn)換成PDF的方法實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
解決python中無(wú)法自動(dòng)補(bǔ)全代碼的問(wèn)題
今天小編就為大家分享一篇解決python中無(wú)法自動(dòng)補(bǔ)全代碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12

