黑松山资源网 Design By www.paidiu.com
本文实例讲述了python实现给微信公众号发送消息的方法。分享给大家供大家参考,具体如下:
现在通过发微信公众号信息来做消息通知和告警已经很普遍了。最常见的就是运维通过zabbix调用shell脚本给微信发消息,起到告警的作用。当要发送的信息较多,而且希望按照指定格式显示的好看一点的时候,shell处理起来,个人感觉不太方便。于是我用Python重写了发微信的功能。
#coding:utf-8 import urllib2 import json import sys def getMsg(): #为了避免发送中文消息报错,使用utf8方式编码 reload(sys) sys.setdefaultencoding('utf8') #这个方法生成想要发送的消息 msg = ''' 要发送的消息1 要发送的消息2 要发送的消息3 ... ''' return msg if __name__ == '__main__': #微信公众号上应用的CropID和Secret CropID='xxxxxxxxxxxxxxxxxx' Secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #获取access_token GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken" % (CropID,Secret) result=urllib2.urlopen(urllib2.Request(GURL)).read() dict_result = json.loads(result) Gtoken=dict_result['access_token'] #生成通过post请求发送消息的url PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send" % Gtoken #企业号中的应用id AppID=1 #部门成员id,微信接收者 UserID=1 #部门id,定义可接收消息的成员范围 PartyID=1 #生成post请求信息 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' #由于字典格式不能被识别,需要转换成json然后在作post请求 #注:如果要发送的消息内容有中文的话,第三个参数一定要设为False json_post_data = json.dumps(post_data,False,False) #通过urllib2.urlopen()方法发送post请求 request_post = urllib2.urlopen(PURL, json_post_data) #read()方法查看请求的返回结果 print request_post.read()
注意:
2017年6月初开始,微信企业公众号迁移到企业微信,发送消息有一些调整,请参考前文《[企业公众号]升级到[企业微信]之后发送消息失败的解决方法》
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》。
希望本文所述对大家Python程序设计有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 林尼攻略一图流
- 李翊君.1993-相思的烈酒【上华】【WAV+CUE】
- 古巨基.1998-LEO.KU(国)【千禧年代】【WAV+CUE】
- 郭子.2001-原来你什么都不想要创作集丫滚石】【WAV+CUE】
- 《使命召唤:黑色行动6》新预告公布!10月25日发售
- Atlus《暗喻幻想》媒体评分汇总:高分好评如潮!
- 2024金摇杆奖提名揭晓 《黑神话》角逐最佳视觉设计!
- 群星《新说唱2024 第3期 (上)》[320K/MP3][32.76MB]
- 群星《新说唱2024 第3期 (上)》[FLAC/分轨][95.38MB]
- 群星《新说唱2024 第3期 (下)》[320K/MP3][31.36MB]
- 幻兽帕鲁手游什么时候正式上线 最新消息一览
- 西普大陆BOSS位置盘点 解锁天启纪元玩法
- 西普大陆精灵进阶培养攻略 精灵养成指南
- dnf手游法控法系职业哪个强 dnf手游法控法系职业强度排行
- 魔兽世界血藤护目镜图纸在哪买 wlk血藤护目镜图纸购买位置介绍