-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (95 loc) · 3.17 KB
/
index.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
require('dotenv').config();
const {
Bot,
Keyboard,
InlineKeyboard,
GrammyError,
HttpError,
} = require('grammy');
const { getRandomQuestion, getCorrectAnswer } = require('./utils');
const bot = new Bot(process.env.BOT_API_KEY);
bot.command('start', async (ctx) => {
const startKeyboard = new Keyboard()
.text('HTML')
.text('CSS')
.row()
.text('JavaScript')
.text('React')
.row()
.text('Случайный вопрос')
.resized();
await ctx.reply(
'Привет! Я - Frontend Interview Prep Bot 🤖 \nЯ помогу тебе подготовиться к интервью по фронтенду',
);
await ctx.reply('С чего начнем? Выбери тему вопроса в меню 👇', {
reply_markup: startKeyboard,
});
});
bot.hears(
['HTML', 'CSS', 'JavaScript', 'React', 'Случайный вопрос'],
async (ctx) => {
const topic = ctx.message.text.toLowerCase();
const { question, questionTopic } = getRandomQuestion(topic);
let inlineKeyboard;
if (question.hasOptions) {
const buttonRows = question.options.map((option) => [
InlineKeyboard.text(
option.text,
JSON.stringify({
type: `${questionTopic}-option`,
isCorrect: option.isCorrect,
questionId: question.id,
}),
),
]);
inlineKeyboard = InlineKeyboard.from(buttonRows);
} else {
inlineKeyboard = new InlineKeyboard().text(
'Узнать ответ',
JSON.stringify({
type: questionTopic,
questionId: question.id,
}),
);
}
await ctx.reply(question.text, {
reply_markup: inlineKeyboard,
});
},
);
bot.on('callback_query:data', async (ctx) => {
const callbackData = JSON.parse(ctx.callbackQuery.data);
if (!callbackData.type.includes('option')) {
const answer = getCorrectAnswer(callbackData.type, callbackData.questionId);
await ctx.reply(answer, {
parse_mode: 'HTML',
disable_web_page_preview: true,
});
await ctx.answerCallbackQuery();
return;
}
if (callbackData.isCorrect) {
await ctx.reply('Верно ✅');
await ctx.answerCallbackQuery();
return;
}
const answer = getCorrectAnswer(
callbackData.type.split('-')[0],
callbackData.questionId,
);
await ctx.reply(`Неверно ❌ Правильный ответ: ${answer}`);
await ctx.answerCallbackQuery();
});
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof GrammyError) {
console.error('Error in request:', e.description);
} else if (e instanceof HttpError) {
console.error('Could not contact Telegram:', e);
} else {
console.error('Unknown error:', e);
}
});
bot.start();