python实现给微信公众号发送消息的方法
作者:felix_yujing 时间:2021-08-25 23:44:57
本文实例讲述了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?corpid=%s&corpsecret=%s" % (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?access_token=%s" % 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,微信
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
流动的线条 —— 中国汉字书法之美
2009-10-30 18:15:00
![](https://img.aspxhome.com/file/UploadPic/200910/30/1-79s.jpg)
细化解析:MySQL 搜索中的大小写敏感性
2008-11-27 15:53:00
ie和firefox中css自动换行实现方法
2008-04-08 12:49:00
python实现坦克大战游戏 附详细注释
2023-06-26 07:58:13
Python 利用pydub库操作音频文件的方法
2022-12-12 05:42:53
浅谈numpy数组中冒号和负号的含义
2023-09-02 01:03:04
python实现精准搜索并提取网页核心内容
2021-04-07 09:14:04
![](https://img.aspxhome.com/file/2023/5/76955_0s.jpg)
asp如何远程注册DLL
2010-06-16 09:58:00
php将12小时制转换成24小时制的方法
2023-11-21 15:56:08
让Dreamweaver MX显示最舒服的编程环境
2008-02-25 14:01:00
![](https://img.aspxhome.com/file/UploadPic/20082/25/200822514442940s.jpg)
python yield关键词案例测试
2021-02-07 03:14:07
经典的退出浏览器弹窗代码
2008-07-30 12:48:00
实现文字放大效果Javascript源码
2010-03-17 20:46:00
![](https://img.aspxhome.com/file/UploadPic/20103/17/2010317204821421s.jpg)
基于循环神经网络(RNN)实现影评情感分类
2021-11-27 16:42:10
Python开发网站目录扫描器的实现
2022-07-09 11:51:02
![](https://img.aspxhome.com/file/2023/7/86337_0s.png)
详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题解决
2021-08-28 15:42:10
![](https://img.aspxhome.com/file/2023/3/85043_0s.png)
颜色渐变效果
2013-07-13 14:14:52
可刷新的Div+CSS+JS二级下拉树型菜单
2007-10-09 19:14:00
基于ORA-12170 TNS 连接超时解决办法详解
2023-06-30 18:18:30
python进程管理工具supervisor的安装与使用教程
2023-10-15 20:41:57