本文實(shí)例講述了python實(shí)現(xiàn)給微信公眾號(hào)發(fā)送消息的方法。分享給大家供大家參考,具體如下:
現(xiàn)在通過發(fā)微信公眾號(hào)信息來做消息通知和告警已經(jīng)很普遍了。最常見的就是運(yùn)維通過zabbix調(diào)用shell腳本給微信發(fā)消息,起到告警的作用。當(dāng)要發(fā)送的信息較多,而且希望按照指定格式顯示的好看一點(diǎn)的時(shí)候,shell處理起來,個(gè)人感覺不太方便。于是我用Python重寫了發(fā)微信的功能。
#coding:utf-8import urllib2import jsonimport sysdef getMsg():  #為了避免發(fā)送中文消息報(bào)錯(cuò),使用utf8方式編碼  reload(sys)  sys.setdefaultencoding('utf8')  #這個(gè)方法生成想要發(fā)送的消息  msg = '''要發(fā)送的消息1要發(fā)送的消息2要發(fā)送的消息3...'''  return msgif __name__ == '__main__':  #微信公眾號(hào)上應(yīng)用的CropID和Secret  CropID='xxxxxxxxxxxxxxxxxx'  Secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #獲取access_token  GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (CropID,Secret)  result=urllib2.urlopen(urllib2.Request(GURL)).read()  dict_result = json.loads(result)  Gtoken=dict_result['access_token']  #生成通過post請(qǐng)求發(fā)送消息的url  PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Gtoken  #企業(yè)號(hào)中的應(yīng)用id  AppID=1  #部門成員id,微信接收者  UserID=1  #部門id,定義可接收消息的成員范圍  PartyID=1  #生成post請(qǐng)求信息  post_data = {}  msg_content = {}  msg_content['content'] = getMsg()  post_data['touser'] = UserID  post_data['toparty'] = PartyID  post_data['msgtype'] = 'text'  post_data['agentid'] = AppID  post_data['text'] = msg_content  post_data['safe'] = '0'  #由于字典格式不能被識(shí)別,需要轉(zhuǎn)換成json然后在作post請(qǐng)求  #注:如果要發(fā)送的消息內(nèi)容有中文的話,第三個(gè)參數(shù)一定要設(shè)為False  json_post_data = json.dumps(post_data,False,False)  #通過urllib2.urlopen()方法發(fā)送post請(qǐng)求  request_post = urllib2.urlopen(PURL, json_post_data)  #read()方法查看請(qǐng)求的返回結(jié)果  print request_post.read()注意:
2017年6月初開始,微信企業(yè)公眾號(hào)遷移到企業(yè)微信,發(fā)送消息有一些調(diào)整,請(qǐng)參考前文《[企業(yè)公眾號(hào)]升級(jí)到[企業(yè)微信]之后發(fā)送消息失敗的解決方法》
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選