-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (87 loc) · 2.37 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
import TelegramBot from 'node-telegram-bot-api';
import { readFile, writeFile, readFileSync } from 'fs';
import { config } from 'dotenv';
config();
const token = process.env.BOT_TOKEN;
const bot = new TelegramBot(token, { polling: true });
const dataFile = 'data.json';
const saveData = (input, id) => {
readFile(dataFile, function (err, data) {
const parsedData = JSON.parse(data);
// create an empty array if user does not have entry before
if (parsedData[id] === undefined) {
parsedData[id] = [];
}
// increment last id
input.id = (parsedData[id].at(-1)?.id || 0) + 1;
parsedData[id].push(input);
writeFile(dataFile, JSON.stringify(parsedData), () => { })
});
}
const isSaved = (uid, kw) => {
const data = readFileSync(dataFile);
const json = JSON.parse(data);
return !!json[`${uid}`]?.find(e => e.title === kw);
}
const parts = (k) => {
let title, description;
const hasDesc = (q) => {
const regex = new RegExp(/(, )./);
return regex.test(q);
}
if (hasDesc(k)) {
const arr = k.split(',').map(e => e.trim());
title = arr[0];
description = arr[1];
}
else {
title = k.replace(',', '').trim();
description = undefined;
}
return {
title,
description
}
}
/*
bot events
*/
bot.on('inline_query', (msg) => {
const uid = msg.from.id;
const query = msg.query;
const title = parts(query).title;
const description = parts(query).description ?? 'tap to save';
const data = readFileSync(dataFile);
const json = JSON.parse(data);
// const articles = json[`${uid}`] || [];
const articles = Object.values(json).flat().filter(e => e.title.startsWith(title));
const newArticle = isSaved(uid, title) ? [] : [
{
type: 'article',
id: Date.now(),
title: title || 'Write something,',
description,
input_message_content:
{
message_text: `${title || 'nothing'} saved`
}
}
];
bot.answerInlineQuery(msg.id, [...newArticle, ...articles], { cache_time: 0 });
});
bot.on('chosen_inline_result', (msg) => {
const uid = msg.from.id;
const query = msg.query;
if (isSaved(uid, parts(query).title)) return;
saveData({
type: 'article',
title: parts(query).title,
description: parts(query).description,
input_message_content: {
message_text: query,
}
}, uid);
});
bot.on('polling_error', (error) => {
console.log(error);
});