用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月初开始,微信企业公众号迁移到企业微信,发送消息有一些调整,请参考博文:http://blog.csdn.net/felix_yujing/article/details/72877249

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值