简述
使用企业微信应用开放的api,使得自定义消息能即时推送到微信(不安装企业微信也可行)
使用Flask框架搭建简易api,简化上述流程,方便自己调用。
调用格式如下
api调用格式: HOST:PORT/API?msg=YOURMESSAGE
举个栗子: localhost:9999/testApi?msg=helloworld
需要手动创建并获取企业微信应用,怎么获取可以参考
CORPID=’’ # 企业id
AGENTID=’’ # 应用id
CORPSECRET=’’ # 应用secret
可配置参数如下
HOST = ‘localhost’ # 如需部署外网访问,请设置0.0.0.0
PORT = 9999 # 端口号
API = ‘testApi’ # API接口名,如localhost:9999/test?msg=
'''
api调用格式: HOST:PORT/API?msg=YOURMESSAGE
举个栗子: localhost:9999/testApi?msg=helloworld
'''
import json,requests
from flask import Flask,request
CORPID='' # 企业id
AGENTID='' # 应用id
CORPSECRET='' # 应用secret
HOST = 'localhost' # 如需部署外网访问,请设置0.0.0.0
PORT = 9999 # 端口号
API = 'testApi' # API接口名,如localhost:9999/test?msg=
def send_to_wecom(text,wecom_cid,wecom_aid,wecom_secret,wecom_touid='@all'):
get_token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={wecom_cid}&corpsecret={wecom_secret}"
response = requests.get(get_token_url).content
access_token = json.loads(response).get('access_token')
if access_token and len(access_token) > 0:
send_msg_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
data = {
"touser":wecom_touid,
"agentid":wecom_aid,
"msgtype":"text",
"text":{
"content":text
},
"duplicate_check_interval":600
}
response = requests.post(send_msg_url,data=json.dumps(data)).content
return response
else:
return False
app = Flask(__name__)
@app.route('/'+API)
def myApi():
msg = request.args.get('msg')
ret = send_to_wecom(msg, CORPID, AGENTID, CORPSECRET)
return ret
if __name__ == "__main__":
app.run(HOST,PORT)