-
Notifications
You must be signed in to change notification settings - Fork 0
/
hkn_bot.py
803 lines (702 loc) · 40.8 KB
/
hkn_bot.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
#########################################################################################################
### HKN Telegram Bot. Main program for the official bot of the Mu Nu Chapter of IEEE Eta Kappa Nu ###
#########################################################################################################
# Imports
import os
import psycopg2
import telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
import filters
import json
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import ConversationHandler
from telegram.ext import MessageHandler
from telegram.ext import CallbackQueryHandler
from telegram.ext import Filters
import re
import html2text
from urllib.request import urlopen
import time
from enum import Enum
# Downloads from website every day study groups dates
import tutor
from event import *
from wordpress_xmlrpc import Client
from wordpress_xmlrpc.methods import posts
from functools import wraps
from telegram import ChatAction
# Lang dictionaries
from lang import lang_en
from lang import lang_it
import binascii
from Crypto.Cipher import AES
from Crypto.Hash import SHA3_512
from Crypto.Util.Padding import pad, unpad
from psycopg2 import Error
# URL of Postgres db
DATABASE_URL = os.environ['DATABASE_URL']
# get users dictionary from db
def getUsersLanguage():
users_dict = {}
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT * FROM users;")
record = cursor.fetchone()
# for each row, add entry in dictionary
while record is not None:
users_dict[str(record[0])] = str(record[1])
record = cursor.fetchone()
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", str(error))
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
return users_dict
# get members list from db
def getMembersID():
memb = []
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT * FROM members;")
record = cursor.fetchone()
# for each row, add entry in the list
while record is not None:
memb.append(record[0])
record = cursor.fetchone()
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
return memb
# Dictionary which stores language used by every user
users = getUsersLanguage()
# List containing ids of all members
members_list = getMembersID()
# enumeration to handle different keyboard types
class KeyboardType(Enum):
DEFAULT = 1
LANGUAGE = 2
BACK = 3
NEWSLETTER_CONFIRM = 4
NEWSLETTER_UNSUB = 5
ABOUT = 6
DRIVE = 7
MEMBERS = 8
GROUPS = 9
ELECTRONICENGINEERINGGROUPS = 10
UNDO = 11
# function to get different keyboard types
def getKeyboard(type, lang, user_id):
if type == KeyboardType.BACK:
inline_keyboard = [[InlineKeyboardButton(lang["back"], callback_data="back")]]
return InlineKeyboardMarkup(inline_keyboard)
elif type == KeyboardType.UNDO:
custom_keyboard = [[lang["back"]]]
return telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
elif type == KeyboardType.NEWSLETTER_CONFIRM:
keyboard_confirm = [[InlineKeyboardButton(lang["newsletterConfirm"], callback_data="confirm")], [InlineKeyboardButton(lang["back"], callback_data="back")]]
return InlineKeyboardMarkup(keyboard_confirm)
elif type == KeyboardType.NEWSLETTER_UNSUB:
keyboard_unsub = [[InlineKeyboardButton(lang["newsletterUnsubscribe"], callback_data="unsubscribe")]]
return InlineKeyboardMarkup(keyboard_unsub)
elif type == KeyboardType.LANGUAGE:
start_keyboard = [[lang["lang_ita"],lang["lang_eng"]]]
return telegram.ReplyKeyboardMarkup(start_keyboard, resize_keyboard=True)
elif type == KeyboardType.ABOUT:
inline_keyboard = [[InlineKeyboardButton(lang["website"], url="< LINK >")], [InlineKeyboardButton(lang["facebook"], url="< LINK >")], [InlineKeyboardButton(lang["instagram"], url="< LINK >")], [InlineKeyboardButton(lang["youtube"], url="< LINK >")]]
return InlineKeyboardMarkup(inline_keyboard)
elif type == KeyboardType.DRIVE:
inline_keyboard = [[InlineKeyboardButton(lang["driveButton"], url="< LINK >")]]
return InlineKeyboardMarkup(inline_keyboard)
elif type == KeyboardType.ELECTRONICENGINEERINGGROUPS:
inline_keyboard = [[InlineKeyboardButton(lang["Triennale"], callback_data="Triennale")],[InlineKeyboardButton(lang["Magistrale"], callback_data="Magistrale")]]
return InlineKeyboardMarkup(inline_keyboard)
elif type == KeyboardType.MEMBERS:
#if the user is one of the members show the special buttons
if user_id in members_list:
inline_keyboard = [[InlineKeyboardButton(lang["FI"], url="< LINK >")],[InlineKeyboardButton(lang["TelegramGroups"], callback_data="TelegramGroups")], [InlineKeyboardButton(lang["HRGame"], callback_data="HRGame")],[InlineKeyboardButton(lang["usefulLinks"], callback_data="usefulLinks")]]
return InlineKeyboardMarkup(inline_keyboard)
elif type == KeyboardType.GROUPS:
inline_keyboard = [[InlineKeyboardButton("EtaKazzateNu", url="< ETAKAZZATENU LINK >")], [InlineKeyboardButton("HKN Drive", url="< DRIVE LINK >")], [InlineKeyboardButton("HKN-Polito Discord Server", url="< DISCORD SERVER LINK >")], [InlineKeyboardButton("Eta Kappa InvestmeNu", url="< ETA KAPPA INVESTMENU LINK >")], [InlineKeyboardButton("Eta Krypto Nu", url="< ETA KRYPTO NU LINK >")], [InlineKeyboardButton("HKGirls", url="< HKGIRLS LINK >")], [InlineKeyboardButton("Eta PN junction NU", url="< ETA PN JUNCTION NU LINK >")], [InlineKeyboardButton("Eta Kappa PhD", url="< ETA KAPPA PHD LINK >")], [InlineKeyboardButton("hknMUsicNUChapter", url="< HKN MUSIC LINK >")], [InlineKeyboardButton("BiblioteKappaNu", url="< BIBLIOTAKAPPANU LINK >")], [InlineKeyboardButton("EtaKappaNerds", url="< ETAKAPPANERDS LINK >")], [InlineKeyboardButton("HKRocket League", url="< HKROCKET LEAGUE LINK >")], [InlineKeyboardButton("EtaKappaMovies", url="< ETAKAPPAMOVIES LINK >")], [InlineKeyboardButton("EtaKappaSports", url="< ETAKAPPASPORTS LINK >")], [InlineKeyboardButton("EtaKoseaMuzzo", url="< ETAKOSEAMUZZO LINK >")], [InlineKeyboardButton("EtanoloKappaNu", url="< ETANOLOKAPPANU LINK >")], [InlineKeyboardButton("Eta Kidding Nu", url="< ETAMEMENU LINK >")], [InlineKeyboardButton("HKN x gif", url="< HKN x GIF LINK >")]]
return InlineKeyboardMarkup(inline_keyboard)
else:
#if the user is one of the members show the members keyboard
if user_id in members_list:
custom_keyboard = [[lang["events"], lang["news"]], [lang["studygroups"], lang["askus"]], [lang["newsletter"], lang["drive"]], [lang["about"], lang["contact"]], [lang["members"], lang["electronicengineeringgroups"]]]
else:
custom_keyboard = [[lang["events"], lang["news"]], [lang["studygroups"], lang["askus"]], [lang["newsletter"], lang["drive"]], [lang["about"], lang["contact"]], [lang["electronicengineeringgroups"]]]
return telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
# Bot's typing action
def send_action(action):
# Sends `action` while processing func command
def decorator(func):
@wraps(func)
def command_func(*args, **kwargs):
bot, update = args
bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
return func(bot, update, **kwargs)
return command_func
return decorator
# The message "is typing" appears while the bot is processing messages
send_typing_action = send_action(ChatAction.TYPING)
# Language selection
def select_language(user_id):
if users.get(str(user_id)) == None or users.get(str(user_id)) == "EN":
return lang_en
else:
return lang_it
from functools import wraps
# Decrypt admins file and set LIST_OF_ADMINS variable
def decrypt():
fr = open("admins.txt", 'r')
hashed_key = binascii.a2b_base64(fr.readline().encode())
hkn_key = os.environ['HKN_BOT_CIPHERKEY']
if len(hkn_key) < 16:
key = pad(hkn_key.encode(), 16)
elif len(hkn_key) > 16:
key = hkn_key[:16].encode()
else:
key = hkn_key.encode()
hk = SHA3_512.new(key).digest()
if hk != hashed_key:
print('Wrong key!')
aes = AES.new(key, AES.MODE_ECB)
for i in fr:
LIST_OF_ADMINS.append(int(unpad(aes.decrypt(binascii.a2b_base64(i.encode())), 16).decode().strip()))
fr.close()
# Handling of restricted commands
LIST_OF_ADMINS = []
decrypt()
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in LIST_OF_ADMINS:
print("Unauthorized access denied for {}. This action will be reported.".format(user_id))
return
return func(bot, update, *args, **kwargs)
return wrapped
# Retrieving bot token (saved as an env variable)
updater = Updater(token = os.environ['HKN_BOT_TOKEN']) # -> metterlo come variabile d'ambiente
# Setting handlers dispatcher
dispatcher = updater.dispatcher
# Save tutoring groups in file
tutor.users = users
tutor.tutoringFile()
# Start command handler
def start(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["welcome"], reply_markup=getKeyboard(KeyboardType.LANGUAGE, lang, user_id))
# Help command handler
def help(bot, update):
lang = select_language(update.effective_user.id)
bot.send_message(chat_id=update.message.chat_id, text=lang["welcome_up"])
# Updates start message if language is changed
def update_start_message(bot, update, lang):
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["welcome_up"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
# Inline buttons handler
def inline_button(bot, update):
lang = select_language(update.effective_user.id)
query = update.callback_query
user_id = update.effective_user.id
if query.data == "back":
bot.send_message(chat_id=query.message.chat_id, text=lang["questionAbort"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
elif query.data =="Triennale":
bot.send_message(chat_id=query.message.chat_id, parse_mode='HTML', text='🎓 English Course: \n - <a href="< LINK >">Communication networks</a> \n - <a href="< LINK >">Electronic devices</a> \n - <a href="< LINK >">Automatic control</a> \n - <a href="< LINK >">Electronic Circuits</a> \n - <a href="< LINK >">Applied electronics</a> \n - <a href="< LINK >">Digital transmission</a> \n - <a href="< LINK >">Electromagnetic waves and antennas</a> \n - <a href="< LINK >">Applied signal processing laboratory</a> \n - <a href="< LINK >">Digital systems electronics</a> \n - <a href="< LINK >">Electronic measurements</a> \n \n \n 🎓 Corso Italiano: \n - <a href="< LINK >">Economia urbana</a> \n - <a href="< LINK >">Misure</a> \n - <a href="< LINK >">Fibre: preparazione, proprietà e tecnologie di trasformazione</a> \n - <a href="< LINK >">Ingegneria delle cellule e dei tessuti</a> \n - <a href="< LINK >">Ingegneria nelle terapie medico-chirurgiche</a> \n - <a href="< LINK >">RSelezione e progettazione dei materiali per applicazioni ingegneristiche (SPMAI)</a> \n - <a href="< LINK >">Architettura tecnica e cultura del costruito</a> \n - <a href="< LINK >">Strumenti e metodi per la sostenibilità dei sistemi edilizi e territoriali</a> \n - <a href="< LINK >">Electromagnetic fields</a> \n - <a href="< LINK >">Processi dell industria alimentare</a>\n - <a href="< LINK >">Valutazioni di impatto ambientale</a> \n - <a href="< LINK >">Electronic measurements</a> \n - <a href="< LINK >">Teoria dei segnali e delle comunicazioni</a> \n - <a href="< LINK >">Electronic Circuits</a> \n - <a href="< LINK >">Digital systems electronics</a> \n - <a href="< LINK >">Campi elettromagnetici</a> \n - <a href="< LINK >">Electronic devices</a> \n - <a href="< LINK >">Elettronica dei sistemi digitali</a> \n - <a href="< LINK >">Dispositivi elettronici</a> \n - <a href="< LINK >">Circuiti elettronici</a> \n - <a href="< LINK >">Analisi matematica II</a> \n - <a href="< LINK >">Fisica II</a> \n - <a href="< LINK >">Metodi matematici per l ingegneria</a> \n - <a href="< LINK >">Elettrotecnica</a>')
return ConversationHandler.END
elif query.data =="Magistrale":
bot.send_message(chat_id=query.message.chat_id, parse_mode='HTML', text='🎓 Master: \n - <a href="< LINK >">Sistemi digitali integrati</a> \n - <a href="< LINK >">Testing and certification</a> \n - <a href="< LINK >">High speed electron devices</a> \n - <a href="< LINK >">Finite element modelling</a> \n - <a href="< LINK >">Elettronica analogica e di potenza</a> \n - <a href="< LINK >">Radar and remote sensing</a> \n - <a href="< LINK >">Microwave electronics</a> \n - <a href="< LINK >">Sistemi elettronici a basso consumo</a> \n - <a href="< LINK >">Electronic systems engineering</a> \n - <a href="< LINK >">Integrated systems technology</a>\n - <a href="< LINK >">Photonic devices</a> \n - <a href="< LINK >">Microelectronic systems</a> \n - <a href="< LINK >">Communication systems</a> \n - <a href="< LINK >">Analog and telecommunication electronics</a> \n - <a href="< LINK >">Radiating electromagnetic systems</a> \n - <a href="< LINK >">Guiding electromagnetic systems</a> \n - <a href="< LINK >">Sistemi di misura e sensori</a> \n - <a href="< LINK >">Microelettronica digitale</a> \n - <a href="< LINK >">Advanced antenna engineering</a> \n - <a href="< LINK >">Microelettronica digitale</a> \n - <a href="< LINK >">Computer aided design of communication systems</a> \n - <a href="< LINK >">Mobile and sensor networks</a> \n - <a href="< LINK >">Electronics for embedded systems</a> \n - <a href="< LINK >">Modeling and optimization of embedded systems</a> \n - <a href="< LINK >">Codesign methods and tools</a> \n - <a href="< LINK >">Convex optimization and engineering applications</a> \n - <a href="< LINK >">Electromagnetic fields and biological tissues: effects and medical applications</a>\n- <a href="< LINK >">Innovative wireless platforms for the internet of things</a> \n - <a href="< LINK >">Bioinformatics</a> \n - <a href="< LINK >">Automation and planning of production systems</a> \n - <a href="< LINK >">Advanced electronic drives</a> \n - <a href="< LINK >">Radio frequency integrated circuits</a> \n - <a href="< LINK >">Analog integrated circuits</a> \n - <a href="< LINK >">Projects and laboratory on communication systems</a> \n - <a href="< LINK >">Big data: architectures and data analytics</a> \n - <a href="< LINK >">Testing and fault tolerance</a>\n - <a href="< LINK >">Nanomaterials and nanotechnologies for energy applications</a> \n - <a href="< LINK >">Integrazione di sistemi embedded</a> \n - <a href="< LINK >">Industrial Photonics</a> \n - <a href="< LINK >">Open Optical Networks</a> \n - <a href="< LINK >">Signal Processing and Wireless Transmission Lab</a> \n - <a href="< LINK >">Signal Processing and Optical Transmission Lab</a> \n - <a href="< LINK >">Engineering Empathy</a>\n - <a href="< LINK >">Micro and Nanoelectronic Devices</a> \n - <a href="< LINK >">CAD of semiconductor devices</a> \n - <a href="< LINK >">Electronic transport in crystalline and organic semiconductors</a> \n - <a href="< LINK >">Nanoelectronic systems</a> \n - <a href="< LINK >">Microelectronics and Micro/Nanosystems Technologies</a> \n - <a href="< LINK >">Introduction to MEMS and Bio-MEMS</a> \n - <a href="< LINK >">Design of microsystems</a> \n - <a href="< LINK >">Wireless Integrated Circuits and Systems</a> \n - <a href="< LINK >">Integrated systems architecture</a> \n - <a href="< LINK >">Power electronics</a> \n - <a href="< LINK >">Computer architectures</a> \n - <a href="< LINK >">Synthesis and optimization of digital systems</a> \n - <a href="< LINK >">Digital Electronics</a> \n - <a href="< LINK >">Passive Optical Components</a> \n - <a href="< LINK >">Advanced design for signal integrity and compliance</a> \n - <a href="< LINK >">Tecnologie digitali e società</a> \n - <a href="< LINK >">Sistemi robotici</a> \n - <a href="< LINK >">Digital Communications</a>\n - <a href="< LINK >">Operating systems</a> \n - <a href="< LINK >">Optoelettronica</a>')
return ConversationHandler.END
elif query.data == "HRGame":
inline_keyboard = [[InlineKeyboardButton(lang["Classifica"], url="<RANKING LINK>")]]
bot.send_message(chat_id=query.message.chat_id, text=lang["HRRes"], reply_markup=InlineKeyboardMarkup(inline_keyboard))
return ConversationHandler.END
elif query.data == "TelegramGroups":
bot.send_message(chat_id=query.message.chat_id, text=lang["GroupsText"], reply_markup=getKeyboard(KeyboardType.GROUPS, lang, user_id))
return ConversationHandler.END
elif query.data == "usefulLinks":
inline_keyboard = [[InlineKeyboardButton("HKN Drive", url="< LINK >")], [InlineKeyboardButton("HKN-Polito Discord Server", url="< LINK >")], [InlineKeyboardButton("hknMUsicNUChapter", url="< LINK >")], [InlineKeyboardButton("HKN x gif", url="< LINK >")]]
bot.send_message(chat_id=query.message.chat_id, text=lang["LinkDescription"], reply_markup=InlineKeyboardMarkup(inline_keyboard))
return ConversationHandler.END
elif query.data == "confirm":
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscribed WHERE id = {};".format(str(query.message.chat_id)))
record = cursor.fetchone()
# id is already a subscriber
while(record):
bot.send_message(chat_id=query.message.chat_id, text=lang["alreadySubscribed"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
# id is a new subscriber!
cursor.execute("INSERT INTO subscribed(id) VALUES({})".format(query.message.chat_id))
bot.send_message(chat_id=query.message.chat_id, text=lang["newsletterSubscription"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
elif query.data == "unsubscribe":
try:
# connect to db and execute query
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("DELETE FROM subscribed WHERE id = {}".format(query.message.chat_id))
bot.send_message(chat_id=query.message.chat_id, text=lang["newsletterUnsubscription"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
# About handler
@send_typing_action
def about(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["abouttext"], reply_markup=getKeyboard(KeyboardType.ABOUT, lang, user_id))
# Selection of the language it
def sel_language_ita(bot, update):
lang = "IT"
updateUserLanguage(str(update.effective_user.id), lang)
users[str(update.effective_user.id)] = lang
tutor.users[str(update.effective_user.id)] = lang
update_start_message(bot, update, lang_it)
# Selection of the language en
def sel_language_eng(bot, update):
lang = "EN"
updateUserLanguage(str(update.effective_user.id), lang)
users[str(update.effective_user.id)] = lang
tutor.users[str(update.effective_user.id)] = lang
update_start_message(bot, update, lang_en)
# Insert or update user language in db
def updateUserLanguage(user_id, language):
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT lang FROM users WHERE id = '{}';".format(user_id))
record = cursor.fetchone()
updated = False
# user exists, update its language
while record:
if language not in record:
cursor.execute("UPDATE users SET lang = '{}' WHERE id = '{}';".format(language, user_id))
updated = True
break
# user not exists, insert it with selected language
if not updated:
cursor.execute("INSERT INTO users(id, lang) VALUES('{}', '{}')".format(user_id, language))
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
# Questions handler
# TODO language selection
TYPING = 1
@send_typing_action
def questions(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["askAQuestion"], reply_markup=getKeyboard(KeyboardType.UNDO, lang, user_id))
return TYPING
# Question appender to file
# if the question is the result of the pushing of the "<-- back" button, the question is aborted, otherwise the question is saved
def answers(bot,update):
lang = select_language(update.effective_user.id)
user_id1 = update.effective_user.id
if update.message.text != lang["back"]:
out_file = open("questions.txt", "a+", encoding="utf-8")
user_id = str(update.effective_user.id)
out_file.write((str(update.message.from_user.username)+"-"+user_id+"-"+update.message.text).strip("\n")+"\n")
out_file.close()
bot.send_message(chat_id=update.message.chat_id, text=lang["questionSaved"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id1))
for admin in LIST_OF_ADMINS:
bot.send_message(chat_id=admin, text=lang["newQuestionFrom"]+str(update.message.from_user.username)+"\n-"+update.message.text+"\n", reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
else:
bot.send_message(chat_id=update.message.chat_id, text=lang["questionAbort"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id1))
return ConversationHandler.END
# News handler
# TODO language selection
@send_typing_action
def fetch_news(bot, update):
lang = select_language(update.effective_user.id)
client = Client(url = '< LINK >', username = "< HKN USERNAME >", password = os.environ['HKN_WEB_PASSWORD'])
postfilters = {"number": 3, "order": "ASC"}
postsdict = client.call(posts.GetPosts(postfilters))
user_id = update.effective_user.id
for post in postsdict:
content = post.title + "\n" + post.link
bot.send_message(chat_id=update.message.chat_id, text=content, reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
# Displays scheduled events
@send_typing_action
def display_events(bot, update):
# Retrieving the language
user_id = update.effective_user.id
lang = select_language(user_id)
langString = lang["Lang"]
n = 0
eventList = load_events(langString)
for theEvent in eventList:
todayDate = datetime.datetime.now()
if theEvent.date > todayDate: #do not print past events
n = n + 1
if not theEvent.imageLink: #if there isn't an image link
bot.send_message(chat_id=update.message.chat_id, parse_mode="markdown", text="*"+theEvent.title+"*\n\n"+theEvent.description, reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
else:
#Build link buttons
keyboard = []
if theEvent.facebookLink != "" and theEvent.eventbriteLink != "":
keyboard = [[InlineKeyboardButton("Facebook Page", callback_data='1',url=theEvent.facebookLink),
InlineKeyboardButton("Eventbrite", callback_data='2',url=theEvent.eventbriteLink)]]
elif theEvent.facebookLink != "":
keyboard = [[InlineKeyboardButton("Facebook Page", callback_data='1',url=theEvent.facebookLink)]]
elif theEvent.eventbriteLink != "":
keyboard = [[InlineKeyboardButton("Eventbrite", callback_data='2',url=theEvent.eventbriteLink)]]
elif theEvent.instagramLink != "":
keyboard = [[InlineKeyboardButton("Instagram Page", callback_data='3',url=theEvent.instagramLink)]]
else:
continue #skip the sending of the links
reply_markup = InlineKeyboardMarkup(keyboard)
bot.send_photo(chat_id=update.message.chat_id, parse_mode="markdown", caption="*"+theEvent.title+"*\n\n"+theEvent.description, photo=theEvent.imageLink, reply_markup=reply_markup)
if n == 0:
bot.send_message(chat_id=update.message.chat_id, text=lang["noEvents"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
@send_typing_action
def display_newsletterSubscription(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT id FROM subscribed WHERE id = {};".format(str(update.message.chat_id)))
record = cursor.fetchone()
isSubscribed = 0
# id is already subscribed
while(record):
isSubscribed = 1
bot.send_message(chat_id=update.message.chat_id, text=lang["alreadySubscribed"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
break;
# id wants to be subscribed
if(isSubscribed == 0):
bot.send_message(chat_id=update.message.chat_id, text=lang["newsletterAreYouSure"], reply_markup=getKeyboard(KeyboardType.NEWSLETTER_CONFIRM, lang, user_id))
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
# Drive handler
@send_typing_action
def display_drive(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["drivetext"], reply_markup=getKeyboard(KeyboardType.DRIVE, lang, user_id))
def go_back(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=query.message.chat_id, text=lang["questionAbort"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
# Contact handler
@send_typing_action
def contact(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["contacttext"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
# Members handler
@send_typing_action
def members(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["memberstext"], reply_markup=getKeyboard(KeyboardType.MEMBERS, lang, user_id))
# Restricted commands (can be executed only by users in admins.txt)
# Reply to answers handler
# Setting up conversation handler to wait for user message
ANSWER = 1
def pop_question(option = "cancel"):
question_file = open("questions.txt", "r+", encoding="utf-8")
questions = question_file.readlines()
if questions == []:
question_file.close()
return None
question_file.seek(0)
for q in questions[1:]:
question_file.write(q)
question_file.truncate()
if(option == "enqueue"):
question_file.write(questions[0])
question_file.close()
return questions[0].split("-")
@restricted
def answer_question(bot, update):
lang = select_language(update.effective_user.id)
question = pop_question()
user_id = update.effective_user.id
if question == None:
bot.send_message(chat_id=update.message.chat_id, text="Formato file questions.txt non corretto", reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
message = update.message.text
bot.send_message(chat_id=question[1], text=lang["hello"] + " {} ".format(question[0]) + lang["yourAnswer"] + "\n{}".format(message), reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
@restricted
def delete_question(bot, update):
lang = select_language(update.effective_user.id)
pop_question()
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["questionDeleted"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
@restricted
def save_question(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
# get first question
question_file = open("questions.txt", "r", encoding="utf-8")
question = question_file.readline()
question_file.close
# write question in file 'savedquestions.txt', if question is not already present
savedQuestion_file = open("savedquestions.txt", "r", encoding="utf-8")
savedQuestions = savedQuestion_file.readlines()
savedQuestion_file.close()
found = False
for line in savedQuestions:
if str(question) in line:
found = True
bot.send_message(chat_id=update.message.chat_id, text=lang["questionAlreadySaved"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
if not found:
savedQuestion_file = open("savedquestions.txt", "a", encoding="utf-8")
savedQuestion_file.write(question)
savedQuestion_file.close()
bot.send_message(chat_id=update.message.chat_id, text=lang["questionSavedCorrectly"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ANSWER
@restricted
def help_admin(bot,update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["help_admin_text"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
@restricted
def skip(bot,update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["questionNotAnswered"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
pop_question(option="enqueue")
return ConversationHandler.END
@restricted
def cancel(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["conversationDeleted"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
@restricted
def reply(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["answerQuestion"] + " \n", reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
question_file = open("questions.txt", "r", encoding="utf-8")
question = question_file.readline()
if(question == ""):
bot.send_message(chat_id=update.message.chat_id, text=lang["noQuestions"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
return ConversationHandler.END
bot.send_message(chat_id=update.message.chat_id, text=question, reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
question_file.close()
return ANSWER
@restricted
def showpending(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
question_file = open("questions.txt", "r", encoding="utf-8")
questions = question_file.readlines()
n = 0
for q in questions:
question = q.split("-")
bot.send_message(chat_id=update.message.chat_id, text=(question[0] + " " + question[2]), reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
n = n + 1
if(n == 0):
bot.send_message(chat_id=update.message.chat_id, text=lang["questionsAnswered"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
@restricted
def sendNewsletter(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
idList = []
try:
# connect to db
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute("SELECT id FROM subscribed;")
rows = cursor.fetchall()
# add ids to the list
for row in rows:
idList.append(row[0])
except (Exception, psycopg2.Error) as error :
# Postgres automatically rollback the transaction
print ("Error while connecting to PostgreSQL", error)
finally:
if(conn):
cursor.close()
conn.close()
print("PostgreSQL connection is closed")
# send newsletter to all the subscribed users
with open("newsletter.json", "r", encoding="utf-8") as f:
data = json.load(f)
for x in data:
if(lang == lang_en):
for userId in idList:
bot.send_message(chat_id=userId, text=x['DescriptionENG'], reply_markup=getKeyboard(KeyboardType.NEWSLETTER_UNSUB, lang, user_id))
else:
for userId in idList:
bot.send_message(chat_id=userId, text=x['DescriptionITA'], reply_markup=getKeyboard(KeyboardType.NEWSLETTER_UNSUB, lang, user_id))
f.close()
@restricted
def showsaved(bot, update):
lang = select_language(update.effective_user.id)
question_file = open("savedquestions.txt", "r", encoding="utf-8")
questions = question_file.readlines()
user_id = update.effective_user.id
n = 0
for q in questions:
question = q.split("-")
bot.send_message(chat_id=update.message.chat_id, text=(question[0] + " " + question[2]), reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
n = n + 1
if(n == 0):
bot.send_message(chat_id=update.message.chat_id, text=lang["noQuestionsSaved"], reply_markup=getKeyboard(KeyboardType.DEFAULT, lang, user_id))
# EIG handler
@send_typing_action
def electronicengineeringgroups(bot, update):
lang = select_language(update.effective_user.id)
user_id = update.effective_user.id
bot.send_message(chat_id=update.message.chat_id, text=lang["electronicengineeringgroupstext"], reply_markup=getKeyboard(KeyboardType.ELECTRONICENGINEERINGGROUPS, lang, user_id))
# Configurating handlers
reply_conv_handler = ConversationHandler(
entry_points=[CommandHandler("reply", reply)],
states={ANSWER: [MessageHandler(Filters.text, answer_question),
CommandHandler("skip", skip),
CommandHandler("delete", delete_question),
CommandHandler("save", save_question)]
},
fallbacks=[CommandHandler("cancel", cancel)]
)
filter_questions = filters.FilterQuestions()
question_conv_handler = ConversationHandler(
entry_points=[CommandHandler("questions", questions),
MessageHandler(filter_questions, questions)],
states={TYPING: [MessageHandler(Filters.text, answers)]
},
fallbacks=[CommandHandler("cancel", cancel),
CallbackQueryHandler(inline_button)] #TODO: probably CallbackQueryHandler useless
)
# Adding handlers
dispatcher.add_handler(reply_conv_handler)
dispatcher.add_handler(question_conv_handler)
start_handler = CommandHandler("start", start)
dispatcher.add_handler(start_handler)
help_handler = CommandHandler("help", help)
dispatcher.add_handler(help_handler)
pendingq_handler = CommandHandler("showpending", showpending)
dispatcher.add_handler(pendingq_handler)
help_admin_handler = CommandHandler("help_admin", help_admin)
dispatcher.add_handler(help_admin_handler)
savedq_handler = CommandHandler("showsaved", showsaved)
dispatcher.add_handler(savedq_handler)
newsletter_handler = CommandHandler("sendnewsletter", sendNewsletter)
dispatcher.add_handler(newsletter_handler)
filter_electronicengineeringgroups = filters.Filterelectronicengineeringgroups()
electronicengineeringgroups_handler = MessageHandler(filter_electronicengineeringgroups,electronicengineeringgroups)
com_electronicengineeringgroups_handler = CommandHandler("electronicengineeringgroups", electronicengineeringgroups)
dispatcher.add_handler(com_electronicengineeringgroups_handler)
dispatcher.add_handler(electronicengineeringgroups_handler)
filter_tutoring = filters.FilterTutoring()
tutoring_handler = MessageHandler(filter_tutoring, tutor.tutoring)
com_tutoring_handler = CommandHandler("studygroups", tutor.tutoring)
dispatcher.add_handler(com_tutoring_handler)
dispatcher.add_handler(tutoring_handler)
filter_events = filters.FilterEvents()
events_handler = MessageHandler(filter_events, display_events)
com_events_handler = CommandHandler("events", display_events)
dispatcher.add_handler(events_handler)
dispatcher.add_handler(com_events_handler)
filter_newsletter = filters.FilterNewsletter()
newsletter_handler = MessageHandler(filter_newsletter, display_newsletterSubscription)
com_newsletter_handler = CommandHandler("newsletter", display_newsletterSubscription)
dispatcher.add_handler(com_newsletter_handler)
dispatcher.add_handler(newsletter_handler)
filter_drive = filters.FilterDrive()
drive_handler = MessageHandler(filter_drive, display_drive);
com_drive_handler = CommandHandler("drive", display_drive)
dispatcher.add_handler(com_drive_handler)
dispatcher.add_handler(drive_handler)
#function used in the section askus associated to the behavior of the "<-- back" keyboard
filter_back = filters.FilterBack()
back_handler = MessageHandler(filter_back, go_back);
com_back_handler = CommandHandler("back", go_back)
dispatcher.add_handler(com_back_handler)
dispatcher.add_handler(back_handler)
filter_news = filters.FilterNews()
news_handler = MessageHandler(filter_news, fetch_news)
com_news_handler = CommandHandler("news", fetch_news)
dispatcher.add_handler(com_events_handler)
dispatcher.add_handler(news_handler)
filter_about = filters.FilterAbout()
about_handler = MessageHandler(filter_about, about)
com_about_handler = CommandHandler("about", about)
dispatcher.add_handler(about_handler)
dispatcher.add_handler(com_about_handler)
filter_contact = filters.FilterContact()
contact_handler = MessageHandler(filter_contact, contact)
com_contact_handler = CommandHandler("contact", contact)
dispatcher.add_handler(contact_handler)
dispatcher.add_handler(com_contact_handler)
filter_members = filters.FilterMembers()
members_handler = MessageHandler(filter_members, members)
com_members_handler = CommandHandler("members", members)
dispatcher.add_handler(members_handler)
dispatcher.add_handler(com_members_handler)
filter_it = filters.FilterIt()
it_handler = MessageHandler(filter_it, sel_language_ita);
com_it_handler = CommandHandler("lang_ita", sel_language_ita)
dispatcher.add_handler(com_it_handler)
dispatcher.add_handler(it_handler)
filter_en = filters.FilterEn()
en_handler = MessageHandler(filter_en, sel_language_eng);
com_en_handler = CommandHandler("lang_eng", sel_language_eng)
dispatcher.add_handler(com_en_handler)
dispatcher.add_handler(en_handler)
inline_button_handler = CallbackQueryHandler(inline_button)
dispatcher.add_handler(inline_button_handler)
updater.start_polling()
updater.idle()