准备工作:
1.需要注册个企业微信账号,地址:https://work.weixin.qq.com/wework_admin/loginpage_wx
2.在企业微信中,创建一个应用,如下图:
需要上传应用logo、填写应用名称、并选择成员,之后点击创建应用
3.应用创建成功后,进入应用,获取应用的AgentId和Secret,如下图:
4.企业微信发送应用消息接口文档地址:https://developer.work.weixin.qq.com/document/path/90236
实现代码:
import requests
import datetime
import json
import urllib3
urllib3.disable_warnings()class SendWeixin:#调用企业微信接口发送微信消息def __init__(self, subject, message): #消息主题和消息内容self.subject = subjectself.message = messagedef get_token(self, corp_id, secret): #获取tokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}".format(corp_id, secret)r = requests.get(url=url)token = r.json()['access_token']return tokendef send_message(self, userid, agent_id, token):url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(token)data = {"touser": userid,"msgtype": "text","agentid": agent_id,"text": {"content": self.subject + '\n' + self.message},"safe":"0"}r = requests.post(url=url, data=json.dumps(data), verify=False)#print(r.json())def send_markdown(self, userid, agent_id, token): #发送markdown消息url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(token)data = {"touser" : userid,"msgtype": "markdown","agentid" : agent_id,"markdown": {"content": """您的会议室已经预定>**事项详情** >事 项:<font color=\"info\">开会</font> >请准时参加会议。 > >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)"""},"enable_duplicate_check": 0,"duplicate_check_interval": 1800}r = requests.post(url=url, data=json.dumps(data), verify=False)print(r.json()) def main(self):corp_id = "xxxxxx" #企业IDsecret = "xxxxx" #应用Secretuserid = "uid1|uid2|uid3" #接收消息的用户账号,支持发给多个用户agent_id = "xxxx" #应用AgentIdtoken = self.get_token(corp_id, secret)self.send_markdown(userid, agent_id, token) #发送markdown消息self.send_message(userid, agent_id, token) #发送文本消息subject = "企业微信测试消息"
message = "test123"
send_weixin = SendWeixin(subject, message)
send_weixin.main()