forked from LyoSU/quote-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
64 lines (54 loc) · 1.65 KB
/
worker.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const fs = require('fs')
const { Telegraf } = require('telegraf')
const { db } = require('./database')
const { stats } = require('./middlewares')
function setupWorker (botToken) {
console.log(`Worker ${process.pid} started`)
const tdlibProxy = new Proxy({}, {
get (target, prop) {
return (...args) => {
return new Promise((resolve, reject) => {
const id = Date.now() + Math.random()
process.send({ type: 'TDLIB_REQUEST', method: prop, args, id })
const handler = (msg) => {
if (msg.type === 'TDLIB_RESPONSE' && msg.id === id) {
process.removeListener('message', handler)
if (msg.error) {
reject(new Error(msg.error))
} else {
resolve(msg.result)
}
}
}
process.on('message', handler)
})
}
}
})
const bot = new Telegraf(botToken)
bot.use((ctx, next) => {
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'))
ctx.config = config
ctx.db = db
ctx.tdlib = tdlibProxy
return next()
})
bot.use(stats.middleware())
const handler = require('./handler')
bot.use(handler)
process.on('message', async (msg) => {
if (msg.type === 'UPDATE') {
try {
if (typeof bot.handleUpdate !== 'function') {
throw new Error('bot.handleUpdate is not a function')
}
await bot.handleUpdate(msg.payload)
} catch (error) {
console.error('Error processing update in worker:', error)
} finally {
process.send({ type: 'TASK_COMPLETED' })
}
}
})
}
module.exports = { setupWorker }