This repository was archived by the owner on Apr 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
156 lines (130 loc) · 4.27 KB
/
app.js
File metadata and controls
156 lines (130 loc) · 4.27 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
'use strict'
const ngrok = require('ngrok')
const config = require('./config')
const commands = require('./commands')
const database = require('./lib/database')
const DomainError = require('./lib/DomainError')
const accessorsFactory = require('./lib/accessors')
const TelegramBot = require('node-telegram-bot-api')
const callbackHandlers = require('./callback-handlers')
const { types: responseTypes, handler: responseHandler } = require('./lib/response')
const getWebHookUrl = async ({ webhook, API_TOKEN }) => {
const hostname = webhook.hostname || await ngrok.connect(config.telegram.webhook.port).then(url => url.split('//')[1])
return `https://${hostname}/${API_TOKEN}`
}
const runCommand = async ({ bot, command, msg, match, repositories, chat, accessors, err }) => {
try {
const result = await command({ msg, match, bot, config, repositories, chat, responseTypes, accessors })
await responseHandler(bot, msg.chat.id, result)
} catch (e) {
return err(e)
}
}
const handleCallbackQuery = async ({ bot, handler, query, match, accessors, repositories, err }) => {
try {
const result = await handler({ query, match, repositories, responseTypes, config, accessors })
await responseHandler(bot, query.message.chat.id, result)
} catch (e) {
return err(e)
}
}
const sendError = (bot, msg) => {
return (err) => {
if (err instanceof DomainError) {
return bot.sendMessage(msg.chat.id, err.message, { parse_mode: 'Markdown', reply_to_message_id: msg.message_id })
}
console.error(err)
bot.sendMessage(msg.chat.id, `Erro ao executar comando: ${err.message}`, {
parse_mode: 'Markdown'
})
}
}
const sendCallbackError = (bot, queryId) => {
return (err) => {
if (err instanceof DomainError) {
return bot.answerCallbackQuery(queryId, { text: err.message, show_alert: true })
}
console.error(err)
bot.answerCallbackQuery(queryId, { text: `Erro ao processar solicitação: ${err.message}`, show_alert: true })
}
}
const setupDependencies = bot => {
const { repositories } = database.factory(config.database)
const accessors = accessorsFactory(bot)
return { bot, repositories, accessors }
}
const setupCommands = async ({ bot, repositories, accessors }) => {
for (const [ , command ] of Object.entries(commands)) {
bot.onText(command.regex, async (msg, match) => {
const chat = await repositories.chats.findById(msg.chat.id)
if (!chat) {
await repositories.chats.create({
id: msg.chat.id,
type: msg.chat.type
})
}
return runCommand({
bot,
command,
msg,
match,
config,
repositories,
chat,
accessors,
err: sendError(bot, msg)
})
})
}
return { bot, repositories, accessors, commands: Object.keys(commands) }
}
const setupCallbackQueries = async ({ bot, repositories, accessors, commands }) => {
bot.on('callback_query', (query) => {
if (!query.message || !query.message.chat || !query.message.chat.id) return
const handler = callbackHandlers.getHandler(query.data)
if (!handler) return
return handleCallbackQuery({
bot,
handler,
query,
match: query.data.match(handler.regex),
accessors,
repositories,
err: sendCallbackError(bot, query.id)
})
})
return { bot, repositories, accessors, commands }
}
const setupErrorEvent = async bot => {
bot.on('polling_error', err => {
console.error(err)
})
return bot
}
const start = async () => {
const bot = new TelegramBot(config.telegram.API_TOKEN, {
webHook: {
autoOpen: true,
port: config.telegram.webhook.port,
host: config.telegram.webhook.bindingHost
},
onlyFirstMatch: true
})
const webHookUrl = await getWebHookUrl(config.telegram)
bot.setWebHook(webHookUrl)
.then(() => console.log(`Webhook set to https://${webHookUrl.split('/')[2]}`))
.then(() => bot.getMe())
.then(me => {
console.log(`Escutando em @${me.username}`)
return bot
})
.then(setupErrorEvent)
.then(setupDependencies)
.then(setupCommands)
.then(setupCallbackQueries)
.then(({ commands }) => console.log(`${commands.length} comandos carregados`))
.catch(err => { console.error(err); process.exit(1) })
}
module.exports = {
start
}