feat: 支持telegram bot

This commit is contained in:
tangyanbiao 2021-12-21 14:31:29 +08:00
parent e5dd79794b
commit 129e4d67c7
5 changed files with 47 additions and 24 deletions

View File

@ -1 +1,4 @@
WEBHOOK_URL=飞书群机器人 webhook 地址
BOTS='TELEGRAM'
FEISHU_TOKEN=''
TELEGRAM_TOKEN=''
TELEGRAM_CHAT_ID=''

View File

@ -1,25 +1,4 @@
import {VercelRequest, VercelResponse} from '@vercel/node'
import fetch from 'node-fetch'
async function send(content: string) {
const body = JSON.stringify({
"msg_type": "text",
"content": {
"text": content
}
})
const res = await fetch(process.env.WEBHOOK_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body,
})
const data = await res.json()
if (data.StatusCode !== 0) {
console.error(data.StatusMessage)
}
}
function handleMessage(name: string, data: any): string {
let action = ''
@ -56,10 +35,16 @@ async function main(req: VercelRequest, res: VercelResponse) {
res.setHeader('Allow', 'POST')
return res.status(405).end('Method Not Allowed')
}
const bots = (process.env.BOTS || '').split(',').map(v => v.toUpperCase())
try {
const product = req.query.product.toString() || 'Unknown'
const content = handleMessage(product, req.body)
await send(content)
if (bots.indexOf('TELEGRAM') >= 0) {
await sendToTelegram(content)
}
if (bots.indexOf('FEISHU') >= 0) {
await sendToFeishu(content)
}
return res.status(200).end('ok')
} catch (e) {
console.error(e)

20
bot/feishu.ts Normal file
View File

@ -0,0 +1,20 @@
async function sendToFeishu(content: string) {
const URL = `https://open.feishu.cn/open-apis/bot/v2/hook/${process.env.FEISHU_TOKEN}`
const body = JSON.stringify({
"msg_type": "text",
"content": {
"text": content
}
})
const res = await fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body,
})
const data = await res.json()
if (data.StatusCode !== 0) {
console.error(data.StatusMessage)
}
}

15
bot/telegram.ts Normal file
View File

@ -0,0 +1,15 @@
async function sendToTelegram(text: string) {
const URL = `https://api.telegram.org/bot${process.env.TELEGRAM_TOKEN}/sendMessage`
const body = `chat_id=${process.env.TELEGRAM_CHAT_ID}&text=${text}`
const res = await fetch(URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body,
})
const data = await res.json()
if (!data.ok) {
console.error(data.StatusMessage)
}
}

View File

@ -1,5 +1,5 @@
{
"rewrites": [
{ "source": "/hooks/:product", "destination": "/api/bot/feishu" }
{ "source": "/hooks/:product", "destination": "/api/txc" }
]
}