-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathTelegramBotIntegration.js
697 lines (647 loc) · 19.1 KB
/
TelegramBotIntegration.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/**
* @author Davide Garino
* @year 2022
* @email [email protected]
* @repository https://github.com/R3D4NG3L/PersonalExpenseReport
* @version 1.0.1
*/
// ---------------------------------------------------------------------------------------------------
// Script initialization - User must compile this part with own tokens
// ---------------------------------------------------------------------------------------------------
/**
* @var token
* @brief 1. Fill with your own Telegram Bot Token Id
* (e.g. 521xxxx7165:AAHxxxxxxxxjbHr5l-m8rGxxxxxxwbk)
*/
var token = "";
/**
* @var webAppUrl
* @brief 2. Fill with your google web app address
* (e.g. https://script.google.com/macros/s/AKfycbXXXXLHeAY-07_A2dmXftSX0JNR8gTxxxEQmzo2j2aWmItIuSsFSYzlB1bJNw0Dovd3qw/exec)
*/
var webAppUrl = "";
/**
* @var ssId
* @brief 3. Fill with Google Spreadsheet Id
* (e.g. 1f_IT_kAFIG0TUOZyXXXXW67fxvdxxxxaw6gbAbtxzEo)
*/
var ssId = "";
/**
* @var locale
* @brief 4. Set your locale for date time parsing
* e.g. it-IT
* e.g. en-US
*/
var locale = "";
/**
* @var timeZone
* @brief 5. Set your timezone for proper date formatting
* e.g. "Europe/Rome"
* e.g. "America/New_York"
*/
var timeZone = "";
/**
* @var currency
* @brief 6. Set your currency
* e.g. "$"
* e.g. "€"
*/
var currency = "";
/**
* @var adminID
* @brief 7. Admin Telegram Chat Id.
* Used to debug in case of problems, error will be sent as a telegram message
* to the chat here mentioned.
* (e.g. 875276202)
*/
var adminID = ""; // 4. Fill in your own Telegram ID for debugging
// ---------------------------------------------------------------------------------------------------
// Script initialization finish
// ---------------------------------------------------------------------------------------------------
/**
* @var telegramUrl
* @brief Telegram Bot Url
*/
var telegramUrl = "https://api.telegram.org/bot" + token;
/*!
* @fn getMe
* @brief Get Telegram Bot
*/
function getMe()
{
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
/*!
* @fn setWebhook
* @brief Set Telegram Webhook
*/
function setWebhook()
{
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
}
/*!
* @fn sendText
* @brief Send Text to Telegram Chat
*/
function sendText(chatId, text, keyBoard)
{
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(chatId),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
};
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
/**
* @fn deleteMessage
* @param {*} chatId
* @param {*} messageId
*/
function deleteMessage(chatId, messageId)
{
var data = {
method: "post",
payload: {
method: "deleteMessage",
chat_id: String(chatId),
message_id: String(messageId)
}
};
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
/*!
* @fn doGet
* @brief HTML Web Service Page
*/
function doGet(e)
{
return HtmlService.createHtmlOutput("<img src='https://i.kym-cdn.com/photos/images/facebook/001/005/935/ef1.jpg'>");
}
/**
* @fn debugMessage
* @param {*} e
*/
function debugMessage(e)
{
// Debug
var data = JSON.parse(e.postData.contents);
if (data.callback_query)
{
var id = data.callback_query.from.id;
sendText(id, "<pre>" + JSON.stringify(e.postData.contents) + "</pre>");
}
else
{
var id = data.message.chat.id;
sendText(id, "<pre>" + JSON.stringify(e.postData.contents) + "</pre>");
}
// End of Debug
}
/**
* @fn logMessage
* @param {@} e: Telegram Message
*/
function logMessage(e)
{
// Log Message
var data = e.postData.contents;
// Google Sheet
var googleSheet = SpreadsheetApp.openById(ssId);
var telegramLog = googleSheet.getSheetByName("Logs");
var lr = telegramLog.getDataRange().getLastRow();
telegramLog.getRange(lr + 1, 1).setValue(data);
}
/**
* @fn clearLogs
* @param {*} e
*/
function clearLogs()
{
// Google Sheet
var googleSheet = SpreadsheetApp.openById(ssId);
var telegramLog = googleSheet.getSheetByName("Logs");
var lr = telegramLog.getDataRange().getLastRow();
for (var i = 2; i < lr + 1; i++)
telegramLog.getRange(i, 1).clearContent();
}
/**
* @fn isNumber
* @brief Checks if a value is a valid number
*/
function isNumber(n)
{
'use strict';
n = n.replace(/\./g, '').replace(',', '.');
return !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* @fn sendTotalExpensesList
* @param {@} id ID of telegram user that asked for the service
*/
function sendTotalExpensesList(id)
{
// Google Sheet
var expenseSheet = SpreadsheetApp.openById(ssId);
var expenses = [];
var dashboardSheet = expenseSheet.getSheetByName("Dashboard");
var lr = dashboardSheet.getDataRange().getLastRow();
for (var i = 2; i <= lr; i++)
{
var category = dashboardSheet.getRange(i, 1).getValue();
var total = dashboardSheet.getRange(i, 2).getValue();
if (total == "")
continue;
expenses.push("\n<b>" + category + "</b>: "+ currency +" " + Number(total).toFixed(2));
}
var expenseList = expenses.join("\n");
sendText(id, decodeURI("<b>Here are your total expenses:</b> <span class=\"tg-spoiler\">%0A " + expenseList) + "\n\n--------------------\n" + "<b><u>💵 TOTAL: " + currency + " " + dashboardSheet.getRange(1, 4).getValue() + "</u></b></span>");
sendMainMenuKeyboard(id);
}
/**
* @fn sendLast5Expenses
* @param {@} id ID of telegram user that asked for the service
*/
function sendLast5Expenses(id)
{
// Google Sheet
var expenseSheet = SpreadsheetApp.openById(ssId);
var expenses = [];
var expensesSheet = expenseSheet.getSheetByName("Expenses");
var lr = expensesSheet.getDataRange().getLastRow();
var counter = 0;
for (var i = lr; i > 1; i--)
{
var date = expensesSheet.getRange(i, 1).getValue();
date = Date.parse(date);
date = new Date(date).toLocaleDateString(locale, {timeZone: timeZone});
var description = expensesSheet.getRange(i, 2).getValue();
var cost = expensesSheet.getRange(i, 3).getValue();
var category = expensesSheet.getRange(i, 4).getValue();
var detalis = expensesSheet.getRange(i, 5).getValue();
expenses.push("\n---------\n"
+ "🗓️ Date: <b>" + date
+ "</b>\n📋 Category: <b>" + category
+ "</b>\n🔎 Description: <b>" + description
+ "</b>\n💸 Cost: <b>" + currency + " " + cost
+ "</b>\n🕵 Details: <b>" + detalis + "</b>");
counter++;
if (counter >= 5)
break;
}
var expenseList = expenses.join("\n");
sendText(id, decodeURI("<b>Here are your last 5 expenses:</b> %0A " + expenseList));
sendMainMenuKeyboard(id);
}
/**
* @fn addNewExpense
* @param {*} id
*/
function addNewExpenseStep1Date(id)
{
var today = new Date();
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var twoDaysAgo = new Date();
twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
var keyBoard = {
"inline_keyboard": [
[
{
"text": "📅 Today - " + today.toLocaleDateString(locale, {timeZone: timeZone}),
"callback_data": "newExpDate" + today.getTime()
}
],
[
{
"text": "📆 Yestday - " + yesterday.toLocaleDateString(locale, {timeZone: timeZone}),
"callback_data": "newExpDate" + yesterday.getTime()
}
],
[
{
"text": "🗓️ 2 Days Ago - " + twoDaysAgo.toLocaleDateString(locale, {timeZone: timeZone}),
"callback_data": "newExpDate" + twoDaysAgo.getTime()
},
]
]
};
sendText(id, "<b><u>🕰️ Choose the expense date:</u></b>", keyBoard);
}
/**
* @fn addNewExpenseStep2Category
* @param {*} id
*/
function addNewExpenseStep2Category(id)
{
var categoryList = [];
// Google Sheet
var expenseSheet = SpreadsheetApp.openById(ssId);
var categoriesList = [];
var categoriesSheet = expenseSheet.getSheetByName("Categories");
var lr = categoriesSheet.getDataRange().getLastRow();
for (var i = 2; i <= lr; i++)
{
var category = categoriesSheet.getRange(i, 1).getValue();
categoriesList.push(
[
{
"text": category,
"callback_data": "category" + category
}
]
);
}
var keyBoard = {
"inline_keyboard": []
};
categoriesList.forEach(element => keyBoard["inline_keyboard"].push(element));
sendText(id, "<b><u>📋 Choose the expense category:</u></b>", keyBoard);
}
/**
* @fn addNewExpenseStep3Description
* @param {*} id
*/
function addNewExpenseStep3Description(id)
{
sendText(id, "<b><u>📜 Write the expense description:</u></b>");
}
/**
* @fn addNewExpenseStep4Value
* @param {*} id
*/
function addNewExpenseStep4Value(id)
{
sendText(id, "<b><u>💸 Write the expense value:</u></b>");
}
/**
* @fn addNewExpenseStep5Details
* @param {*} id
*/
function addNewExpenseStep5Details(id)
{
var keyBoard = {
"inline_keyboard": [
[
{
"text": "N/A",
"callback_data": "detailsNotAvailable"
}
]
]
};
sendText(id, "<b><u>🕵 Write the expense details:</u></b>", keyBoard);
}
/**
* @fn sendMainMenuKeyboard
* @param {@} id ID of telegram user that asked for the service
*/
function sendMainMenuKeyboard(id)
{
var keyBoard = {
"inline_keyboard": [
[
{
"text": "⏮️ Total Expenses",
"callback_data": 'totalExpenses'
}
],
[
{
"text": "💸 Last 5 Expenses",
"callback_data": 'last5Expenses'
}
],
[
{
"text": "✍️ Add new expense",
"callback_data": 'addNewExpenseStep1Date'
},
],
[
{
"text": "❌ Delete an expense",
"callback_data": 'deleteAnExpense'
},
]
]
};
sendText(id, "What you want to do?", keyBoard)
}
/**
* @fn addExpenseToSpreadsheet
* @param {@} id ID of telegram user that asked for the service
*/
function addExpenseToSpreadsheet(id)
{
try
{
// Google Sheet
var googleSheet = SpreadsheetApp.openById(ssId);
var telegramLog = googleSheet.getSheetByName("Logs");
var lr = telegramLog.getDataRange().getLastRow();
var date = JSON.parse(telegramLog.getRange(lr - 4, 1).getValue());
date = date.callback_query.data.slice("newExpDate".length);
date = new Date(parseInt(date)).toLocaleDateString(locale, {timeZone: timeZone});
var category = JSON.parse(telegramLog.getRange(lr - 3, 1).getValue());
category = category.callback_query.data.slice("category".length);
var description = JSON.parse(telegramLog.getRange(lr - 2, 1).getValue());
description = description.message.text.charAt(0).toUpperCase() + description.message.text.slice(1);
var value = JSON.parse(telegramLog.getRange(lr - 1, 1).getValue());
valueParsed = parseFloat(value.message.text.replace(/\s/g, "").replace(",", "."));
var details = JSON.parse(telegramLog.getRange(lr, 1).getValue());
if (details.callback_query)
details = "";
else
details = details.message.text.charAt(0).toUpperCase() + details.message.text.slice(1);
var expensesSheet = googleSheet.getSheetByName("Expenses");
lr = expensesSheet.getDataRange().getLastRow();
expensesSheet.getRange(lr + 1, 1).setValue(date);
expensesSheet.getRange(lr + 1, 2).setValue(description);
expensesSheet.getRange(lr + 1, 3).setValue(valueParsed);
expensesSheet.getRange(lr + 1, 4).setValue(category);
expensesSheet.getRange(lr + 1, 5).setValue(details);
sendText(id, "✔️ Expense added correctly!");
sendTotalExpensesList(id);
}
catch (e)
{
sendText(id, "❌ An error occurred: " + e);
}
}
/**
* @fn manageAddExpense
* @param {*} id: Chat id
* @return true: Managed correctly
* false: Error
*/
function manageAddExpense(id)
{
// Google Sheet
var googleSheet = SpreadsheetApp.openById(ssId);
var telegramLog = googleSheet.getSheetByName("Logs");
var lr = telegramLog.getDataRange().getLastRow();
if (lr < 4)
return false;
var fourthLastLog = JSON.parse(telegramLog.getRange(lr - 3, 1).getValue());
var thirdLastLog = JSON.parse(telegramLog.getRange(lr - 2, 1).getValue());
var secondLastLog = JSON.parse(telegramLog.getRange(lr - 1, 1).getValue());
var lastLog = JSON.parse(telegramLog.getRange(lr, 1).getValue());
if (true
&& lastLog.message
&& secondLastLog.callback_query
&& secondLastLog.callback_query.data.includes("category"))
{
// User wrote "Description", wait for Value
addNewExpenseStep4Value(id);
return true;
}
else if (true
&& lastLog.message
&& secondLastLog.message
&& thirdLastLog.callback_query
&& thirdLastLog.callback_query.data.includes("category"))
{
// User wrote "Value", wait for Details
// Data Validation
if (!isNumber(lastLog.message.text))
{
sendText(id, "❌ An error occurred: value inserted is not valid! (" + lastLog.message.text + ")");
return false;
}
addNewExpenseStep5Details(id);
return true;
}
else if (true
&& lastLog.message
&& secondLastLog.message
&& thirdLastLog.message
&& fourthLastLog.callback_query
&& fourthLastLog.callback_query.data.includes("category"))
{
// User wrote "Details", ready to add expense
addExpenseToSpreadsheet(id);
return true;
}
return false;
}
/**
* @fn deleteAnExpenseChoose
* @brief Choose which expense to delete
*/
function deleteAnExpenseChoose(id)
{
// Google Sheet
var expenseSheet = SpreadsheetApp.openById(ssId);
var expenses = [];
var expensesSheet = expenseSheet.getSheetByName("Expenses");
var lr = expensesSheet.getDataRange().getLastRow();
categoriesList = []
counter = 0;
for (var i = lr; i > 1; i--)
{
var date = expensesSheet.getRange(i, 1).getValue();
date = Date.parse(date);
var dateNotParsed = new Date(date);
var dateParsed = dateNotParsed.toLocaleDateString(locale, {timeZone: timeZone});
var description = expensesSheet.getRange(i, 2).getValue();
var cost = expensesSheet.getRange(i, 3).getValue();
var category = expensesSheet.getRange(i, 4).getValue();
var detalis = expensesSheet.getRange(i, 5).getValue();
categoriesList.push(
[
{
"text": "🗑️ " + dateParsed + ": " + category + " - " + description + " - " + currency + " " + cost,
"callback_data": "deleteExpense" + i + "_" + dateNotParsed.getTime() + "_" + cost
}
]
);
counter++;
if (counter >= 5)
break;
}
var keyBoard = {
"inline_keyboard": []
};
categoriesList.forEach(element => keyBoard["inline_keyboard"].push(element));
sendText(id, "<b><u>❌ Choose which expense to delete: </u></b>", keyBoard)
}
/**
* @fn deleteAnExpense
* @brief Delete an expense
*/
function deleteAnExpense(id, callback_query)
{
// Google Sheet
var expenseSheet = SpreadsheetApp.openById(ssId);
var expensesSheet = expenseSheet.getSheetByName("Expenses");
try
{
var data = callback_query.slice("deleteExpense".length);
var dataSplitted = data.split("_");
var line = dataSplitted[0];
var date = dataSplitted[1];
var cost = dataSplitted[2];
if (true
&& (Date.parse(expensesSheet.getRange(line, 1).getValue()) == date)
&& (expensesSheet.getRange(line, 3).getValue() == cost)
)
{
// Clear line
expensesSheet.deleteRow(line);
sendText(id, "✔️ Expense deleted correctly")
}
}
catch (e)
{
sendText(id, "❌ An error occurred: " + e);
}
sendMainMenuKeyboard(id);
}
/**
* @fn checkUserAuthentication
* @brief Check user authentication
*/
function checkUserAuthentication(id)
{
// Google Sheet
var googleSheet = SpreadsheetApp.openById(ssId);
var authenticatedUsersSheet = googleSheet.getSheetByName("Authenticated Users");
var lr = authenticatedUsersSheet.getDataRange().getLastRow();
for (var i = lr; i > 1; i--)
{
var userId = authenticatedUsersSheet.getRange(i, 1).getValue();
if (userId == id)
return true;
}
sendText(id, "⛔ You're not authorized to interact with this bot!");
return false;
}
/*!
* @fn doPost
* @brief Webhook Callback
*/
function doPost(e)
{
// Log Message
logMessage(e);
try
{
// Telegram Message
var contents = JSON.parse(e.postData.contents);
// Is it a telegram button callback?
if (contents.callback_query)
{
// Telegram button callback
var id_callback = contents.callback_query.from.id;
var data = contents.callback_query.data;
if (!checkUserAuthentication(id_callback))
return;
// Delete last message
deleteMessage(id_callback, contents.callback_query.message.message_id)
if (data == 'totalExpenses')
{
sendTotalExpensesList(id_callback);
clearLogs();
}
else if (data == 'last5Expenses')
{
sendLast5Expenses(id_callback);
clearLogs();
}
else if (data == 'addNewExpenseStep1Date')
{
addNewExpenseStep1Date(id_callback);
}
else if (data.includes("newExpDate"))
{
var dateChosen = new Date(parseInt(data.slice("newExpDate".length)));
dateChosen = dateChosen.toLocaleDateString(locale, {timeZone: timeZone});
sendText(id_callback, "<b>🕰️ Date: " + dateChosen + "</b>");
addNewExpenseStep2Category(id_callback);
}
else if (data.includes("category"))
{
sendText(id_callback, "<b>📋 Category: " + data.slice("category".length) + "</b>");
addNewExpenseStep3Description(id_callback);
}
else if (data == 'detailsNotAvailable')
{
addExpenseToSpreadsheet(id_callback);
}
else if (data == 'deleteAnExpense')
{
deleteAnExpenseChoose(id_callback);
clearLogs();
}
else if (data.includes("deleteExpense"))
{
deleteAnExpense(id_callback, data);
clearLogs();
}
}
else if (contents.message)
{
// It is a normal message
var id_message = contents.message.chat.id;
var text = contents.message.text;
if (!checkUserAuthentication(id_message))
return;
if (!manageAddExpense(id_message, text))
{
sendMainMenuKeyboard(id_message);
}
}
}
catch (e)
{
sendText(adminID, JSON.stringify(e, null, 4));
}
}