Python编程实现微信企业号文本消息推送功能示例

yipeiwu_com5年前Python基础

本文实例讲述了Python微信企业号文本消息推送功能。分享给大家供大家参考,具体如下:

企业号的创建、企业号应用的创建、组、tag、part就不赘述了,一搜一大堆,但是网上拿的那些个脚本好多都不好使,所以自己修了一个

坦率的讲,这个脚本是用来作为zabbix的通知媒介脚本的,本人是个菜鸟,如果哪里不对,大神们不要笑话,python也处于学习阶段,如果有哪些地方不合理,很希望可以不吝赐教,废话不多说,脚本奉上:

#!/usr/bin/python
# _*_coding:utf-8 _*_
import urllib2
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def gettoken(corpid, corpsecret):
  gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
  try:
    token_file = urllib2.urlopen(gettoken_url)
  except urllib2.HTTPError as e:
    print e.code
    print e.read().decode("utf8")
    sys.exit()
  token_data = token_file.read().decode('utf-8')
  token_json = json.loads(token_data)
  token_json.keys()
  token = token_json['access_token']
  return token
def senddata(access_token, user, party, agent, subject, content):
  send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
  send_values = "{\"touser\":\"" + user + "\",\"toparty\":\"" + party + "\",\"totag\":\"\",\"msgtype\":\"text\",\"agentid\":\"" + agent + "\",\"text\":{\"content\":\"" + subject + "\n" + content + "\"},\"safe\":\"0\"}"
  send_request = urllib2.Request(send_url, send_values)
  response = json.loads(urllib2.urlopen(send_request).read())
  print str(response)
if __name__ == '__main__':
  user = str(sys.argv[1]) # 参数1:发送给用户的账号,必须关注企业号,并对企业号有发消息权限
  party = str(sys.argv[2]) # 参数2:发送给组的id号,必须对企业号有权限
  agent = str(sys.argv[3]) # 参数3:企业号中的应用id
  subject = str(sys.argv[4]) # 参数4:标题【消息内容的一部分】
  content = str(sys.argv[5]) # 参数5:文本具体内容
  corpid = 'CorpID' # CorpID是企业号的标识
  corpsecret = 'corpsecretSecret' # corpsecretSecret是管理组凭证密钥
  try:
    accesstoken = gettoken(corpid, corpsecret)
    senddata(accesstoken, user, party, agent, subject, content)
  except Exception, e:
    print str(e) + "Error Please Check \"corpid\" or \"corpsecret\" Config"

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》。

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中为什么要用self探讨

接触Python以来,看到类里的函数要带个self参数,一直搞不懂啥麻子原因。晚上特别针对Python的self查了一下,理理。 Python要self的理由 Python的类的方法和普...

python发送邮件功能实现代码

本文实例为大家分享了python发邮件精简代码,供大家参考,具体内容如下 import smtplib from email.mime.text import MIMEText fr...

Python 类与元类的深度挖掘 II【经验】

  上一篇解决了通过调用类对象生成实例对象过程中可能遇到的命名空间相关的一些问题,这次我们向上回溯一层,看看类对象本身是如何产生的。   我们知道 type() 方法可以查看一个对象的类...

python中map()与zip()操作方法

对于map()它的原型是:map(function,sequence),就是对序列sequence中每个元素都执行函数function操作。 比如之前的a,b,c = map(int,r...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...