利用 Vercel 搭建企业微信消息推送 API
2022/6/3 23:21:59
本文主要是介绍利用 Vercel 搭建企业微信消息推送 API,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Vercel 是一个用于前端框架和静态站点的平台,可以用来部署静态网站和 Serverless 函数,功能强大,使用方便。
企业微信提供一系列的 API 接口,可以通过企业微信应用或群机器人发送消息,而且企业微信接入了 MiPush,在 MIUI 系统上可以无后台接收消息。
但是发送企业微信应用消息比较麻烦,要先通过corpid
和corpsecret
获取access_token
,然后通过 POST 请求发送消息。所以我利用 Vercel 搭建了一个 Serverless 函数,只需要一个token
就可以发送消息,非常方便。
接口说明
请求地址为https://api.meancoder.xyz/push,参数如下:
参数 | 必须 | 说明 |
---|---|---|
token | 是 | 在环境变量中设置的TOKEN ,用于验证身份 |
content | 是 | 消息内容 |
msgtype | 否 | text 或markdown ,默认为text |
touser | 否 | 指定接收消息的成员,默认为Mean |
代码
# -*- coding: utf8 -*- import requests import json import os import urllib.parse from http.server import BaseHTTPRequestHandler def push(content, touser, msgtype): params = { 'corpid': os.environ['CORPID'], 'corpsecret': os.environ['CORPSECRET'] } access_token = json.loads(requests.get( 'https://qyapi.weixin.qq.com/cgi-bin/gettoken', params=params).text)['access_token'] push_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+access_token data = { 'msgtype': msgtype, 'agentid': os.environ['AGENTID'], msgtype: { 'content': content }, 'touser': touser } response = requests.post(push_url, json=data) return response.text class handler(BaseHTTPRequestHandler): def do_GET(self): errcode = 0 errmsg = "ok" content = "" touser = "Mean" msgtype = "text" datas = urllib.parse.parse_qs(self.path.split("?")[1]) if "token" not in datas: errcode = -1 errmsg = "no token" elif datas["token"][0] != os.environ["TOKEN"]: errcode = -2 errmsg = "invalid token" if "content" in datas: content = datas["content"][0] else: errcode = -3 errmsg = "no content" if "touser" in datas: touser = datas["touser"][0] if "msgtype" in datas: if datas["msgtype"][0] not in ["text", "markdown"]: errcode = -4 errmsg = "invalid token" else: msgtype = datas["msgtype"][0] if errcode == 0: errmsg = push(content, touser, msgtype) else: errmsg = json.dumps({"errcode": errcode, "errmsg": errmsg}) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(errmsg.encode()) return
重定向
由于 api 要放在/api
路径下,默认是通过https://api.meancoder.xyz/api/push发送请求。如果在根目录配置vercel.json
文件,就可以把/api
重定向到根目录,就能直接通过https://api.meancoder.xyz/push发送请求了。
{ "rewrites": [ { "source": "/:path*", "destination": "/api/:path*" } ] }
这篇关于利用 Vercel 搭建企业微信消息推送 API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升