准备工作
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 = subject
        self.message = message

    def get_token(self, corp_id, secret): #获取token
        url = "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 token
    
    def 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" #企业ID
        secret = "xxxxx" #应用Secret
        userid = "uid1|uid2|uid3" #接收消息的用户账号,支持发给多个用户
        agent_id = "xxxx"  #应用AgentId
        token = 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()

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐