-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
72 lines (62 loc) · 1.7 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
const Telegraf = require('telegraf');
const Extra = require('telegraf/extra');
const Markup = require('telegraf/markup');
const db = require('./db');
const { TELEGRAM_TOKEN, TELEGRAM_USER } = require('./secrets.js');
const bot = new Telegraf(TELEGRAM_TOKEN);
const itemKeyboard = Markup.inlineKeyboard([Markup.callbackButton('Done', 'done')]);
const addItem = (text) => {
const item = {
stamp: String(Date.now()),
text,
};
return db.newItem(item);
};
const formatItem = item =>
`${item.text} since ${new Date(Number(item.stamp))
.toString()
.split(' ')
.slice(0, -2)
.join(' ')} - ${item.stamp}`;
bot.start(ctx => ctx.reply('Welcome!'));
bot.command('add', (ctx) => {
if (String(ctx.from.id) !== TELEGRAM_USER) {
ctx.reply('Wrong user ID');
return;
}
const text = ctx.message.text
.split(' ')
.slice(1)
.join(' ');
if (!text) {
ctx.reply('No ToDo item ?');
return;
}
addItem(text)
.then(ctx.replyWithMarkdown(`Added item \`${text}\``))
.catch(err => ctx.reply(`An error occured ${err.text}`));
});
bot.command('get', (ctx) => {
if (String(ctx.from.id) !== TELEGRAM_USER) {
ctx.reply('Wrong user ID');
return;
}
db
.getItems()
.then((docs) => {
if (!docs) {
ctx.reply('No ToDo items !');
return;
}
docs.forEach(item => ctx.reply(formatItem(item), Extra.markup(itemKeyboard)));
})
.catch(err => ctx.reply(`An error occured ${err.text}`));
});
bot.action('done', (ctx) => {
const stamp = ctx.callbackQuery.message.text.split(' ').slice(-1)[0];
db.deleteItem(stamp).catch((err) => {
ctx.reply(`An error occured ${err.text}`);
});
return ctx.deleteMessage();
});
bot.startPolling();