-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
909 lines (770 loc) · 29 KB
/
main.py
File metadata and controls
909 lines (770 loc) · 29 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
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
from AWSDatabase import AWSDatabase, UserNotAuthorizedException, UserNotFoundError, WatchlistNotFoundException, WatchlistDuplicateException, ProductNotFoundException, EmptyProfileException, EmptyWatchlistException, BadAmazonProductException
import logging
from dotenv import load_dotenv
from sys import argv
from os import getenv,makedirs
from os.path import isfile,isdir,dirname
import schedule
from time import sleep
import telebot
import threading
from typing import Tuple,List
##?## ------------------------------ VARIABLES ------------------------------ ##?##
load_dotenv()
RESOURCES_PATH = "./resources/"
SCHEDULED_TIME = "13:00"
bot:telebot.TeleBot = telebot.TeleBot("faketoken")
db:AWSDatabase
if (isfile(".env")):
bot = telebot.TeleBot(getenv("TOKEN"),disable_web_page_preview=True)
db = AWSDatabase(int(getenv("ADMIN_ID")),RESOURCES_PATH)
##?## ------------------------------ LOGGING ------------------------------ ##?##
def logger_init() -> logging.Logger:
logging.basicConfig(filename="bot.log",filemode="w",format="%(asctime)s %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
return logger
def log(message:telebot.types.Message,logger:logging.Logger) -> None:
log_msg = (
"{" + str(message.from_user.first_name) +
((" "+str(message.from_user.last_name)) if message.from_user.last_name is not None else "") +
", id="+str(message.from_user.id)+"} -> "+
"{" + str(message.chat.first_name) +
((" "+str(message.chat.last_name)) if message.chat.last_name is not None else "") +
", id="+str(message.chat.id)+"}\n" +
str(message.text)+"\n"
)
print(log_msg)
logger.info(log_msg)
logger = logger_init()
##?## ------------------------------ FUNCTIONS ------------------------------ ##?##
def addPendingRequest(user_id:int) -> int:
userExists = False
with open(db.pendingPath,"r+",encoding='utf-8') as pending_txt:
pending = [int(line.strip()) for line in pending_txt.readlines()]
if (user_id in pending): userExists = True
else: pending_txt.write(str(user_id)+'\n')
if (userExists): return -1
return 0
def removePendingRequest(user_id:int) -> int:
userExists = True
pending = []
with open(db.pendingPath,"r",encoding='utf-8') as pending_txt:
pending = [int(line.strip()) for line in pending_txt.readlines()]
if (user_id not in pending): userExists = False
else: pending.remove(user_id)
if(not userExists): return -1
with open(db.pendingPath,"w",encoding='utf-8') as pending_txt:
for pending_id in pending: pending_txt.write(str(pending_id)+'\n')
return 0
def askAdminAuthUser(user_id:int, user_firstName:str) -> None:
keyboard = telebot.util.quick_markup({
"Yes": {"callback_data":f"y:{user_id}:{user_firstName}"},
"No": {"callback_data":f"n:{user_id}:{user_firstName}"}
}, row_width=2
)
bot.send_message(
chat_id=db.adminId,
text=f"User {user_firstName} ({user_id}) has asked for authorization to use AWS Bot. Authorize?",
reply_markup=keyboard
)
@bot.callback_query_handler(func=(lambda query: query.data[:2] == "y:"))
def adminAuthResponse_yes(query:telebot.types.CallbackQuery) -> None:
if (query.from_user.id != db.adminId): return
res,user_id,user_firstName = query.data.split(':')
user_id = int(user_id)
if (res == "y"):
if (db.addUser(user_id,user_firstName) == -1):
sent = bot.send_message(chat_id=db.adminId,text="User already in the database! Unexpected anomaly :(")
log(sent,logger)
return
sent = bot.send_message(chat_id=user_id,text="You have been authorized to use this bot! :)")
log(sent,logger)
removePendingRequest(user_id)
bot.delete_message(chat_id=db.adminId,message_id=query.message.id)
bot.send_message(chat_id=db.adminId,text=f"User {user_firstName} authorized!",reply_markup=telebot.types.ReplyKeyboardRemove())
else:
sent = bot.send_message(chat_id=db.adminId,text="Unexpected callback query behaviour!")
log(sent,logger)
@bot.callback_query_handler(func=(lambda query: query.data[:2] == "n:"))
def adminAuthResponse_no(query:telebot.types.CallbackQuery) -> None:
if (query.from_user.id != db.adminId): return
res,user_id,user_firstName = query.data.split(':')
user_id = int(user_id)
if (res == "n"):
sent = bot.send_message(chat_id=user_id,text="You have not been authorized to use this bot :(")
log(sent,logger)
removePendingRequest(user_id)
bot.delete_message(chat_id=db.adminId,message_id=query.message.id)
bot.send_message(chat_id=db.adminId,text=f"User {user_firstName} not authorized!",reply_markup=telebot.types.ReplyKeyboardRemove())
else:
sent = bot.send_message(chat_id=db.adminId,text="Unexpected callback query behaviour!")
log(sent,logger)
def firstRun() -> bool:
flag = False
if (not isdir(RESOURCES_PATH)):
makedirs(dirname(RESOURCES_PATH),exist_ok=True)
flag = True
if (not isfile(".env")):
with open(".env","x",encoding='utf-8') as new_env:
new_env.write(f"TOKEN = \"\"\nADMIN_ID = \"\"")
flag = True
return flag
def dailyUpdate() -> None:
db.loadDb()
for user_id in db.authorizedUsers:
tmp_msg = bot.send_message(chat_id=user_id,text=f"Automatic daily update running...")
try:
msg = db.updateWatchlists(user_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(user_id)
return
except UserNotFoundError:
userNotFoundError_message(user_id)
return
except:
unknownError_message(user_id)
return
bot.delete_message(chat_id=user_id,message_id=tmp_msg.id)
sent = bot.send_message(
chat_id=user_id,
text=(msg if msg != "" else "You have no updates"),
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
tmp_msg = bot.send_message(chat_id=db.adminId,text=f"Automatic daily update running...")
try:
msg = db.updateWatchlists(db.adminId)
except UserNotAuthorizedException:
userNotAuthorizedException_message(db.adminId)
return
except UserNotFoundError:
userNotFoundError_message(db.adminId)
return
except:
unknownError_message(db.adminId)
return
bot.delete_message(chat_id=db.adminId,message_id=tmp_msg.id)
sent = bot.send_message(
chat_id=db.adminId,
text=(msg if msg != "" else "You have no updates"),
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def updateRoutine() -> None:
while True:
schedule.run_pending()
sleep(60)
def isValidTime(t:str) -> bool:
return (
(len(t) == 5) and
(t.count(':') == 1) and
(t.replace(':','',1).isdecimal()) and
(int(t[:2]) <= 23) and
(int(t[3:]) <= 59)
)
def isValidUrl(url:str) -> bool:
return (
url.startswith("https://") and
(("amazon" in url) or ("amzn" in url))
)
def isAuthorizedUser(user_id:int) -> bool:
return (
(user_id in db.authorizedUsers) or
(user_id == db.adminId)
)
"""
#! DO NOT USE UNTIL AUX FUNCTIONS GET WRITTEN
def rescheduleUpdate(scheduled_time:str,user_id:str) -> bool:
if (not isValidTime(scheduled_time)): return False
schedule.clear()
schedule.every().day.at(scheduled_time).do(dailyUpdate,user_id)
print("~> Daily update rescheduled at "+scheduled_time)
logger.info("Daily update rescheduled at "+scheduled_time)
"""
def command_switch(message:telebot.types.Message) -> bool:
switcher = {
"/start":start,
"/addwatchlist":addwatchlist,
"/removewatchlist":removewatchlist,
"/addproduct":addproduct,
"/removeproduct":removeproduct,
"/listall":listall,
"/update":update,
"/auth":auth
}
if (message.text in switcher.keys()):
switcher.get(message.text)(message)
return True
return False
def userNotAuthorizedException_message(user_id:int) -> None:
sent = bot.send_message(
chat_id=user_id,
text="Error: it seems like you are not an authorized user :(\nTry asking for authorization with /auth",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def userNotFoundError_message(user_id:int) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"Error: user \"{user_id}\" not found!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def watchlistNotFoundException_message(user_id:int, wl_name:str) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"Error: watchlist \"{wl_name}\" not found!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def watchlistDuplicateException_message(user_id:int, wl_name:str) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"Error: watchlist \"{wl_name}\" already exists!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def productNotFoundException_message(user_id:int, prod_name:str) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"Error: product \"{prod_name}\" not found!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def emptyProfileException_message(user_id:int) -> None:
sent = bot.send_message(
chat_id=user_id,
text="You have no watchlists yet!\nTry creating one with /addwatchlist",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def emptyWatchlistException_message(user_id:int, wl_name:str) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"Watchlist {wl_name} has no products!\nAdd one with /addproduct",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def unknownError_message(user_id:int) -> None:
sent = bot.send_message(
chat_id=user_id,
text="Error: something went wrong!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
def badAmazonProductException_message(user_id:int, prod_name:str) -> None:
sent = bot.send_message(
chat_id=user_id,
text=f"\"{prod_name}\" Amazon product is not fit for web scraping, sorry :(",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
##?## ------------------------------ BOT ROUTES ------------------------------ ##?##
#? START
@bot.message_handler(commands=['start'])
def start(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (sender_id == db.adminId):
bot.send_message(
chat_id=db.adminId,
text="Hi Jaf :)",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
else:
msg = f"Hi {message.from_user.first_name}"
if (sender_id not in db.authorizedUsers):
msg += "\nUse the command /auth to ask for the authorization to use this bot"
bot.send_message(
chat_id=sender_id,
text=msg,
reply_markup=telebot.types.ReplyKeyboardRemove()
)
#? ADDWATCHLIST
@bot.message_handler(commands=['addwatchlist'])
def addwatchlist(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
new_msg = bot.send_message(
chat_id=sender_id,
text="Name of the watchlist to be created? (64 characters max, unique)",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
bot.register_next_step_handler(message=new_msg,callback=addwatchlist_step_1,args=(sender_id))
def addwatchlist_step_1(message:telebot.types.Message,args:int) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args
wl_name = message.text
#if (wl_name in db.getWatchlists(sender_id)):
# watchlistDuplicateException_message(sender_id,wl_name)
# return
if (len(wl_name) > 64):
bot.send_message(chat_id=sender_id,text="Invalid name: it's longer than 64 characters")
return
new_msg = bot.send_message(chat_id=sender_id,text="Do you want to set a target price for this watchlist? (Number if yes, \"no\" otherwise)")
bot.register_next_step_handler(message=new_msg,callback=addwatchlist_step_2,args=(sender_id,wl_name))
def addwatchlist_step_2(message:telebot.types.Message,args:Tuple[int,str]) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args[0]
wl_name = args[1]
targetPrice = message.text
if (targetPrice in ["No","no"]):
targetPrice = None
elif (targetPrice.replace('.','',1).isdigit()):
targetPrice = float(targetPrice)
else:
bot.send_message(chat_id=sender_id,text=f"{targetPrice} is not a valid answer")
return
try:
db.addWatchlist(sender_id,wl_name,targetPrice)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except WatchlistDuplicateException:
watchlistDuplicateException_message(sender_id,wl_name)
return
except:
unknownError_message(sender_id)
return
final_msg = bot.send_message(chat_id=sender_id,text=f"Watchlist \"{wl_name}\" created!")
log(final_msg,logger)
#? REMOVEWATCHLIST
@bot.message_handler(commands=['removewatchlist'])
def removewatchlist(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
try:
wl_names = db.getWatchlists(sender_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except EmptyProfileException:
emptyProfileException_message(sender_id)
return
except:
unknownError_message(sender_id)
return
keyboard = telebot.types.ReplyKeyboardMarkup(
row_width=1,
one_time_keyboard=True,
selective=True,
resize_keyboard=True
)
for wl_name in wl_names: keyboard.add(wl_name)
new_msg = bot.send_message(
chat_id=sender_id,
text="Which watchlist do you want to remove?",
reply_markup=keyboard
)
bot.register_next_step_handler(message=new_msg,callback=removewatchlist_step_1,args=(sender_id))
def removewatchlist_step_1(message:telebot.types.Message,args:int) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args
wl_name = message.text
try:
db.removeWatchlist(sender_id,wl_name)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except WatchlistNotFoundException:
watchlistNotFoundException_message(sender_id,wl_name)
return
except:
unknownError_message(sender_id)
return
final_msg = bot.send_message(
chat_id=sender_id,
text=f"Watchlist \"{wl_name}\" removed!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(final_msg,logger)
#? ADDPRODUCT
@bot.message_handler(commands=['addproduct'])
def addproduct(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
try:
wl_names = db.getWatchlists(sender_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except EmptyProfileException:
emptyProfileException_message(sender_id)
return
except:
unknownError_message(sender_id)
return
keyboard = telebot.types.ReplyKeyboardMarkup(
row_width=1,
one_time_keyboard=True,
selective=True,
resize_keyboard=True
)
for wl_name in wl_names: keyboard.add(wl_name)
new_msg = bot.send_message(
chat_id=sender_id,
text="To which watchlist do you want to add a product?",
reply_markup=keyboard
)
bot.register_next_step_handler(message=new_msg,callback=addproduct_step_1,args=(sender_id))
def addproduct_step_1(message:telebot.types.Message,args:int) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args
wl_name = message.text
if (wl_name not in db.getWatchlists(sender_id)):
watchlistNotFoundException_message(sender_id,wl_name)
return
new_msg = bot.send_message(
chat_id=sender_id,
text="Product URL:",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
bot.register_next_step_handler(message=new_msg,callback=addproduct_step_2,args=(sender_id,wl_name))
def addproduct_step_2(message:telebot.types.Message,args:Tuple[int,str]) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args[0]
wl_name = args[1]
url = message.text
if (not isValidUrl(url)):
new_msg = bot.send_message(chat_id=sender_id,text=f"Invalid URL! ({url})\nMake sure to paste an Amazon URL. Try again:")
bot.register_next_step_handler(message=new_msg,callback=addproduct_step_2,args=(sender_id,wl_name))
return
new_msg = bot.send_message(chat_id=sender_id,text="Do you want to give the product a custom name? (64 characters max, \"no\" to use Amazon's name):")
bot.register_next_step_handler(message=new_msg,callback=addproduct_step_3,args=(sender_id,wl_name,url))
def addproduct_step_3(message:telebot.types.Message,args:Tuple[int,str,str]) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args[0]
wl_name = args[1]
url = args[2]
prod_name = message.text
if (len(prod_name) > 64):
bot.send_message(chat_id=sender_id,text="Invalid name: name longer than 64 characters!")
return
if (prod_name in ["No","no"]): prod_name = None
tmp_msg = bot.send_message(
chat_id=sender_id,
text="Scraping Amazon's website..."
)
try:
added_name = db.addProduct(sender_id,wl_name,url,prod_name)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except WatchlistNotFoundException:
watchlistNotFoundException_message(sender_id,wl_name)
return
except BadAmazonProductException:
badAmazonProductException_message(sender_id,(prod_name if prod_name not in ["No","no"] else ""))
return
except:
unknownError_message(sender_id)
return
bot.delete_message(chat_id=sender_id,message_id=tmp_msg.id)
final_msg = bot.send_message(
chat_id=sender_id,
text=f"\"{added_name}\" added to watchlist \"{wl_name}\"!"
)
log(final_msg,logger)
#? REMOVEPRODUCT
@bot.message_handler(commands=['removeproduct'])
def removeproduct(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
try:
wl_names = db.getWatchlists(sender_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except EmptyProfileException:
emptyProfileException_message(sender_id)
return
except:
unknownError_message(sender_id)
return
keyboard = telebot.types.ReplyKeyboardMarkup(
row_width=1,
one_time_keyboard=True,
selective=True,
resize_keyboard=True
)
for wl_name in wl_names: keyboard.add(wl_name)
new_msg = bot.send_message(
chat_id=sender_id,
text="From which watchlist do you want to remove a product?",
reply_markup=keyboard
)
bot.register_next_step_handler(message=new_msg,callback=removeproduct_step_1,args=(sender_id))
def removeproduct_step_1(message:telebot.types.Message,args:int) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args
wl_name = message.text
try:
prod_names = db.getProducts(sender_id,wl_name)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except WatchlistNotFoundException:
watchlistNotFoundException_message(sender_id)
return
except EmptyWatchlistException:
emptyWatchlistException_message(sender_id,wl_name)
return
except:
unknownError_message(sender_id)
return
keyboard = telebot.types.ReplyKeyboardMarkup(
row_width=1,
one_time_keyboard=True,
selective=True,
resize_keyboard=True
)
for prod_name in prod_names: keyboard.add(prod_name)
new_msg = bot.send_message(
chat_id=sender_id,
text="Which product do you want to remove?",
reply_markup=keyboard
)
bot.register_next_step_handler(message=new_msg,callback=removeproduct_step_2,args=(sender_id,wl_name))
def removeproduct_step_2(message:telebot.types.Message,args:Tuple[int,str]) -> None:
if command_switch(message): return
log(message,logger)
sender_id = args[0]
wl_name = args[1]
prod_name = message.text
try:
db.removeProduct(sender_id,wl_name,prod_name)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except WatchlistNotFoundException:
watchlistNotFoundException_message(sender_id,wl_name)
return
except ProductNotFoundException:
productNotFoundException_message(sender_id,prod_name)
return
except:
unknownError_message(sender_id)
return
final_msg = bot.send_message(
chat_id=sender_id,
text=f"{prod_name} removed from watchlist \"{wl_name}\"!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(final_msg,logger)
#? LISTALL
@bot.message_handler(commands=['listall'])
def listall(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
try:
msg = db.toString(sender_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except EmptyProfileException:
emptyProfileException_message(sender_id)
return
except:
unknownError_message(sender_id)
return
bot.send_message(
chat_id=sender_id,
text=msg,
reply_markup=telebot.types.ReplyKeyboardRemove()
)
#? UPDATE
@bot.message_handler(commands=['update'])
def update(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (not isAuthorizedUser(sender_id)):
userNotAuthorizedException_message(sender_id)
return
tmp_msg = bot.send_message(
chat_id=sender_id,
text="Scraping Amazon's website... (could take a while)"
)
try:
msg = db.updateWatchlists(sender_id)
except UserNotAuthorizedException:
userNotAuthorizedException_message(sender_id)
return
except UserNotFoundError:
userNotFoundError_message(sender_id)
return
except:
unknownError_message(sender_id)
return
bot.delete_message(chat_id=sender_id,message_id=tmp_msg.id)
sent = bot.send_message(
chat_id=sender_id,
text=(msg if msg != "" else "You have no updates"),
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(sent,logger)
#? AUTH
@bot.message_handler(commands=['auth'])
def auth(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
if (message.from_user.id in db.bannedUsers): return
log(message,logger)
sender_id = message.from_user.id
if (sender_id == db.adminId):
bot.send_message(
chat_id=db.adminId,
text="Why are you asking for authorization, jaf?"
)
return
if (isAuthorizedUser(sender_id)):
bot.send_message(
chat_id=sender_id,
text="You already are an authorized user, no need to ask again :)"
)
return
if (addPendingRequest(sender_id) == -1):
bot.send_message(
chat_id=sender_id,
text="You already have a pending authorization request that will get reviewed soon."
)
return
askAdminAuthUser(sender_id,message.from_user.first_name)
bot.send_message(
chat_id=sender_id,
text="An authorization request has been sent! You will be notified when the request gets reviewed.",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
##?## ----- ADMIN TOOLS ----- ##?##
#? USERS (ADMIN COMMAND ONLY)
@bot.message_handler(commands=['users'])
def users(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
log(message,logger)
if (message.from_user.id != db.adminId): return
msg = "List of users:\n"
for user_id,user_firstName,user_role in db.getAuthUsers():
msg += f"{user_id}, {user_firstName}, {user_role}\n"
sent = bot.send_message(
chat_id=db.adminId,
text=msg
)
log(sent,logger)
#? BAN (ADMIN COMMAND ONLY)
@bot.message_handler(commands=['ban'])
def ban(message:telebot.types.Message) -> None:
if (message.from_user.is_bot): return
log(message,logger)
if (message.from_user.id != db.adminId): return
keyboard = telebot.types.ReplyKeyboardMarkup(
row_width=1,
one_time_keyboard=True,
selective=True,
resize_keyboard=True
)
for user_id,user_firstName,role in db.getAuthUsers():
keyboard.add(f"{user_firstName}, {user_id}")
new_msg = bot.send_message(
chat_id=db.adminId,
text="Which user do you want to ban?",
reply_markup=keyboard
)
bot.register_next_step_handler(message=new_msg,callback=ban_step_2)
def ban_step_2(message:telebot.types.Message) -> None:
if command_switch(message): return
log(message,logger)
try:
user_firstName, user_id = message.text.split(', ')
user_id = int(user_id)
except: return
if (db.banUser(user_id) == -1):
sent = bot.send_message(chat_id=db.adminId,text=f"Unable to ban user {user_firstName} Unexpected anomaly :(")
log(sent,logger)
return
final_msg = bot.send_message(
chat_id=db.adminId,
text=f"User {user_firstName} banned!",
reply_markup=telebot.types.ReplyKeyboardRemove()
)
log(final_msg,logger)
##?## ------------------------------ MAIN ------------------------------ ##?##
if (__name__ == "__main__"):
if firstRun():
print("All needed files and folders created, make sure to fill the .env file and run again to start\n")
exit(0)
if (len(argv) > 1):
if (argv[1] in ["--help","-h"]):
print(
"Optional arguments of main.py:\n"
"<scheduledTime>: the time of day at which the bot sends its daily update, formatted as HH:MM\n"
)
exit(0)
if (isValidTime(argv[1])):
SCHEDULED_TIME = argv[1]
schedule.every().day.at(SCHEDULED_TIME).do(dailyUpdate)
dailyUpdateThread = threading.Thread(target=updateRoutine)
print("Jaf's AWS (Amazon Web Scraper) Telegram bot started\n")
logger.info("Jaf's AWS (Amazon Web Scraper) server started")
dailyUpdateThread.start()
bot.infinity_polling()