-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattendancebot.js
More file actions
707 lines (622 loc) Β· 26.2 KB
/
attendancebot.js
File metadata and controls
707 lines (622 loc) Β· 26.2 KB
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
698
699
700
701
702
703
704
705
706
707
const TOKEN = '7950091328:AAGr2z8bH4JXTSwiFOYz0yup80gXvcZmGP4';
const ATTENDANCE_SHEET_NAME = 'ACC_Attendance';
const SETTINGS_SHEET_NAME = 'Group_Settings';
const TELEGRAM_API = `https://api.telegram.org/bot${TOKEN}`;
const ONE_HOUR_IN_SECONDS = 3600;
// CRC32 Table for hash generation
const CRC32_TABLE = (() => {
let c;
const table = [];
for (let n = 0; n < 256; n++) {
c = n;
for (let k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
})();
// ===== MAIN FUNCTIONS =====
function doPost(e) {
try {
const update = JSON.parse(e.postData.contents);
if (update.message?.text === '/start' || update.message?.text === '/start@alp_attendance_bot') {
handleStartCommand(update.message);
}
else if (update.message?.text === '/info' || update.message?.text === '/info@alp_attendance_bot') {
handleStartCommand(update.message);
}
else if (update.message?.text === '/startsign' || update.message?.text === '/startsign@alp_attendance_bot') {
handleStartSignCommand(update.message);
}
else if (update.message?.text === '/startsignout' || update.message?.text === '/startsignout@alp_attendance_bot') {
handleStartSignCommand(update.message);
}
else if (update.message?.text === '/timetable' || update.message?.text === '/timetable@alp_attendance_bot') {
handleStartCommand(update.message);
}
else if (update.callback_query) {
if (update.callback_query.data === 'sign_in') {
handleSignIn(update.callback_query);
}
else if (update.callback_query.data === 'sign_out') {
handleSignOut(update.callback_query);
}
}
} catch (e) {
console.error("Error in doPost:", e);
}
}
function handleStartSignCommand(msg) {
const chatId = msg.chat.id;
const userId = msg.from.id;
const settings = getGroupSettings(chatId);
if (!settings) {
sendMessage(chatId, "β This group is not configured for attendance tracking.");
deleteMessage(chatId, msg.message_id);
return;
}
// Check if user is a teacher
if (!settings.teacherIds.includes(userId.toString())) {
let replyMessage = sendMessage(chatId, "β Only teachers can start attendance!");
deleteMessage(chatId, msg.message_id);
deleteMessage(chatId, replyMessage.message_id);
return;
}
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
const fullName = getUserFullName(msg.from);
const cache = CacheService.getScriptCache();
// Calculate end times based on settings
const signInEndTime = addMinutes(currentTime, settings.signInDelay);
const signOutEndTime = addMinutes(currentTime, settings.signOutDelay);
// Check if the message contains "out" to start sign-out instead
if (msg?.text === '/startsignout' || msg?.text === '/startsignout@alp_attendance_bot') {
cache.put(`manual_sign_active_${chatId}`, "out", ONE_HOUR_IN_SECONDS);
cache.put(`manual_signout_end_${chatId}`, signOutEndTime, ONE_HOUR_IN_SECONDS);
sendMessage(chatId,
`π’ @everyone\n` +
`πͺ <b>MANUAL SIGN-OUT STARTED</b> by teacher ${fullName}\n\n` +
`π Sign-out will be open for ${settings.signOutDelay} minutes!\n` +
`Click below to sign out:`,
[[{ text: "π Sign Out", callback_data: "sign_out" }]]
);
deleteMessage(chatId, msg.message_id);
return;
}
// Store in cache what we're starting (sign-in or sign-out)
cache.put(`manual_sign_active_${chatId}`, "in", ONE_HOUR_IN_SECONDS); // 6 hours
cache.put(`manual_sign_end_${chatId}`, signInEndTime, ONE_HOUR_IN_SECONDS);
sendMessage(chatId,
`π’ @everyone\n` +
`β
<b>MANUAL SIGN-IN STARTED</b> by teacher ${fullName}\n\n` +
`π Sign-in will be open for ${settings.signInDelay} minutes!\n` +
`Click below to sign in:`,
[[{ text: "π Sign In", callback_data: "sign_in" }]]
);
// Delete teacher's command
deleteMessage(chatId, msg.message_id);
}
// ===== CORE FUNCTIONALITY =====
function handleStartCommand(msg) {
const chatId = msg.chat.id;
const settings = getGroupSettings(chatId);
if (!settings) {
sendMessage(chatId, "β Sorry This Group/Chat is not configured for attendance tracking.");
return;
}
if (msg?.text === '/info' || msg?.text === '/info@alp_attendance_bot') {
const cache = CacheService.getScriptCache();
const lastInfoMsgId = cache.get(`last_info_${chatId}`);
// Delete the bot's previous /info response (if exists)
if (lastInfoMsgId) {
deleteMessage(chatId, lastInfoMsgId);
Utilities.sleep(500); // Short delay to ensure deletion
}
deleteMessage(chatId, msg.message_id);
let infomsg = `π <b>Hello amazing students!</b>\n\n` +
`Iβm <b>ALP Attendance Bot</b>, your smart assistant for keeping track of class attendance πβ¨\n\n` +
`Iβm here to help you easily sign in and sign out during your lessons - no stress, no paperwork!\n` +
`Just follow the steps below:\n\n` +
`β
<b>To Sign In:</b>\n` +
`Click the button Iβll send when class starts (within the first few minutes β°).\n` +
`Youβll see a <b>π Sign In</b> button - just tap it!\n\n` +
`β
<b>To Sign Out:</b>\n` +
`At the end of class, Iβll send another message with a <b>π Sign Out</b> button.\n` +
`Tap it during the sign-out window to complete your attendance.\n\n` +
`β οΈ <b>Note:</b>\n` +
`β’ You can only sign in <i>during the allowed sign-in time</i>.\n` +
`β’ You can only sign out <i>at the end of the class</i>, during the last few minutes.\n` +
`β’ If you miss any step, your attendance wonβt count for the day π\n\n` +
`π‘ <b>Need help?</b>\n` +
`Just type <code>/info</code> and Iβll guide you again!\n\n` +
`π€ <b>Availabe Commands:</b> \n` +
`β’ <code>/info</code>, Guide.\n` +
`β’ <code>/start</code>, Start The Bot.\n` +
`β’ <code>/timetable</code>, Timetable.\n` +
`β’ <code>/startsign</code>, (Only Teachers) \n` +
`β’ <code>/startsignout</code>, (Only Teachers)\n\n` +
/*
/start - Start The Bot
/info - Guide
/timetable - View Class Timetable
/startsign - Start Manual Sign-In (Only Teachers)
/startsignout - Start Manual Sign-Out (Only Teachers)
*/
`Letβs have a great learning experience together π\n` +
`Sit tight and Iβll let you know when itβs time to take action π\n\n` +
`- With care,\n` +
`<b>ALP Attendance Bot π€π</b>\n\n` +
`π© <b>For more info or assistance:</b> <a href="https://t.me/Thedevdanalmag">Dev. Abdullmajeed</a>`;
const sentMessage = sendMessage(chatId, infomsg);
// Store the new message_id in cache (expires in 6 hours)
if (sentMessage && sentMessage.message_id) {
cache.put(`last_info_${chatId}`, sentMessage.message_id.toString(), ONE_HOUR_IN_SECONDS); // 6h cache
}
return;
}
if (msg?.text === '/timetable' || msg?.text === '/timetable@alp_attendance_bot') {
const cache = CacheService.getScriptCache();
const lastTimetableMsgId = cache.get(`last_timetable_${chatId}`);
// Delete the bot's previous /timetable response (if exists)
if (lastTimetableMsgId) {
deleteMessage(chatId, lastTimetableMsgId);
Utilities.sleep(500); // Short delay to ensure deletion
}
deleteMessage(chatId, msg.message_id);
const timetableMsg = getFormattedTimetable(settings);
const senttMessage = sendMessage(chatId, timetableMsg);
// Store the new message_id in cache (expires in 6 hours)
if (senttMessage && senttMessage.message_id) {
cache.put(`last_timetable_${chatId}`, senttMessage.message_id.toString(), ONE_HOUR_IN_SECONDS); // 6h cache
}
return;
}
// If not info or timetable, proceed with normal start command
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
const fullName = getUserFullName(msg.from);
// Calculate time windows
const signInEndTime = addMinutes(settings.startTime, settings.signInDelay);
const signOutStartTime = subtractMinutes(settings.endTime, settings.signOutDelay);
const cache = CacheService.getScriptCache();
const manualActive = cache.get(`manual_sign_active_${chatId}`);
const manualEndTime = cache.get(`manual_sign_end_${chatId}`);
const laststartres = cache.get(`last_start_res_${chatId}`);
console.log("Last cached message ID:", laststartres); // Debug cache
// Delete bot's previous response (if exists)
if (laststartres) {
console.log("Attempting to delete previous message:", laststartres);
deleteMessage(chatId, laststartres);
Utilities.sleep(500); // Ensure deletion completes
}
// Delete user's /start command (optional)
try {
deleteMessage(chatId, msg.message_id);
} catch (e) {
console.error("Failed to delete user message:", e);
}
let message = `π ${fullName} (${settings.course})\n\n`;
if (manualActive === "in") {
if (compareTimes(currentTime, manualEndTime) > 0) {
const replyMessage = sendMessage(chatId, "β³ Manual sign-in period has ended!");
deleteMessage(chatId, msg.message_id);
if (replyMessage && replyMessage.message_id) {
cache.put(`last_start_res_${chatId}`, replyMessage.message_id.toString(), ONE_HOUR_IN_SECONDS);
}
return;
}
message += `β
<b>MANUAL SIGN-IN ACTIVE</b>\n\n` +
`π Sign-in is open for ${settings.signInDelay} minutes!\n` +
`Click below to sign in:`;
const replyMessage = sendMessage(chatId, message, [[{ text: "π Sign In", callback_data: "sign_in" }]]);
if (replyMessage && replyMessage.message_id) {
cache.put(`last_start_res_${chatId}`, replyMessage.message_id.toString(), ONE_HOUR_IN_SECONDS);
}
return;
}
else if (manualActive === "out") {
if (compareTimes(currentTime, manualEndTime) > 0) {
const replyMessage = sendMessage(chatId, "β³ Manual sign-out period has ended!");
deleteMessage(chatId, msg.message_id);
if (replyMessage && replyMessage.message_id) {
cache.put(`last_start_res_${chatId}`, replyMessage.message_id.toString(), ONE_HOUR_IN_SECONDS);
}
return;
}
message += `πͺ <b>MANUAL SIGN-OUT ACTIVE</b>\n\n` +
`π Sign-out is open for ${settings.signOutDelay} minutes!\n` +
`Click below to sign out:`;
const replyMessage = sendMessage(chatId, message, [
[{ text: "π Sign Out", callback_data: "sign_out" }]
]);
if (replyMessage && replyMessage.message_id) {
cache.put(`last_start_res_${chatId}`, replyMessage.message_id.toString(), ONE_HOUR_IN_SECONDS);
}
return;
}
// Default message when no manual activity is active
message += `π <b>ATTENDANCE NOT ACTIVE</b>\n\n` +
`β° Class starts at ${removeHash(settings.startTime)}\n` +
`π΄ Class ends at ${removeHash(settings.endTime)}\n\n` +
`β
Sign-In opens for ${settings.signInDelay} minutes \n` +
`πͺ Sign-Out opens for ${settings.signOutDelay} minutes \n` +
`π
Class Days: ${getDayEmojis(settings.days)}\n\n` +
`π¨βπ« Teacher: ${settings.teacher}\n\n` +
`Available Commands:\n` +
`β’ /start - Start the Bot\n` +
`β’ /info - Get Help and Info\n` +
`β’ /startsign - Start Manual Sign-In (Only Teachers)\n` +
`β’ /startsignout - Start Manual Sign-Out (Only Teachers)\n` +
`β’ /timetable - View Class Timetable\n\n` +
`β οΈ Note: You can only sign in during the allowed sign-in time and sign out at the end of class.`;
const replyMessage = sendMessage(chatId, message);
if (replyMessage && replyMessage.message_id) {
cache.put(`last_start_res_${chatId}`, replyMessage.message_id.toString(), ONE_HOUR_IN_SECONDS);
}
}
function handleSignIn(callback) {
const user = callback.from;
const chatId = callback.message.chat.id;
const messageId = callback.message.message_id;
const settings = getGroupSettings(chatId);
if (!settings) {
answerCallbackWithAlert(callback.id, "β Group configuration error");
deleteMessage(chatId, messageId);
return;
}
const cache = CacheService.getScriptCache();
const manualActive = cache.get(`manual_sign_active_${chatId} `);
const manualEndTime = cache.get(`manual_sign_end_${chatId} `);
// If in manual mode, check if still within allowed time
if (manualActive === "in") {
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
if (compareTimes(currentTime, manualEndTime) > 0) {
answerCallbackWithAlert(callback.id, "β³ Manual sign-in period has ended!");
return;
}
// Skip normal time checks if in manual mode
}
// Check if attendance is active
if (!manualActive) {
answerCallbackWithAlert(callback.id, "β³ Attendance hasn't been started yet by the teacher.");
return;
}
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
const today = formatDateForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "dd-MM-yyyy"));
const fullName = getUserFullName(user);
const signInEndTime = addMinutes(settings.startTime, settings.signInDelay);
// Time validation
// if (compareTimes(currentTime, settings.startTime) < 0 || compareTimes(currentTime, signInEndTime) > 0) {
// answerCallbackWithAlert(callback.id, `β ${ fullName }, Sign - In closed!(Only first ${ settings.signInDelay } min)`);
// deleteMessage(chatId, messageId);
// return;
// }
// Check for existing sign-in
const existingRecord = findAttendanceRecord(user.id, today, chatId);
if (existingRecord && existingRecord.signedInTime) {
answerCallbackWithAlert(callback.id, `β οΈ ${fullName}, You already signed in today at ${removeHash(existingRecord.signedInTime)} !`);
return;
}
// Record sign-in
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ATTENDANCE_SHEET_NAME);
const timestamp = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss"));
if (existingRecord) {
// Update existing incomplete record
sheet.getRange(existingRecord.row, 1).setValue(timestamp);
sheet.getRange(existingRecord.row, 8).setValue(currentTime);
sheet.getRange(existingRecord.row, 10).setValue("Signed In");
} else {
// Create new record
sheet.appendRow([
timestamp, // Timestamp
fullName, // Name
user.username || "N/A", // Username
user.id, // Telegram ID
today, // Date
settings.course, // Course
chatId, // Group ID
currentTime, // Signed In Time
"", // Sign Out Time (empty)
"Signed In", // Status
"" // Hash (empty)
]);
}
answerCallbackWithAlert(callback.id, `β
${fullName}, Sign - In recorded at ${removeHash(currentTime)} `);
}
function handleSignOut(callback) {
const user = callback.from;
const chatId = callback.message.chat.id;
const messageId = callback.message.message_id;
const settings = getGroupSettings(chatId);
if (!settings) {
answerCallbackWithAlert(callback.id, "β Group configuration error");
deleteMessage(chatId, messageId);
return;
}
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
const today = formatDateForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "dd-MM-yyyy"));
const fullName = getUserFullName(user);
const signOutStartTime = subtractMinutes(settings.endTime, settings.signOutDelay);
const cache = CacheService.getScriptCache();
const manualActive = cache.get(`manual_sign_active_${chatId} `);
const manualEndTime = cache.get(`manual_signout_end_${chatId} `);
// If in manual mode, check if still within allowed time
if (manualActive === "out") {
if (compareTimes(currentTime, manualEndTime) > 0) {
answerCallbackWithAlert(callback.id, "β³ Manual sign-in period has ended!");
return;
}
// Skip normal time checks if in manual mode
}
// Check if attendance is active
if (!manualActive) {
answerCallbackWithAlert(callback.id, "β³ Attendance hasn't been started yet by the teacher.");
return;
}
// Time validation
// if (compareTimes(currentTime, signOutStartTime) < 0 || compareTimes(currentTime, settings.endTime) > 0) {
// answerCallbackWithAlert(callback.id, `β ${ fullName }, Sign - Out not available yet!(Last ${ settings.signOutDelay } min)`);
// deleteMessage(chatId, messageId);
// return;
// }
// Find existing record
const existingRecord = findAttendanceRecord(user.id, today, chatId);
if (!existingRecord) {
answerCallbackWithAlert(callback.id, `β ${fullName}, You must sign in first!`);
// deleteMessage(chatId, messageId);
return;
}
if (existingRecord.signOutTime) {
answerCallbackWithAlert(callback.id, `β οΈ ${fullName}, You already signed out today at ${removeHash(existingRecord.signOutTime)} !`);
return;
}
// Generate hash and update record
const uniqueHash = generateAttendanceHash(user.id, today, chatId);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ATTENDANCE_SHEET_NAME);
sheet.getRange(existingRecord.row, 9).setValue(currentTime); // Sign Out Time
sheet.getRange(existingRecord.row, 10).setValue("Completed"); // Status
sheet.getRange(existingRecord.row, 11).setValue(uniqueHash); // Hash
answerCallbackWithAlert(callback.id, `β
${fullName}, Sign - Out recorded at ${removeHash(currentTime)} \nAttendance complete!`);
}
// ===== HELPER FUNCTIONS =====
function getGroupSettings(chatId) {
try {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SETTINGS_SHEET_NAME);
const data = sheet.getDataRange().getValues();
for (let i = 1; i < data.length; i++) {
const row = data[i];
if (row[4] == chatId) {
return {
course: row[0],
startTime: formatTimeForSheet(String(row[1])),
endTime: formatTimeForSheet(String(row[2])),
reminderTime: formatTimeForSheet(String(row[3])),
groupId: row[4],
signInDelay: parseInt(row[5]) || 5,
signOutDelay: parseInt(row[6]) || 5,
days: String(row[7]),
teacher: String(row[8]),
teacherIds: String(row[9]).split(',').map(id => id.trim()) // New column for teacher IDs
};
}
}
return null;
} catch (e) {
console.error("Error in getGroupSettings:", e);
return null;
}
}
function findAttendanceRecord(userId, date, groupId) {
try {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ATTENDANCE_SHEET_NAME);
const data = sheet.getDataRange().getValues();
for (let i = 1; i < data.length; i++) {
const row = data[i];
if (row[3] == userId && row[4] == date && row[6] == groupId) {
return {
row: i + 1,
signedInTime: row[7],
signOutTime: row[8],
status: row[9],
hash: row[10]
};
}
}
return null;
} catch (e) {
console.error("Error in findAttendanceRecord:", e);
return null;
}
}
function formatTimeForSheet(timeStr) {
return `#${timeStr.replace(/^#/, '')} `;
}
function formatDateForSheet(dateStr) {
return `#${dateStr.replace(/^#/, '')} `;
}
function removeHash(value) {
return String(value).replace(/^#/, '');
}
function generateAttendanceHash(userId, date, groupId) {
const uniqueString = `${userId}| ${removeHash(date)}| ${groupId} `;
return crc32(uniqueString).toString(16);
}
function crc32(str) {
let crc = 0 ^ (-1);
for (let i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
}
function compareTimes(time1, time2) {
const t1 = removeHash(time1).replace(/:/g, '');
const t2 = removeHash(time2).replace(/:/g, '');
return parseInt(t1) - parseInt(t2);
}
function addMinutes(timeStr, minutes) {
const [hours, mins] = removeHash(timeStr).split(':').map(Number);
const date = new Date();
date.setHours(hours, mins + minutes, 0, 0);
return formatTimeForSheet(Utilities.formatDate(date, Session.getScriptTimeZone(), "HH:mm"));
}
function subtractMinutes(timeStr, minutes) {
return addMinutes(timeStr, -minutes);
}
function getUserFullName(user) {
return `${user.first_name || ""} ${user.last_name || ""} `.trim();
}
function sendMessage(chatId, text, keyboard = null) {
try {
const payload = {
chat_id: chatId,
text: text,
parse_mode: "HTML"
};
if (keyboard) {
payload.reply_markup = JSON.stringify({ inline_keyboard: keyboard });
}
const response = UrlFetchApp.fetch(`${TELEGRAM_API}/sendMessage`, {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload)
});
const responseData = JSON.parse(response.getContentText());
return responseData.result; // Contains message_id
} catch (e) {
console.error("Error in sendMessage:", e);
return null;
}
}
function deleteMessage(chatId, messageId) {
try {
UrlFetchApp.fetch(`${TELEGRAM_API}/deleteMessage`, {
method: "post",
contentType: "application/json",
payload: JSON.stringify({
chat_id: chatId,
message_id: messageId
})
});
} catch (e) {
console.error("Error in deleteMessage:", e);
}
}
function answerCallbackWithAlert(callbackId, text) {
try {
UrlFetchApp.fetch(`${TELEGRAM_API}/answerCallbackQuery`, {
method: "post",
contentType: "application/json",
payload: JSON.stringify({
callback_query_id: callbackId,
text: text,
show_alert: true
})
});
} catch (e) {
console.error("Error in answerCallbackWithAlert:", e);
}
}
// ===== AUTOMATED REMINDERS =====
function sendDailyReminders() {
try {
const now = new Date();
const currentTime = formatTimeForSheet(Utilities.formatDate(now, Session.getScriptTimeZone(), "HH:mm"));
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SETTINGS_SHEET_NAME);
const groups = sheet.getDataRange().getValues();
for (let i = 1; i < groups.length; i++) {
const group = groups[i];
const settings = {
course: group[0],
startTime: formatTimeForSheet(String(group[1])),
endTime: formatTimeForSheet(String(group[2])),
reminderTime: formatTimeForSheet(String(group[3])),
groupId: group[4],
signInDelay: parseInt(group[5]) || 5,
signOutDelay: parseInt(group[6]) || 5,
days: String(group[7]),
teacher: String(group[8])
};
// testing(settings.groupId);
let classDays = settings.days;
let classDaysArray = classDays.split(",").map(day => day.trim());
const today = Utilities.formatDate(now, Session.getScriptTimeZone(), "EEEE");
if (!classDaysArray.includes(today)) {
Logger.log("No Class Today for group: " + settings.groupId);
continue; // Skip this group but continue with others
}
// // Send sign-out reminder at exact reminder time
if (removeHash(currentTime) === removeHash(settings.reminderTime)) {
let message = "π Good day, amazing students!\n\nToday is <b>" + today +
"</b>, and we have our scheduled class with " + settings.teacher + ".\n\n" +
"π <b>Class Time:</b> " + removeHash(settings.startTime) + "\n\n" +
"π <b>Teacher:</b> Please use /startattendance when ready to begin.\n" +
"Students, for Attendace please wait for the teacher to start attendance.";
sendMessage(settings.groupId, message);
}
// // Send sign-in reminder at exact start time
// if (removeHash(currentTime) === removeHash(settings.startTime)) {
// sendMessage(settings.groupId,
// `π’ @everyone (${settings.course})\n\n` +
// `β° Sign-In open for ${settings.signInDelay} minutes!\n` +
// `Click below to sign in:`,
// [[{ text: "π Sign In", callback_data: "sign_in" }]]
// );
// }
// // Send actual sign-out message at calculated time
// const signOutStartTime = subtractMinutes(settings.endTime, settings.signOutDelay);
// if (removeHash(currentTime) === removeHash(signOutStartTime)) {
// sendMessage(settings.groupId,
// `π’ @everyone (${settings.course})\n\n` +
// `β° Sign-Out open for ${settings.signOutDelay} minutes!\n` +
// `Click below to sign out:`,
// [[{ text: "π Sign Out", callback_data: "sign_out" }]]
// );
// }
}
} catch (e) {
console.error("Error in sendDailyReminders:", e);
}
}
function getFormattedTimetable(settings) {
const signOutStartTime = subtractMinutes(settings.endTime, settings.signOutDelay);
return `π
<b>${settings.course} Timetable</b> π
\n\n` +
`β° <b>Class Hours</b>\n` +
`π’ Start: ${removeHash(settings.startTime)}\n` +
`π΄ End: ${removeHash(settings.endTime)}\n\n` +
`π <b>Attendance Windows</b> \n\n` +
`β
Sign-In: First ${settings.signInDelay} mins after start\n` +
` β ${removeHash(settings.startTime)} - ${removeHash(addMinutes(settings.startTime, settings.signInDelay))}\n\n` +
`πͺ Sign-Out: Last ${settings.signOutDelay} mins before end\n` +
` β ${removeHash(signOutStartTime)} - ${removeHash(settings.endTime)}\n\n` +
`π
<b>Class Days</b> \n` +
`${getDayEmojis(settings.days)}\n\n` +
`π¨βπ« <b>Teacher</b> ${settings.teacher}\n` +
`βοΈ Use /startsign to begin attendance early`;
}
function getDayEmojis(daysString) {
const days = daysString.split(',').map(d => d.trim());
const dayEmojis = {
'Monday': 'π
Monday',
'Tuesday': 'π
Tuesday',
'Wednesday': 'π
Wednesday',
'Thursday': 'π
Thursday',
'Friday': 'π
Friday',
'Saturday': 'π
Saturday',
'Sunday': 'π
Sunday'
};
return days.map(day => dayEmojis[day] || day).join(' β’ ');
}
// ===== SETUP FUNCTIONS =====
function setWebhook() {
try {
const webhookUrl = ScriptApp.getService().getUrl();
const response = UrlFetchApp.fetch(`${TELEGRAM_API}/setWebhook?url=${webhookUrl}`);
console.log("Webhook setup response:", response.getContentText());
} catch (e) {
console.error("Error in setWebhook:", e);
}
}