16年python练手,开发了采用企业微信批量发工资条的程序,其中对企业微信发消息的功能做了包装。在此记录和分享一下。
整体程序,使用了 wxPython GUI ,以 excel 来存放数据和消息格式配置。
消息内容和格式都可以在excel内自由定制,不限列数,行数。下面是最终在企业微信内的显示效果。
发消息模块(仅供学习研究)
#!/usr/bin/python
# -*- coding: utf-8 -*-
# WeiXin_App_Helper.py
#
# Copyright (C) 2016 - xulong <fangkailove@yeah.net>
#
import time
import json
import requests
#import pdb
#******************************************
#类定义区
#******************************************
class WeiXin_App_Helper(object):
"""
#企业微信应用消息发送工具类,
corpid : 填写自己企业ID,
corpsecret : 填写自己的管理组Secret,
appid :应用ID
"""
def __init__(self, corpid, corpsecret,appid):
#self.corpid = corpid
#self.corpsecret = corpsecret
self.baseurl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}'.format(corpid, corpsecret)
self.appid = appid
self.expire_time = 0.0
self.access_token = ""
#print 'ini exprie_time',self.expire_time
# 获取token
def __get_token(self):
retDict = {'errcode':0}
if self.expire_time < time.time(): #到期时间小于当前时间,说明token到期了需要重新获取
try:
response = requests.get(self.baseurl)
#pdb.set_trace()
if response.status_code == 200:
retDict = response.json()
if 'errcode' in retDict.keys():
if retDict['errcode'] != 0:
return retDict
self.expire_time = time.time() + retDict['expires_in']
self.access_token = retDict['access_token']
except Exception, e:
retDict["errcode"]=9999
retDict["errmsg"]=e.message
#print 'get new expire_time:',self.expire_time
return retDict
def send_msg(self,touser,content):
"""
发送消息,
touser:接收消息者(企业微信中的微信号),
content:消息内容
"""
#print "access_Token", qs_token
#pdb.set_trace()
retDict=self.__get_token()
if retDict['errcode'] != 0:
return retDict
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}".format(self.access_token)
payload = {
"touser": touser,
"msgtype": "text",
"agentid": self.appid,
"text": {
"content": content
},
"safe": "1"
}
#print payload
data = json.dumps(payload, ensure_ascii=False)
data = data.encode('utf-8')
try:
#pdb.set_trace()
response = requests.post(url, data=data)#,verify=resource_path("cacert.pem"))
#print ret
if response.status_code == 200:
retDict = response.json()
except Exception, e:
retDict["errcode"]=9999
retDict["errmsg"]=e.message
return retDict
if __name__ == '__main__':
print 'test send message'
g_corpid = "xxxxxxxxxxxxxxxxxx" # 填写自己企业ID
g_corpsecret ="XXXXXXXXXXXXXXXXXXXXXXXXXX" # 填写自己的管理组Secret
g_appid = 99 #应用ID
winxin = WeiXin_App_Helper(g_corpid,g_corpsecret,g_appid)
winxin.send_msg('101062','test mdsfasfasfasfessage')