-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
45 lines (39 loc) · 1.15 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const fs = require('fs')
const url = require('url')
const http = require('http')
const https = require('https')
module.exports = (bot) => {
const token = '/' + bot.token
const opt = bot.config.webhook
const host = opt.host
const port = opt.port
const path = url.parse(opt.url).pathname
const key = opt.key && fs.readFileSync(opt.key)
const cert = opt.cert && fs.readFileSync(opt.cert)
const botUrl = path && path !== '/' ? path : ''
const fullPath = botUrl + token
const handler = (req, res) => {
if (req.url == fullPath && req.method == 'POST') {
let body = ''
req.on('data', (data) => body += data)
req.on('end', () => {
res.end()
try {
const update = JSON.parse(body)
bot.updateState(update)
} catch (error) {
bot.log('[bot.error.webhook]', error)
res.end()
}
})
}
}
// Create server
const server = key && cert ?
https.createServer({key, cert}, handler) :
http.createServer(handler)
// Start server
server.listen(port, host, () => {
bot.log(`[webhook] started${ key ? ' secure' : ''} server on "${ host }:${ port }"`)
})
}