This repository has been archived by the owner on Apr 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
248 lines (203 loc) · 8.52 KB
/
bot.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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
* Main code.
* Inicializa e controla o bot.
*
* emojis (c) https://emojipedia.org
*
* Storage on ctx.session:
* - ultima_resposta_dada
* - esperando_msg
* - ultima_pergunta_identificada
*/
const { Extra, Markup, session } = require('telegraf')
const Brain = require('./brain')
const strUtils = require('../lib/utils/string_utils')
const { strQueriesAprendizado } = require('./brain/aprendizado-utils')
const DEFAULT_REPLY_OPTIONS = Extra.HTML().notifications(false).webPreview(false)
// ========================================== MENSAGENS PRÉ-DEFINIDAS ========================================== //
const MSG_ERRO_FUNCIONALIDADE = 'desculpe, ocorreu um problema 🔧...\nNão tente usar essa funcionalidade por enquanto.'
const HELP_MESSAGE = `${strUtils.asBold('📋Observações:')}
${strUtils.asCode('1.')} conheço os sinônimos de várias palavras;
${strUtils.asCode('2.')} entendo palavras mesmo sem a acentuação devida;
${strUtils.asCode('3.')} a priori, todas as mensagens serão tratadas como perguntas, então não precisam terminar com interrogação;
${strUtils.asCode('4.')} não há distinção entre caracteres maiúsculos e minúsculos;
${strUtils.asCode('5.')} as perguntas que eu já sei responder estão listadas ${strUtils.asLink('aqui', 'https://github.com/micalevisk/siege-telegram-bot#readme')}.`
const COMMANDS_AVAILABLE = `${strUtils.asBold('Olá, eu posso te ajudar a conhecer o Brasil 🇧🇷!')} 😉
Me faça algumas perguntas sobre a geografia brasileira que talvez eu saiba respondê-las 😊
📡 Comandos disponíveis:
${strUtils.asLink('/help')} - ${strUtils.asCode('listar observações e instruções.')}
${strUtils.asLink('/cancelar')} - ${strUtils.asCode('parar espera do bot.')}`
// ------------------------------------------------------------------------------------------------------------- //
/**
* Recupera as opções para respostas
* do bot usando as opções padrão, sem alterá-las
* adicionando a opção 'inReplyTo'.
* @param {number} messageId
* @return {object}
*/
const getExtraWithInReplyTo = messageId => Object.assign({}, DEFAULT_REPLY_OPTIONS, Extra.inReplyTo(messageId))
/**
* Inicializa o bot.
* @param {Telegraf} bot
* @param {RiveScript} rsBrain
*/
function initializeBot(bot, rsBrain) {
const brain = new Brain(rsBrain)
bot.use( session() )
/**
*
* @param {*} ctx
* @param {*} next
* @return {*} envio da resposta
*/
function bandeiraMiddleware(ctx, next) {
const msg = ctx.message.text
const match = ctx.match
if (!match) return next()
const inicioNome = msg.indexOf(match[1])
const nome = brain.primeiroNome(msg, inicioNome)
const { filepath, caption } = brain.getImagemBandeira(nome)
return (filepath)
? ctx.replyWithPhoto(filepath, { caption })
: ctx.reply('Nome inválido 🤷')
}
/**
*
* @param {*} ctx
* @param {object} inlineKeyboard
* @return
*/
function handlerRespostaComInlineKeyboard(ctx, inlineKeyboard) {
return ctx.reply(ctx.session.ultima_resposta_dada, Object.assign({}, getExtraWithInReplyTo(ctx.message.message_id), Extra.markup(inlineKeyboard)) )
}
/**
*
* @param {*} ctx
* @return
*/
function handlerLerResposta(ctx) {
const { session: { ultima_pergunta_identificada }, from: { username, id }, message: { date, text, message_id, entities } } = ctx
const controladorConsulta = async (query) => {
try {
const res = await query.next()
return res !== false
} catch (e) {
console.log('[handlerLerResposta::error]', e)
return null
}
}
const respostaDada = strUtils.removeEmojis( text.trim() )
if (respostaDada) {
ctx.session.esperando_msg = false
return brain.plg
.executeQuery(strQueriesAprendizado.salvarQuestao(ultima_pergunta_identificada, brain.obterTextoComEntidades(respostaDada, entities), username, id, brain.obterAnoDe(date)), controladorConsulta)
.then((salvou) => {
return (salvou)
? ctx.reply('Obrigado por me ensinar!!', getExtraWithInReplyTo(message_id))
: ctx.reply(MSG_ERRO_FUNCIONALIDADE)
})
}
return ctx.reply('Não posso salvar uma resposta vazia (emojis removidos), tente somente caracteres válidos...', getExtraWithInReplyTo(message_id))
}
/**
*
* @param {*} ctx
* @return {promise} envio da resposta
*/
function callBrainMiddleware(ctx, next) {
if (ctx.session.esperando_msg === true) return handlerLerResposta(ctx, next)
const { reply, from: { is_bot, id, username }, message: { text, message_id } } = ctx
if (is_bot) return next()
rsBrain.setUservar(username, 'id', id)
return brain.responderMensagem({ id, username, text })
.then((r) => {
if (r.text) {
ctx.session.ultima_resposta_dada = r.text
return reply(r.text, DEFAULT_REPLY_OPTIONS)
}
if (r.respostaDada) {
ctx.session.ultima_resposta_dada = r.respostaDada
ctx.session.ultima_pergunta_identificada = r.pergunta
return handlerRespostaComInlineKeyboard(ctx, Markup.inlineKeyboard([
Markup.callbackButton(`⚠️ (${r.qtdVotos})`, 'incrementar_votos'),
Markup.callbackButton('✅', 'remover_opcoes'),
]))
}
// msg sem intent ou sem conhecimento externo
ctx.session.ultima_pergunta_identificada = r.pergunta
ctx.session.ultima_resposta_dada = r.respostaAusente
return handlerRespostaComInlineKeyboard(ctx, Markup.inlineKeyboard([
Markup.urlButton('🔍', `http://google.com/search?q=${ctx.session.ultima_pergunta_identificada.replace(/\s/g, '+')}`),
Markup.callbackButton('📝', 'ensinar'),
Markup.callbackButton('😕', 'remover_opcoes'),
]))
})
.catch((msgErro) => {
if (typeof msgErro === 'string') return reply(msgErro, getExtraWithInReplyTo(message_id))
return next()
})
}
bot.start((ctx) => {
ctx.session.esperando_msg = false
ctx.reply(COMMANDS_AVAILABLE, DEFAULT_REPLY_OPTIONS)
})
bot.command('help', ({ reply }) => reply(HELP_MESSAGE, DEFAULT_REPLY_OPTIONS))
bot.command('cancelar', (ctx, next) => {
if (ctx.session.esperando_msg === true) {
ctx.session.esperando_msg = false
return ctx.reply('Tudo bem 🙁 não estou esperando sua resposta mais...')
}
return next()
})
bot.hears(/^(?:qual) .+ bandeira d[oea] (.+)\?*/i, bandeiraMiddleware)
bot.hears(/^[^/\s]+.+$/i, callBrainMiddleware)
bot.action('incrementar_votos', (ctx) => {
const controladorConsulta = async (query) => {
try {
const res = await query.next()
return res.Votos
} catch (e) {
console.log('[bot-incrementar_votos::error]', e)
return null
}
}
return brain.plg
.executeQuery(strQueriesAprendizado.incrementarVoto(ctx.session.ultima_pergunta_identificada), controladorConsulta)
.then((qtdVotos) => {
if (qtdVotos === null) return ctx.reply(MSG_ERRO_FUNCIONALIDADE)
if (qtdVotos > 3) {
return ctx.answerCbQuery('voto negativo computado!')
.then(() => ctx.editMessageText(ctx.session.ultima_resposta_dada, DEFAULT_REPLY_OPTIONS))
.catch((err) => {
console.log('[bot-incrementar_votos::error]', err)
return ctx.deleteMessage() // sessão perdida
})
}
return ctx.answerCbQuery('resposta removida!!')
.then(() => ctx.editMessageText(`${strUtils.asItalic('Desculpe, não sei te responder...')}`, DEFAULT_REPLY_OPTIONS))
.catch((err) => {
console.log('[bot-incrementar_votos::error]', err)
return ctx.deleteMessage() // sessão perdida
})
})
})
bot.action('ensinar', (ctx) => {
ctx.session.esperando_msg = true
return ctx.answerCbQuery('😀 Opa! Estou esperando a sua resposta, tudo bem?', true)
.then(() => ctx.editMessageText(ctx.session.ultima_resposta_dada, DEFAULT_REPLY_OPTIONS))
.catch((err) => {
ctx.session.esperando_msg = false
console.log('[bot-ensinar::error]', err)
return ctx.editMessageText(`Desculpe, perdi sua mensagem...\n${strUtils.asBold('Não')} estou esperando sua resposta`, DEFAULT_REPLY_OPTIONS)
})
})
bot.action('remover_opcoes', (ctx) => {
return ctx.editMessageText(ctx.session.ultima_resposta_dada, DEFAULT_REPLY_OPTIONS)
.catch((err) => {
console.log('[bot-incrementar_votos::error]', err)
return ctx.deleteMessage() // sessão perdida
})
})
bot.startPolling()
}
module.exports = initializeBot