txc-webhooks/api/txc.ts

60 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-10-15 07:40:45 +00:00
import {VercelRequest, VercelResponse} from '@vercel/node'
2021-12-21 06:57:38 +00:00
import { sendToTelegram } from '../bot/telegram'
import { sendToFeishu } from '../bot/feishu'
2021-10-15 07:40:45 +00:00
function handleMessage(name: string, data: any): string {
let action = ''
let content = ''
switch (data.type) {
// 主贴发表
case 'post.created':
action = '主贴发表'
content = data?.payload?.post?.content
break
// 主贴更新
case 'post.updated':
action = '主贴更新'
content = data?.payload?.post?.content
break
// 回复发表
case 'reply.created':
action = '回复发表'
content = data?.payload?.reply?.content
break
// 回复更新
case 'reply.updated':
action = '回复更新'
content = data?.payload?.reply?.content
break
default:
2021-12-21 06:57:38 +00:00
action = data.type
content = JSON.stringify(data?.payload)
break
2021-10-15 07:40:45 +00:00
}
return `${name}${action}: ${content}`
}
2021-12-26 18:03:53 +00:00
async function main(req: VercelRequest, res: VercelResponse) {
2021-10-15 07:40:45 +00:00
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST')
return res.status(405).end('Method Not Allowed')
}
2021-12-21 06:31:29 +00:00
const bots = (process.env.BOTS || '').split(',').map(v => v.toUpperCase())
2021-10-15 07:40:45 +00:00
try {
const product = req.query.product.toString() || 'Unknown'
const content = handleMessage(product, req.body)
2021-12-21 06:31:29 +00:00
if (bots.indexOf('TELEGRAM') >= 0) {
2021-12-26 18:03:53 +00:00
await sendToTelegram(content)
2021-12-21 06:31:29 +00:00
}
if (bots.indexOf('FEISHU') >= 0) {
2021-12-26 18:03:53 +00:00
await sendToFeishu(content)
2021-12-21 06:31:29 +00:00
}
2021-10-15 07:40:45 +00:00
return res.status(200).end('ok')
} catch (e) {
console.error(e)
return res.status(500).end(e.message || 'Server Error')
}
}
2021-12-26 18:03:53 +00:00
export default main