forked from limyeechern/eusoff-mods-community
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
995 lines (868 loc) · 38.6 KB
/
main.py
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
import telegram
from telegram import *
from telegram.ext import *
import logging
import psycopg2 as pg2
import re
import os
import json
'''config'''
token = os.environ.get('BOT_TOKEN')
bot = Bot(os.environ.get('BOT_TOKEN'))
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
DB_URL = os.environ.get('DATABASE_URL')
replyKeyboardStandard = [['/mods', '/cancel', '/help', '/mymods'],
['/groupchatcreated', '/deletemod', '/addmod']]
replyKeyboardFaculties = [['Biz', 'Computing', 'CHS(AY21/22 Onwards)', 'Engineering'],
['FASS', 'Science', 'Law', 'Public Policy'],
['ISE', 'Music', 'Public Health', 'SDE']]
replyKeyboardModFaculties = [['Biz', 'Computing', 'CHS Mods', 'Engineering'],
['FASS', 'GE Mods', 'Law', 'Music'],
['Public Health', 'Public Policy'],
['Science', 'SDE', 'Others']]
moduleToFaculty = {}
facultyToCategory = {
'NUS Business School': 'Biz',
'Computing': 'Computing',
'College of Design and Engineering': 'Engineering',
'Arts and Social Science': 'FASS',
'SSH School of Public Health': 'Public Health',
'LKY School of Public Policy': 'Public Policy',
'Science': 'Science',
'Design and Environment': 'SDE',
'Law': 'Law',
'YST Conservatory of Music': 'Music'
}
# Opening JSON file
with open('module_data.json') as module_list:
modules_data = json.load(module_list)
for module_data in modules_data:
moduleToFaculty[module_data['moduleCode'].upper()] = module_data['faculty']
''''''''
class Account:
def __init__(
self,
username=None,
name=None,
roomnumber=None,
faculty=None,
course=None,
mods=None,
year=None,
chat_id=None):
if mods is None:
mods = {}
self.name = name
self.username = username
self.roomNumber = roomnumber
self.faculty = faculty
self.course = course
self.mods = mods
self.year = year
self.chat_id = chat_id
updater = Updater(token, use_context=True)
dispatcher = updater.dispatcher
print(Bot.get_me(bot))
''''commands'''
ROOMNUMBER, FACULTY, COURSE, YEAR, MODS1, MODS2, MODS3, MODS4, MODS5, MODS6, MODS7, MODS8 = range(
12)
selectionDict = {}
dictDict = {}
newAccountDict = {}
def input_id_into_selection_dict(username):
if username not in selectionDict:
selectionDict[username] = ''
def input_id_into_dict_dict(username):
if username not in dictDict:
dictDict[username] = {}
def input_id_into_newAccountDict(username):
if username not in newAccountDict:
newAccountDict[username] = Account()
def initialise_account(update: Update):
newAccount = newAccountDict[update.effective_chat.username]
conn = pg2.connect(DB_URL)
cur = conn.cursor()
insert_account = '''
INSERT INTO accounts(username,name,roomnumber,faculty,course,year,chat_id)
VALUES (%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (chat_id) DO NOTHING
'''
cur.execute(insert_account,
(newAccount.username, newAccount.name, newAccount.roomNumber, newAccount.faculty, newAccount.course,
newAccount.year, newAccount.chat_id))
for fac in newAccount.mods:
for mod in newAccount.mods[fac]:
insert_to_all_modules = '''
INSERT INTO all_modules(mod_name,faculty_id)
VALUES(%s,(SELECT faculty_id FROM faculties
WHERE faculty_name = %s))
ON CONFLICT (mod_name) DO NOTHING
'''
cur.execute(insert_to_all_modules, (mod, fac.lower()))
conn.commit()
for fac in newAccount.mods:
for mod in newAccount.mods[fac]:
insert_to_mods = '''
INSERT INTO mods(account_id,mod_id,faculty_id)
VALUES((SELECT id FROM accounts
WHERE username = %s),(SELECT mod_id FROM all_modules
WHERE mod_name = %s), (SELECT faculty_id FROM all_modules
WHERE mod_name = %s))
'''
cur.execute(insert_to_mods, (newAccount.username, mod, mod))
conn.commit()
for fac in newAccount.mods:
for mod in newAccount.mods[fac]:
get_chat_id = '''
SELECT chat_id FROM accounts
INNER JOIN mods
ON accounts.id = mods.account_id
WHERE mods.mod_id = (SELECT mod_id FROM all_modules
WHERE mod_name = %s)
'''
cur.execute(get_chat_id, (mod,))
data = cur.fetchall()
for chat_id in data:
if chat_id[0] == update.effective_message.chat_id:
continue
else:
chat_id = chat_id[0]
try:
bot.send_message(chat_id=chat_id,
text="Someone is now taking " + mod + "! Run /mods to check")
except:
continue
conn.close()
def start(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_newAccountDict(update.effective_chat.username)
user = update.message.from_user
logger.info("User %s started the bot", user.username)
reply_keyboard = [['/register']]
update.message.reply_text(
'Welcome to Eusoff Mods, this is a bot to identify a community of Eusoffians taking the same mods, such as GE '
'mods, as well as the group chats created, firstly, please register up to 8 mods with /register. Credits to @chernanigans for creating this bot.',
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
def register(update: Update, _: CallbackContext) -> int:
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
logger.info("User %s is registering", user.username)
data = update.effective_chat
username = data['username']
name = data['first_name']
newAccount.username = username
newAccount.name = name
newAccount.chat_id = update.effective_message.chat_id
update.message.reply_text(
'Please key in your ROOM NUMBER (for authentication purposes only, will not be disclosed) \nIf you make a '
'mistake anytime, restart by typing /cancel. \nYou can edit your mods via /deletemod or /addmod anytime after '
'registration.')
print(newAccountDict)
return ROOMNUMBER
def roomnumber(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
trueOrFalse = checkvalidroomnumber(update.message.text.upper(), update)
if trueOrFalse is False:
return ROOMNUMBER
logger.info("Room Number of %s: %s", user.username, update.message.text.upper())
newAccount.roomNumber = update.message.text.upper()
update.message.reply_text(
'Please indicate your faculty',
reply_markup=ReplyKeyboardMarkup(replyKeyboardFaculties, one_time_keyboard=True))
return FACULTY
def faculty(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
trueOrFalse = checkvalidfaculty(update.message.text.upper(), update)
if trueOrFalse is False:
return FACULTY
logger.info("Faculty of %s: %s", user.username, update.message.text)
newAccount.faculty = update.message.text
update.message.reply_text(
'Please indicate your major',
reply_markup=ReplyKeyboardRemove())
return COURSE
def course(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
logger.info("Course of %s: %s", user.username, update.message.text.upper())
newAccount.course = update.message.text.upper()
yearList = ["Year 1", "Year 2", "Year 3", "Year 4"]
keyboard = []
for i in yearList:
keyboard.append([InlineKeyboardButton(i, callback_data=i)])
reply_markup = InlineKeyboardMarkup(keyboard)
update.effective_message.reply_text('Please select your year', reply_markup=reply_markup)
return YEAR
def year(update: Update, _: CallbackContext):
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
year = str(update.callback_query.data)
query = update.callback_query
query.edit_message_text(text=f"Selected option: {query.data}")
newAccount.year = year
update.effective_message.reply_text(
'Please indicate the name of your first mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS1
def mods1(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS1
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your second mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS2
def mods2(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS2
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your third mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS3
def mods3(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS3
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your fourth mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS4
def mods4(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS4
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your fifth mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS5
def mods5(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS5
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your sixth mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS6
def mods6(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS6
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your seventh mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS7
def mods7(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS7
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'Please indicate the name of your eighth mod e.g. CS1010S or /done when you have enumerated all your courses '
'or /back to restart.',
reply_markup=ReplyKeyboardRemove())
return MODS8
def mods8(update: Update, _: CallbackContext) -> int:
input_id_into_newAccountDict(update.effective_chat.username)
newAccount = newAccountDict[update.effective_chat.username]
user = update.message.from_user
tempMod = update.message.text.upper()
tempMod = tempMod.replace(" ", "")
tempFaculty = ''
trueOrFalseMod = checkvalidmod(tempMod, update)
if trueOrFalseMod is False:
return MODS8
else:
tempFaculty = convertmodtofaculty(tempMod, update)
selectionDict[update.effective_chat.username] = tempFaculty
if tempFaculty not in newAccount.mods:
newAccount.mods[tempFaculty] = []
newAccount.mods[tempFaculty].append(update.message.text.upper())
update.message.reply_text(
'This is the last mod you can input, please type /done',
reply_markup=ReplyKeyboardRemove())
def done(update: Update, _: CallbackContext) -> int:
input_id_into_selection_dict(update.effective_chat.username)
user = update.message.from_user
update.message.reply_text(
'Your data is being stored in the system, this may take a while')
initialise_account(update)
update.message.reply_text(
'Your data has been stored into the system, please type /mods and follow instructions to find people who are '
'taking the same '
'mods as you do', reply_markup=ReplyKeyboardMarkup(replyKeyboardStandard, one_time_keyboard=False))
logger.info("%s has initialised their account", user.username)
return ConversationHandler.END
def cancel(update: Update, _: CallbackContext) -> int:
input_id_into_selection_dict(update.effective_chat.username)
user = update.message.from_user
if update.effective_chat.username in newAccountDict:
del newAccountDict[update.effective_chat.username]
logger.info("User %s canceled the conversation.", user.username)
update.message.reply_text(
'Cancelled, you may run another command \n /register to register \n /mods to check mods \n /groupchatcreated '
'to insert groupchat link', reply_markup=ReplyKeyboardMarkup(replyKeyboardStandard, one_time_keyboard=False)
)
print(newAccountDict)
return ConversationHandler.END
def back(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
user = update.message.from_user
if update.effective_chat.username in newAccountDict:
newAccountDict[update.effective_chat.username].mods = {}
update.message.reply_text(
"Please restart module registration from the first module. If you are prone to errors, just register for one mod first and subsequently add modules individually."
)
update.effective_message.reply_text(
'Please indicate the faculty of your first MOD, e.g. "FASS" for PL1101E, "Science" for MA1101R, "GE Mods" for '
'GER1000, "Biz" for ACC1002 etc. Please check and input the correct faculty and /back whenever you make a '
'mistake.',
reply_markup=ReplyKeyboardMarkup(replyKeyboardModFaculties, one_time_keyboard=True))
return MODS1_F
def button(update: Update, _: CallbackContext) -> None:
query = update.callback_query
query.answer()
query.edit_message_text(text=f"Selected option: {query.data}")
GETFACULTIES, GETMODS, LINK = range(3)
tempDict = {}
def mods(update: Update, _: CallbackContext) -> None:
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_dict_dict(update.effective_chat.username)
isRegisteredAccount = checkregisteredaccount(update.effective_message.chat_id, update)
if isRegisteredAccount is False:
return
user = update.message.from_user
logger.info("User %s has run /mods", user.username)
conn = pg2.connect(DB_URL)
cur = conn.cursor()
getFaculty = '''
SELECT faculty_name, mod_name FROM all_modules
INNER JOIN faculties
ON all_modules.faculty_id = faculties.faculty_id
'''
cur.execute(getFaculty)
data = cur.fetchall()
faculty = []
tempDict = dictDict[update.effective_chat.username]
tempDict.clear()
for key, value in data:
if key.title() not in faculty:
faculty.append(key.title())
if key.title() not in tempDict:
tempDict[key.title()] = []
tempDict[key.title()].append(value)
faculty.sort()
keyboard = []
for i in faculty:
keyboard.append([InlineKeyboardButton(i, callback_data=str(i))])
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose the faculty:', reply_markup=reply_markup)
return GETFACULTIES
def getfaculties(update: Update, _: CallbackContext) -> int:
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_dict_dict(update.effective_chat.username)
query = update.callback_query
query.edit_message_text(text=f"Selected option: {query.data}")
tempDict = dictDict[update.effective_chat.username]
tempFacultyChosen = query.data
mods = tempDict[tempFacultyChosen]
mods.sort()
keyboard = []
for i in range(0, len(mods), 2):
try:
keyboard.append([InlineKeyboardButton(mods[i], callback_data=mods[i]), InlineKeyboardButton(mods[i + 1], callback_data=mods[i + 1])])
except Exception:
keyboard.append([InlineKeyboardButton(mods[i], callback_data=mods[i])])
reply_markup = InlineKeyboardMarkup(keyboard)
update.effective_message.reply_text('Please choose the module:', reply_markup=reply_markup)
return GETMODS
def getmods(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
update.effective_message.reply_text('Fetching data from database, may take a while...')
modChosen = str(update.callback_query.data)
query = update.callback_query
query.edit_message_text(text=f"Selected option: {query.data}")
conn = pg2.connect(DB_URL)
cur = conn.cursor()
getNameList = '''
SELECT username FROM mods
INNER JOIN accounts
ON mods.account_id = accounts.id
AND
mod_id = (SELECT mod_id FROM all_modules
WHERE mod_name = %s)
'''
cur.execute(getNameList, (modChosen,))
data = cur.fetchall()
getLink = '''
SELECT link FROM all_modules
WHERE mod_name = %s
'''
cur.execute(getLink, (modChosen,))
tempLink = cur.fetchone()
modLink = ''
for link in tempLink:
modLink = link
if modLink is not None:
namelist = 'Usernames of Eusoffians taking' + ' ' + modChosen + '\n' + modLink + '\n'
else:
namelist = 'Usernames of Eusoffians taking' + ' ' + modChosen + '\n' + 'No groupchat created yet \n/groupchatcreated to add groupchat ' \
'link' + '\n'
for i in data:
namelist += ('@' + i[0] + '\n')
update.effective_message.reply_text(namelist)
return ConversationHandler.END
def groupchatcreated(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
user = update.effective_message.from_user
logger.info("User %s has run /groupchatcreated", user.username)
modChosen = str(update.callback_query.data)
tempModChosen = modChosen
selectionDict[update.effective_chat.username] = tempModChosen
query = update.callback_query
query.edit_message_text(text=f"Selected option: {query.data}")
update.effective_message.reply_text('Please copy and paste the group link here.')
return LINK
def link(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
tempModChosen = selectionDict[update.effective_chat.username]
linkSubmitted = update.message.text
user = update.effective_message.from_user
logger.info("User %s has added the link of %s", user.username, linkSubmitted)
accountUsername = update.effective_chat.username
conn = pg2.connect(DB_URL)
cur = conn.cursor()
createLink = '''
UPDATE all_modules
SET link = %s
,link_sender = %s
WHERE mod_name = %s
'''
cur.execute(createLink, (linkSubmitted, str(accountUsername), tempModChosen))
conn.commit()
conn.close()
update.effective_message.reply_text('Link has been added, /mods to check')
return ConversationHandler.END
def delete_account(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
isRegisteredAccount = checkregisteredaccount(update.effective_message.chat_id, update)
if isRegisteredAccount is False:
return
user = update.message.from_user
logger.info("User %s has deleted account", user.username)
username = update.effective_chat.username
conn = pg2.connect(DB_URL)
cur = conn.cursor()
query = '''
DELETE FROM mods
WHERE mods.account_id = (SELECT id
FROM accounts
WHERE accounts.username = %s)
'''
cur.execute(query, (username,))
conn.commit()
conn.close()
update.effective_message.reply_text('Account has been deleted, please complete registration again if you wish to '
'continue using the bot. \n/register')
CHOOSEMODULE = range(1)
def deletemod(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_dict_dict(update.effective_chat.username)
isRegisteredAccount = checkregisteredaccount(update.effective_message.chat_id, update)
if isRegisteredAccount is False:
return
user = update.message.from_user
logger.info("User %s has run /deletemod", user.username)
username = update.effective_chat.username
conn = pg2.connect(DB_URL)
cur = conn.cursor()
query = '''
SELECT mod_name, mods.mod_id, accounts.id FROM mods
INNER JOIN accounts ON mods.account_id = accounts.id
INNER JOIN all_modules ON all_modules.mod_id = mods.mod_id
WHERE username = %s
'''
cur.execute(query, (username,))
modules = cur.fetchall()
moduleDict = dictDict[update.effective_chat.username]
moduleDict.clear()
for i, j, k in modules:
moduleDict[i] = j
accountId = k
selectionDict[update.effective_chat.username] = accountId
keyboard = []
for i in moduleDict:
keyboard.append([InlineKeyboardButton(i, callback_data=i)])
reply_markup = InlineKeyboardMarkup(keyboard)
update.effective_message.reply_text('Please choose the module you wish to delete', reply_markup=reply_markup)
return CHOOSEMODULE
def choosemodule(update, context):
input_id_into_selection_dict(update.effective_chat.username)
input_id_into_dict_dict(update.effective_chat.username)
modChosen = str(update.callback_query.data)
query = update.callback_query
query.edit_message_text(text=f"Selected option: {query.data}")
moduleDict = dictDict[update.effective_chat.username]
accountId = selectionDict[update.effective_chat.username]
modId = moduleDict[modChosen]
conn = pg2.connect(DB_URL)
cur = conn.cursor()
query = '''
DELETE FROM mods
WHERE mods.mod_id = %s
AND account_id = %s
'''
cur.execute(query, (modId, accountId))
conn.commit()
conn.close()
moduleDict.clear()
update.effective_message.reply_text('Module has been deleted from your account')
return ConversationHandler.END
STATEMODULE = range(1)
def add_module(update, context):
isRegisteredAccount = checkregisteredaccount(update.effective_message.chat_id, update)
if isRegisteredAccount is False:
return
input_id_into_selection_dict(update.effective_chat.username)
user = update.message.from_user
logger.info("User %s has run /addmod", user.username)
update.message.reply_text(
'Please indicate the name of your mod e.g. CS1010S',
reply_markup=ReplyKeyboardRemove())
return STATEMODULE
def statemodule(update: Update, _: CallbackContext):
input_id_into_selection_dict(update.effective_chat.username)
module = update.message.text.upper()
module = module.replace(" ", "")
user = update.effective_chat.username
trueOrFalseMod = checkvalidmod(update.message.text.upper(), update)
if trueOrFalseMod is False:
return STATEMODULE
tempFaculty = convertmodtofaculty(module, update)
conn = pg2.connect(DB_URL)
cur = conn.cursor()
insertToAllModules = '''
INSERT INTO all_modules(mod_name,faculty_id)
VALUES(%s,(SELECT faculty_id FROM faculties
WHERE faculty_name = %s))
ON CONFLICT (mod_name) DO NOTHING
'''
cur.execute(insertToAllModules, (module, tempFaculty.lower()))
query = '''
INSERT INTO mods(account_id,mod_id,faculty_id)
VALUES((SELECT id FROM accounts
WHERE username = %s),
(SELECT mod_id FROM all_modules
WHERE mod_name = %s),
(SELECT faculty_id FROM all_modules
WHERE mod_name = %s))
'''
cur.execute(query, (user, module, module))
update.message.reply_text(
'Your data is being stored in the system, this may take a while')
conn.commit()
get_chat_id = '''
SELECT chat_id FROM accounts
INNER JOIN mods
ON accounts.id = mods.account_id
WHERE mods.mod_id = (SELECT mod_id FROM all_modules
WHERE mod_name = %s)
'''
cur.execute(get_chat_id, (module,))
data = cur.fetchall()
for chat_id in data:
if chat_id[0] == update.effective_message.chat_id:
continue
else:
chat_id = chat_id[0]
try:
bot.send_message(chat_id=chat_id,
text="Someone is now taking " + module + "! Run /mods to check")
except:
continue
update.message.reply_text(
'Your data has been stored into the system, please type /addmod to add another module',
reply_markup=ReplyKeyboardMarkup(replyKeyboardStandard, one_time_keyboard=False))
return ConversationHandler.END
def help(update, context):
user = update.message.from_user
replyKeyboardStandard = [['/mods', '/cancel', '/help', '/mymods'],
['/groupchatcreated', '/deletemod', '/addmod']]
logger.info("User %s has run /help", user.username)
update.message.reply_text("/start - Register with your room, faculty, mods "
"etc \n/done - Run after you are done entering all "
"your mods \n/cancel - Cancel to type another "
"command \n/mods - Obtain list of people studying "
"the particular mod \n/mymods- View your mods \n/groupchatcreated - Run if "
"you have created a group chat for a mod "
"\n/addmod - Add additional mod \n/deletemod - Delete mods that are wrongly added "
"\n/deleteaccount - Deletes your account \nPM "
"@amadeus_chi for any help",
reply_markup=ReplyKeyboardMarkup(replyKeyboardStandard, one_time_keyboard=False))
def mymods(update: Update, _: CallbackContext):
user = update.message.from_user
logger.info("User %s has run /mymods to check mods", user.username)
isRegisteredAccount = checkregisteredaccount(update.effective_message.chat_id, update)
if isRegisteredAccount is False:
return
input_id_into_selection_dict(update.effective_chat.username)
user = update.effective_chat.username
conn = pg2.connect(DB_URL)
cur = conn.cursor()
getMyMods = '''
select mod_name from mods
inner join all_modules
on mods.mod_id = all_modules.mod_id
WHERE mods.account_id = (SELECT id
FROM accounts
WHERE accounts.username = %s)
'''
cur.execute(getMyMods, (user,))
data = cur.fetchall()
mods = "The mods that you are taking this semester are \n"
for i in sorted(data):
mods += i[0] + '\n'
update.message.reply_text(
mods,
reply_markup=ReplyKeyboardMarkup(replyKeyboardStandard, one_time_keyboard=False))
return ConversationHandler.END
def unknown(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, something cropped up. Please "
"type /cancel to restart this.")
def checkvalidfaculty(faculty, update):
validInput = ['BIZ', 'COMPUTING', 'CHS MODS', 'GE MODS', 'ENGINEERING', 'FASS', 'SCIENCE', 'LAW', 'PUBLIC POLICY',
'MUSIC', 'PUBLIC HEALTH', 'SDE', 'CHS(AY21/22 ONWARDS)', 'OTHERS']
if faculty not in validInput:
bot.send_message(chat_id=update.effective_chat.id,
text="It appears that you have inputted an invalid faculty, please only select faculty from "
"the on-screen keyboard below.")
return False
return True
def checkvalidmod(mod, update):
if mod not in moduleToFaculty:
bot.send_message(chat_id=update.effective_chat.id,
text="It appears that you have inputted an invalid mod, please only enter a valid mod "
"code.")
return False
return True
def checkvalidroomnumber(roomNumber, update):
m = re.match(r"([ABCDE][1234][012][0-9])", roomNumber)
try:
start, stop = m.span()
if stop - start == len(roomNumber):
return True
else:
bot.send_message(chat_id=update.effective_chat.id,
text="It appears that you have inputted an invalid room number, please only enter a valid "
"room number "
".")
return False
except:
bot.send_message(chat_id=update.effective_chat.id,
text="It appears that you have inputted an invalid room number, please only enter a valid "
"room number "
".")
return False
registeredAccountSet = set()
def checkregisteredaccount(chat_id, update):
if chat_id in registeredAccountSet:
return True
else:
conn = pg2.connect(DB_URL)
cur = conn.cursor()
getChatId = '''
SELECT chat_id FROM accounts
'''
cur.execute(getChatId)
data = cur.fetchall()
for id in data:
id = id[0]
if id not in registeredAccountSet:
registeredAccountSet.add(id)
if chat_id in registeredAccountSet:
return True
else:
bot.send_message(chat_id=update.effective_chat.id,
text="Please register before using with /register")
return False
def convertmodtofaculty(mod, update):
if mod[0:3] in ['GEC','GEX','GEA','GEI','GEN','GEH','GER','GES','GET','GEQ']:
return 'GE Mods'
elif mod[0:2] == "HS":
return 'CHS Mods'
else:
temp = moduleToFaculty[mod]
if temp in facultyToCategory:
return facultyToCategory[temp]
else:
return 'Others'
def main():
# account creator
accountInitialisation = ConversationHandler(
entry_points=[CommandHandler('register', register)],
states={
ROOMNUMBER: [MessageHandler(Filters.text & ~Filters.command, roomnumber)],
FACULTY: [MessageHandler(Filters.text & ~Filters.command, faculty)],
COURSE: [MessageHandler(Filters.text & ~Filters.command, course)],
YEAR: [CallbackQueryHandler(year)],
MODS1: [MessageHandler(Filters.text & ~Filters.command, mods1), CommandHandler('done', done)],
MODS2: [MessageHandler(Filters.text & ~Filters.command, mods2), CommandHandler('done', done)],
MODS3: [MessageHandler(Filters.text & ~Filters.command, mods3), CommandHandler('done', done)],
MODS4: [MessageHandler(Filters.text & ~Filters.command, mods4), CommandHandler('done', done)],
MODS5: [MessageHandler(Filters.text & ~Filters.command, mods5), CommandHandler('done', done)],
MODS6: [MessageHandler(Filters.text & ~Filters.command, mods6), CommandHandler('done', done)],
MODS7: [MessageHandler(Filters.text & ~Filters.command, mods7), CommandHandler('done', done)],
MODS8: [MessageHandler(Filters.text & ~Filters.command, mods8), CommandHandler('done', done)],
},
fallbacks=[CommandHandler('cancel', cancel), CommandHandler('back', back)])
dispatcher.add_handler(accountInitialisation)
# getting the mods from database
moduleRecall = ConversationHandler(
entry_points=[CommandHandler('mods', mods)],
states={
GETFACULTIES: [CallbackQueryHandler(getfaculties)],
GETMODS: [CallbackQueryHandler(getmods)],
},
fallbacks=[CommandHandler('cancel', cancel)], )
dispatcher.add_handler(moduleRecall)
# inserting link for group chat into database
createGroup = ConversationHandler(
entry_points=[CommandHandler('groupchatcreated', mods)],
states={
GETFACULTIES: [CallbackQueryHandler(getfaculties)],
GETMODS: [CallbackQueryHandler(groupchatcreated)],
LINK: [MessageHandler(Filters.text & ~Filters.command, link)]
},
fallbacks=[CommandHandler('cancel', cancel)], )
dispatcher.add_handler(createGroup)
# delete_mod
deleteMod = ConversationHandler(
entry_points=[CommandHandler('deletemod', deletemod)],
states={
CHOOSEMODULE: [CallbackQueryHandler(choosemodule)]
},
fallbacks=[CommandHandler('cancel', cancel)], )
dispatcher.add_handler(deleteMod)
# add mod
addMod = ConversationHandler(
entry_points=[CommandHandler('addmod', add_module)],
states={
STATEMODULE: [MessageHandler(Filters.text & ~Filters.command, statemodule)]
},
fallbacks=[CommandHandler('cancel', cancel)], )
dispatcher.add_handler(addMod)
startHandler = CommandHandler('start', start)
dispatcher.add_handler(startHandler)
helpHandler = CommandHandler('help', help)
dispatcher.add_handler(helpHandler)
deleteHandler = CommandHandler('deleteaccount', delete_account)
dispatcher.add_handler(deleteHandler)
cancelHandler = CommandHandler('cancel', cancel)
dispatcher.add_handler(cancelHandler)
myModsHandler = CommandHandler('mymods', mymods)
dispatcher.add_handler(myModsHandler)
unknownHandler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(unknownHandler)
updater.start_polling()
if __name__ == '__main__':
main()