
本文示例描述了python向微信公众账号发送消息的方法. 与您分享以供参考微信公众平台接口 python,如下:

现在常见的是通过发送微信公众号信息来发送消息通知和警告. 最常见的是,O&M通过zabbix调用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/gettokencorpid=%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/sendaccess_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字符串操作技巧概述”微信公众平台接口 python,“ Python编码操作技巧概述”,“ Python数据结构和算法教程”,“ Python函数用法”技能“摘要”和“ Python简介和高级经典教程”.
我希望本文对Python编程的每个人都有帮助.
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-226239-1.html
而不是人为故意或无意放进去的