-
Notifications
You must be signed in to change notification settings - Fork 389
/
YTSpammerPurge.py
1785 lines (1577 loc) · 88.3 KB
/
YTSpammerPurge.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
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#######################################################################################################
################################# YOUTUBE SPAM COMMENT DELETER ########################################
#######################################################################################################
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
###
### Function: Allows you to scan for spam comments with multiple methods, and delete them all at once
###
### Purpose: Recently, there has been a massive infestation of spam on YouTube where fake impersonator
### accounts leave spam/scam replies to hundreds of users on a creator's videos.
###
### For some god-forsaken reason, YouTube offers no way to delete all comments by a specific
### user at once, meaning you must delete them one by one BY HAND.
###
### YouTube offers a functionality to ban a user, but it does NOT delete previous comments.
### Therefore I created this script to allow you to instantly purge their spam comments.
###
### NOTES: 1. To use this script, you will need to obtain your own API credentials file by making
### a project via the Google Developers Console (aka 'Google Cloud Platform').
### The credential file should be re-named 'client_secret.json' and be placed in the
### same directory as this script.
### >>> See the Readme for instructions on this.
###
### 2. I suck at programming so if something doesn't work I'll try to fix it but might not
### even know how, so don't expect too much.
###
### Author: ThioJoe - YouTube.com/ThioJoe
### Twitter.com/ThioJoe
###
### GitHub: https://github.com/ThioJoe/YT-Spammer-Purge/
###
### License: GPL-3.0
###
### IMPORTANT: I OFFER NO WARRANTY OR GUARANTEE FOR THIS SCRIPT. USE AT YOUR OWN RISK.
### I tested it on my own and implemented some failsafes as best as I could,
### but there could always be some kind of bug. You should inspect the code yourself.
version = "2.17.1"
configVersion = 32
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
print("Importing Script Modules...")
# Import other module files
from Scripts.shared_imports import *
import Scripts.auth as auth
import Scripts.validation as validation
import Scripts.utils as utils
import Scripts.files as files
import Scripts.logging as logging
import Scripts.operations as operations
import Scripts.user_tools as user_tools
from Scripts.community_downloader import main as get_community_comments #Args = post's ID, comment limit
import Scripts.community_downloader as community_downloader
from Scripts.utils import choice
print("Importing Standard Libraries...")
# Standard Libraries
import time
from dataclasses import dataclass
from datetime import datetime, timedelta
from collections import namedtuple
import json, ast
from pkg_resources import parse_version
print("Importing Third-Party Modules...")
# Other Libraries
from googleapiclient.errors import HttpError
##########################################################################################
##########################################################################################
###################################### MAIN ##############################################
##########################################################################################
##########################################################################################
def main():
global S
global B
global F
# These variables are from shared_imports.py
# S - Style
# B - Background
# F - Foreground
# Run check on python version, must be 3.6 or higher because of f strings
if sys.version_info[0] < 3 or sys.version_info[1] < 6:
print("Error Code U-2: This program requires running python 3.6 or higher! You are running" + str(sys.version_info[0]) + "." + str(sys.version_info[1]))
input("Press Enter to Exit...")
sys.exit()
# Declare Global Variables
global YOUTUBE
global CURRENTUSER
User = namedtuple('User', 'id name configMatch')
# Some Typehints
scanMode: str
config: dict
jsonData: dict
versionInfoJson: dict
utils.clear_terminal()
print("\nLoading YT Spammer Purge @ " + str(version) + "...")
# Authenticate with the Google API - If token expired and invalid, deletes and re-authenticates
YOUTUBE = auth.first_authentication()
#### Prepare Resources ####
resourceFolder = RESOURCES_FOLDER_NAME
whitelistPathWithName = os.path.join(resourceFolder, "whitelist.txt")
spamListFolder = os.path.join(resourceFolder, "Spam_Lists")
filtersFolder = os.path.join(resourceFolder, "Filters")
filterFileName = "filter_variables.py"
spamListDict = {
'Lists': {
'Domains': {'FileName': "SpamDomainsList.txt"},
'Accounts': {'FileName': "SpamAccountsList.txt"},
'Threads': {'FileName': "SpamThreadsList.txt"}
},
'Meta': {
'VersionInfo': {'FileName': "SpamVersionInfo.json"},
'SpamListFolder': spamListFolder
#'LatestLocalVersion': {} # Gets added later during check, this line here for reference
}
}
filterListDict = {
'Files': {
'FilterVariables': {'FileName': filterFileName}
},
'ResourcePath': filtersFolder
#'LocalVersion': {} # Gets added later during check, this line here for reference
}
resourcesDict = {
'Whitelist': {
'PathWithName': whitelistPathWithName,
'FileName': "whitelist.txt",
}
}
print("Checking for updates to program and spam lists...")
# Check if resources, spam list, and filters folders exist, and create them
if not os.path.isdir(resourceFolder):
try:
os.mkdir(resourceFolder)
# Create readme
with open(os.path.join(resourceFolder, "_What_Is_This_Folder.txt"), "w") as f:
f.write("# This Resources folder is used to store resources required for the YT Spammer Purge program.\n")
f.write("# Note: If you had a previous spam_lists folder that was created in the same folder as \n")
f.write("# the .exe file, you can delete that old spam_lists folder. The resources folder is the \n")
f.write("# new location they will be stored.\n")
except:
print("\nError: Could not create folder. To update the spam lists, try creating a folder called 'SpamPurge_Resources',")
print(" then inside that, create another folder called 'Spam_Lists'.")
input("Press Enter to Continue...")
if os.path.isdir(resourceFolder) and not os.path.isdir(spamListFolder):
try:
os.mkdir(spamListFolder)
except:
print("\nError: Could not create folder. To update the spam lists, go into the 'SpamPurge_Resources' folder,")
print(" then inside that, create another folder called 'Spam_Lists'.")
if os.path.isdir(resourceFolder) and not os.path.isdir(filtersFolder):
try:
os.mkdir(filtersFolder)
except:
print("\nError: Could not create folder. To update the spam lists, go into the 'SpamPurge_Resources' folder,")
print(" then inside that, create another folder called 'Filters'.")
# Prepare to check and ingest spammer list files
# Iterate and get paths of each list. Also gets path of filter_variables.py
# This for loops might not actually do anything?
for x,spamList in spamListDict['Lists'].items():
spamList['Path'] = os.path.join(spamListFolder, spamList['FileName'])
spamListDict['Meta']['VersionInfo']['Path'] = os.path.join(spamListFolder, spamListDict['Meta']['VersionInfo']['FileName']) # Path to version included in packaged assets folder
# Check if each spam list exists, if not copy from assets, then get local version number, calculate latest version number
latestLocalSpamListVersion = "1900.12.31"
for x, spamList in spamListDict['Lists'].items():
if not os.path.exists(spamList['Path']):
files.copy_asset_file(spamList['FileName'], spamList['Path'])
listVersion = files.get_list_file_version(spamList['Path'])
spamList['Version'] = listVersion
if listVersion and parse_version(listVersion) > parse_version(latestLocalSpamListVersion):
latestLocalSpamListVersion = listVersion
spamListDict['Meta']['VersionInfo']['LatestLocalVersion'] = latestLocalSpamListVersion
# Check for version info file, if it doesn't exist, get from assets folder
if not os.path.exists(spamListDict['Meta']['VersionInfo']['Path']):
files.copy_asset_file(spamListDict['Meta']['VersionInfo']['FileName'], spamListDict['Meta']['VersionInfo']['Path'])
# Check if filter_variables.py is in Spampurge_Resources, if not copy from temp folder or scripts, depending if using pyinstaller
filterFilePath = os.path.join(filtersFolder, filterFileName)
if not os.path.exists(filterFilePath):
files.copy_scripts_file(filterFileName, filterFilePath)
# Get stored spam list version data from json file
jsonData = open(spamListDict['Meta']['VersionInfo']['Path'], 'r', encoding="utf-8")
versionInfoJson = str(json.load(jsonData)) # Parses json file into a string
versionInfo = ast.literal_eval(versionInfoJson) # Parses json string into a dictionary
spamListDict['Meta']['VersionInfo']['LatestRelease'] = versionInfo['LatestRelease']
spamListDict['Meta']['VersionInfo']['LastChecked'] = versionInfo['LastChecked']
# Get current version of filter_variables.py that is in the SpamPurge_Resources/Filters folder
filterVersion = files.get_current_filter_version(filterListDict)
filterListDict['LocalVersion'] = filterVersion
# Check for primary config file, load into dictionary 'config'. If no config found, loads data from default config in assets folder
utils.clear_terminal()
config = files.load_config_file(configVersion)
validation.validate_config_settings(config)
utils.clear_terminal()
# Disable colors before they are used anywhere
if config['colors_enabled'] == False:
# Disables colors entirely
init(autoreset=True, strip=True, convert=False)
else:
# Initiates colorama and creates shorthand variables for resetting colors
init(autoreset=True)
# Check for program and list updates if auto updates enabled in config
try:
if config['release_channel'] == "all":
updateReleaseChannel = "all"
elif config['release_channel'] == "stable":
updateReleaseChannel = "stable"
else:
print("Invalid value for 'release_channel' in config file. Must be 'All' or 'Stable'")
print("Defaulting to 'All'")
input("Press Enter to Continue...")
updateReleaseChannel = "all"
except KeyError:
print("\nYour version of the config file does not specify a release channel. Defaulting to 'All'")
print(f"{F.YELLOW}Re-create your config{S.R} to get the latest version.")
input("\nPress Enter to Continue...")
updateReleaseChannel = "all"
if config['auto_check_update'] == True:
try:
updateAvailable = files.check_for_update(version, updateReleaseChannel, silentCheck=True, )
except Exception as e:
print(f"{F.LIGHTRED_EX}Error Code U-3 occurred while checking for updates. (Checking can be disabled using the config file setting) Continuing...{S.R}\n")
updateAvailable = None
# Only check for updates once a day, compare current date to last checked date
if datetime.today() > datetime.strptime(spamListDict['Meta']['VersionInfo']['LastChecked'], '%Y.%m.%d.%H.%M')+timedelta(days=1):
# Check for update to filter variables file
files.check_for_filter_update(filterListDict, silentCheck=True)
# Check spam lists if today or tomorrow's date is later than the last update date (add day to account for time zones)
if datetime.today()+timedelta(days=1) >= datetime.strptime(spamListDict['Meta']['VersionInfo']['LatestLocalVersion'], '%Y.%m.%d'):
spamListDict = files.check_lists_update(spamListDict, silentCheck=True)
else:
updateAvailable = False
# In all scenarios, load spam lists into memory
for x, spamList in spamListDict['Lists'].items():
spamList['FilterContents'] = files.ingest_list_file(spamList['Path'], keepCase=False)
# In all scenarios, load filter variables into memory. Must import prepare_modes after filter_variables has been updated and placed in SpamPurge_Resources
print("Loading filter file...\n")
import Scripts.prepare_modes as modes
####### Load Other Data into MiscData #######
print("\nLoading other assets..\n")
@dataclass
class MiscDataStore:
resources:dict
spamLists:dict
totalCommentCount:int
channelOwnerID:str
channelOwnerName:str
miscData = MiscDataStore(
resources = {},
spamLists = {},
totalCommentCount = 0,
channelOwnerID = "",
channelOwnerName = "",
)
miscData.resources = resourcesDict
rootDomainListAssetFile = "rootZoneDomainList.txt"
rootDomainList = files.ingest_asset_file(rootDomainListAssetFile)
miscData.resources['rootDomainList'] = rootDomainList
miscData.spamLists['spamDomainsList'] = spamListDict['Lists']['Domains']['FilterContents']
miscData.spamLists['spamAccountsList'] = spamListDict['Lists']['Accounts']['FilterContents']
miscData.spamLists['spamThreadsList'] = spamListDict['Lists']['Threads']['FilterContents']
# Create Whitelist if it doesn't exist,
if not os.path.exists(whitelistPathWithName):
with open(whitelistPathWithName, "a") as f:
f.write("# Commenters whose channel IDs are in this list will always be ignored. You can add or remove IDs (one per line) from this list as you wish.\n")
f.write("# Channel IDs for a channel can be found in the URL after clicking a channel's name while on the watch page or where they've left a comment.\n")
f.write("# - Channels that were 'excluded' will also appear in this list.\n")
f.write("# - Lines beginning with a '#' are comments and aren't read by the program. (But do not put a '#' on the same line as actual data)\n\n")
miscData.resources['Whitelist']['WhitelistContents'] = []
else:
miscData.resources['Whitelist']['WhitelistContents'] = files.ingest_list_file(whitelistPathWithName, keepCase=True)
if config:
moderator_mode = config['moderator_mode']
else:
moderator_mode = False
utils.clear_terminal()
#----------------------------------- Begin Showing Program ---------------------------------
print(f"{F.LIGHTYELLOW_EX}\n===================== YOUTUBE SPAMMER PURGE v" + version + f" ====================={S.R}")
print("=========== https://github.com/ThioJoe/YT-Spammer-Purge ===========")
print("================= Author: ThioJoe - YouTube.com/ThioJoe ================ \n")
# Instructions
print("Purpose: Lets you scan for spam comments and mass-delete them all at once \n")
print("NOTE: It's probably better to scan individual videos, because you can scan all those comments,")
print(" but scanning your entire channel must be limited and might miss older spam comments.")
print("You will be shown the comments to confirm before they are deleted.")
# While loop until user confirms they are logged into the correct account
confirmedCorrectLogin = False
while confirmedCorrectLogin == False:
# Get channel ID and title of current user, confirm with user
userInfo = auth.get_current_user(config)
CURRENTUSER = User(id=userInfo[0], name=userInfo[1], configMatch=userInfo[2]) # Returns [channelID, channelTitle, configmatch]
auth.CURRENTUSER = CURRENTUSER
print("\n > Currently logged in user: " + f"{F.LIGHTGREEN_EX}" + str(CURRENTUSER.name) + f"{S.R} (Channel ID: {F.LIGHTGREEN_EX}" + str(CURRENTUSER.id) + f"{S.R} )")
if choice(" Continue as this user?", CURRENTUSER.configMatch) == True:
confirmedCorrectLogin = True
utils.clear_terminal()
else:
auth.remove_token()
utils.clear_terminal()
YOUTUBE = auth.get_authenticated_service()
# Declare Classes
@dataclass
class ScanInstance:
matchedCommentsDict: dict #Comments flagged by the filter
duplicateCommentsDict: dict #Comments flagged as duplicates
repostedCommentsDict: dict #Comments stolen from other users
otherCommentsByMatchedAuthorsDict: dict #Comments not matched, but are by a matched author
scannedThingsList: list #List of posts or videos that were scanned
spamThreadsDict: dict #Comments flagged as parent of spam threads
allScannedCommentsDict: dict #All comments scanned for this instance
vidIdDict: dict #Contains the video ID on which each comment is found
vidTitleDict: dict #Contains the titles of each video ID
matchSamplesDict: dict #Contains sample info for every flagged comment of all types
authorMatchCountDict: dict #The number of flagged comments per author
scannedRepliesCount: int #The current number of replies scanned so far
scannedCommentsCount: int #The current number of comments scanned so far
logTime: str #The time at which the scan was started
logFileName: str #Contains a string of the current date/time to be used as a log file name or anything else
errorOccurred:bool #True if an error occurred during the scan
##############################################
######### PRIMARY INSTANCE FUNCTION ##########
##############################################
## Allows Re-running Program From Main Menu ##
##############################################
def primaryInstance(miscData):
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# Instantiate class for primary instance
current = ScanInstance(
matchedCommentsDict={},
duplicateCommentsDict={},
repostedCommentsDict={},
otherCommentsByMatchedAuthorsDict={},
scannedThingsList=[],
spamThreadsDict = {},
allScannedCommentsDict={},
vidIdDict={},
vidTitleDict={},
matchSamplesDict={},
authorMatchCountDict={},
scannedRepliesCount=0,
scannedCommentsCount=0,
logTime = timestamp,
logFileName = None,
errorOccurred = False,
)
# Declare Default Variables
maxScanNumber = 999999999
scanVideoID = None
videosToScan = []
recentPostsListofDicts = []
postURL = ""
loggingEnabled = False
userNotChannelOwner = False
utils.clear_terminal()
# -----------------------------------------------------------------------------------------------------------------------------
if updateAvailable != False:
updateStringLabel = "Update Available: "
if updateAvailable == True: # Stable update available
updateString = f"{B.LIGHTGREEN_EX}{F.BLACK} Yes {S.R}"
elif updateAvailable == "beta": # Beta Update Available
if updateReleaseChannel == "stable":
updateStringLabel = ""
updateString = ""
else:
updateString = f"{B.LIGHTCYAN_EX}{F.BLACK} Beta {S.R}"
elif updateAvailable == None:
updateString = f"{F.LIGHTRED_EX}Error{S.R}"
print("> Note: Error during check for updates. Select 'Check For Updates' for details.")
else:
if config['auto_check_update'] == False:
updateStringLabel = "Update Checking: "
updateString = "Off"
else:
updateStringLabel = ""
updateString = ""
# User selects scanning mode, while Loop to get scanning mode, so if invalid input, it will keep asking until valid input
print("\n{:<59}{:<18}{:>7}".format("> At any prompt, enter 'X' to return here", updateStringLabel, updateString))
print("> Enter 'Q' now to quit")
print(f"\n\n-------------------------------- {F.YELLOW}Scanning Options{S.R} --------------------------------")
print(f" 1. Scan {F.LIGHTCYAN_EX}specific videos{S.R}")
print(f" 2. Scan {F.LIGHTCYAN_EX}recent videos{S.R} for a channel")
print(f" 3. Scan recent comments across your {F.LIGHTBLUE_EX}Entire Channel{S.R}")
print(f" 4. Scan a specific {F.LIGHTMAGENTA_EX}community post{S.R} (Experimental)")
print(f" 5. Scan {F.LIGHTMAGENTA_EX}recent community posts{S.R} for a channel (Experimental)")
print(f"\n--------------------------------- {F.YELLOW}Other Options{S.R} ----------------------------------")
print(f" 6. Create your own {F.LIGHTGREEN_EX}config file(s){S.R} to run the program with pre-set settings")
print(f" 7. Remove comments using a {F.LIGHTRED_EX}pre-existing list{S.R} or log file")
print(f" 8. Recover deleted comments using log file")
print(f" 9. Check & Download {F.LIGHTCYAN_EX}Updates{S.R}")
print(f" 10. {F.BLACK}{B.LIGHTGREEN_EX} NEW! {S.R} Helpful Tools")
print("")
# Make sure input is valid, if not ask again
validMode:bool = False
validConfigSetting:bool = True
while validMode == False:
if validConfigSetting == True and config and config['scan_mode'] != 'ask':
scanMode = config['scan_mode']
else:
scanMode = input("Choice (1-10): ")
if scanMode.lower() == "q":
sys.exit()
# Set scanMode Variable Names
validModeValues = ['1', '2', '3', '4', '5', '6', '7', '8', '9','10', 'chosenvideos', 'recentvideos', 'entirechannel', 'communitypost', 'commentlist', 'recentcommunityposts']
if scanMode in validModeValues:
validMode = True
if scanMode == "1" or scanMode == "chosenvideos":
scanMode = "chosenVideos"
elif scanMode == "2" or scanMode == "recentvideos":
scanMode = "recentVideos"
elif scanMode == "3" or scanMode == "entirechannel":
scanMode = "entireChannel"
elif scanMode == "4" or scanMode == "communitypost":
scanMode = "communityPost"
elif scanMode == "5" or scanMode == "recentcommunityposts":
scanMode = "recentCommunityPosts"
elif scanMode == "6":
scanMode = "makeConfig"
elif scanMode == "7" or scanMode == "commentlist":
scanMode = "commentList"
elif scanMode == "8":
scanMode = "recoverMode"
elif scanMode == "9":
scanMode = "checkUpdates"
elif scanMode == "10":
scanMode = "tools"
else:
print(f"\nInvalid choice: {scanMode} - Enter a number from 1 to 10")
validConfigSetting = False
# ================================================================================= CHOSEN VIDEOS ======================================================================================================
# If chooses to scan single video - Validate Video ID, get title, and confirm with user
if scanMode == "chosenVideos":
# While loop to get video ID and if invalid ask again
confirm:bool = False
validConfigSetting = True
while confirm == False:
numVideos = 1
allVideosMatchBool = True
miscData.totalCommentCount = 0
# Checks if input list is empty and if contains only valid video IDs
listNotEmpty:bool = False
validVideoIDs = False # False just to get into the loop
while listNotEmpty == False or validVideoIDs == False:
if validConfigSetting == True and config and config['videos_to_scan'] != 'ask':
enteredVideosList = utils.string_to_list(config['videos_to_scan'])
if len(enteredVideosList) == 0:
validConfigSetting = False
listNotEmpty = False
print(f"{F.LIGHTRED_EX}\nError: Video list is empty!{S.R}")
else:
listNotEmpty = True
else:
print(f"\nEnter a list of {F.YELLOW}Video Links{S.R} or {F.YELLOW}Video IDs{S.R} to scan, separated by commas.")
print(" > Note: All videos must be from the same channel.")
enteredVideosList = utils.string_to_list(input("\nEnter here: "))
if str(enteredVideosList).lower() == "['x']":
return True # Return to main menu
validConfigSetting = False
if len(enteredVideosList) == 0:
listNotEmpty = False
print(f"{F.LIGHTRED_EX}\nError: Video list is empty!{S.R}")
else:
listNotEmpty = True
# Validates all video IDs/Links, gets necessary info about them
validVideoIDs:bool = True
videosToScan = []
videoListResult = [] # True/False, video ID, videoTitle, commentCount, channelID, channelTitle
for i in range(len(enteredVideosList)):
videoListResult.append([])
videosToScan.append({})
videoListResult[i] = validation.validate_video_id(enteredVideosList[i]) # Sends link or video ID for isolation and validation
if videoListResult[i][0] == False:
validVideoIDs = False
validConfigSetting = False
confirm = False
break
for i in range(len(videoListResult)): # Change this
if videoListResult[i][0] == True:
videosToScan[i]['videoID'] = str(videoListResult[i][1])
videosToScan[i]['videoTitle'] = str(videoListResult[i][2])
videosToScan[i]['commentCount'] = int(videoListResult[i][3])
videosToScan[i]['channelOwnerID'] = str(videoListResult[i][4])
videosToScan[i]['channelOwnerName'] = str(videoListResult[i][5])
miscData.totalCommentCount += int(videoListResult[i][3])
if str(videoListResult[i][1]) not in current.vidTitleDict:
current.vidTitleDict[videoListResult[i][1]] = str(videoListResult[i][2])
else:
print(f"\nInvalid Video: {enteredVideosList[i]} | Video ID = {videoListResult[1]}")
validConfigSetting = False
break
# Check each video against first to ensure all on same channel
if allVideosMatchBool == True:
misMatchVidIndex = 0
if videosToScan[0]['channelOwnerID'] != videosToScan[i]['channelOwnerID']:
misMatchVidIndex += 1
if allVideosMatchBool == True:
print(f"\n {F.LIGHTRED_EX}ERROR: Videos scanned together all must be from the same channel.{S.R}")
print(" The following videos do not match the channel owner of the first video in the list: ")
if misMatchVidIndex == 11 and len(enteredVideosList) > 10:
remainingCount = str(len(enteredVideosList) - 10)
userChoice = choice(f"There are {remainingCount} more mis-matched videos, do you want to see the rest?")
if userChoice == False:
break
elif userChoice == None:
return True # Return to main menu
print(f" {misMatchVidIndex}. {str(videosToScan[i]['videoTitle'])}")
validConfigSetting = False
allVideosMatchBool = False
# If videos not from same channel, skip and re-prompt
if allVideosMatchBool == True:
# Print video titles, if there are many, ask user to see all if more than 5
i = 0
print(f"\n{F.BLUE}Chosen Videos:{S.R}")
for video in videosToScan:
i += 1
if i==6 and len(enteredVideosList) > 5:
remainingCount = str(len(enteredVideosList) - 5)
if config['skip_confirm_video'] == False:
userChoice = choice(f"You have entered many videos, do you need to see the rest (x{remainingCount})?")
if userChoice == False:
break
elif userChoice == None:
return True # Return to main menu
print(f" {i}. {video['videoTitle']}")
print("")
if CURRENTUSER.id != videosToScan[0]['channelOwnerID']:
userNotChannelOwner = True
miscData.channelOwnerID = videosToScan[0]['channelOwnerID']
miscData.channelOwnerName = videosToScan[0]['channelOwnerName']
# Ask if correct videos, or skip if config
if config['skip_confirm_video'] == True:
confirm = True
else:
if userNotChannelOwner == True and moderator_mode == False:
print(f"{F.LIGHTRED_EX}NOTE: This is not your video. Enabling '{F.YELLOW}Not Your Channel Mode{F.LIGHTRED_EX}'. You can report spam comments, but not delete them.{S.R}")
elif userNotChannelOwner == True and moderator_mode == True:
print(f"{F.LIGHTRED_EX}NOTE: {F.YELLOW}Moderator Mode is enabled{F.LIGHTRED_EX}. You can hold comments for review when using certain modes{S.R}")
print("Total number of comments to scan: " + str(miscData.totalCommentCount))
if miscData.totalCommentCount >= 100000:
print(f"\n{B.YELLOW}{F.BLACK} WARNING: {S.R} You have chosen to scan a large amount of comments. The default API quota limit ends up")
print(f" around {F.YELLOW}10,000 comment deletions per day{S.R}. If you find more spam than that you will go over the limit.")
print(f" > Read more about the quota limits for this app here: {F.YELLOW}TJoe.io/api-limit-info{S.R}")
if userNotChannelOwner == False or moderator_mode == True:
print(f"{F.LIGHTCYAN_EX}> Note:{S.R} You may want to disable 'check_deletion_success' in the config, as this doubles the API cost! (So a 5K limit)")
confirm = choice("Is this video list correct?", bypass=validConfigSetting)
if confirm == None:
return True # Return to main menu
# ============================================================================ RECENT VIDEOS ==========================================================================================================
elif scanMode == "recentVideos":
confirm = False
validEntry = False
validChannel = False
while validChannel == False:
# Get and verify config setting for channel ID
if config['channel_to_scan'] != 'ask':
if config['channel_to_scan'] == 'mine':
channelID = CURRENTUSER.id
channelTitle = CURRENTUSER.name
validChannel = True
break
else:
validChannel, channelID, channelTitle = validation.validate_channel_id(config['channel_to_scan'])
if validChannel == True:
break
else:
print("Invalid Channel ID or Link in config file!")
print(f"\nEnter a {F.YELLOW}channel ID or Link{S.R} to scan {F.LIGHTCYAN_EX}recent videos{S.R} from")
print(f" > If scanning {F.YELLOW}your own channel{S.R}, just hit {F.LIGHTGREEN_EX}Enter{S.R}")
inputtedChannel = input("\nEnter Here: ")
if inputtedChannel == "":
channelID = CURRENTUSER.id
channelTitle = CURRENTUSER.name
validChannel = True
elif str(inputtedChannel).lower() == "x":
return True # Return to main menu
else:
validChannel, channelID, channelTitle = validation.validate_channel_id(inputtedChannel)
if CURRENTUSER.id != channelID:
userNotChannelOwner = True
print(f"\nChosen Channel: {F.LIGHTCYAN_EX}{channelTitle}{S.R}")
# Get number of recent videos to scan, either from config or user input, and validate
while validEntry == False or confirm == False:
videosToScan=[]
validConfigSetting = True
if config['recent_videos_amount'] != 'ask' and validConfigSetting == True:
numVideos = config['recent_videos_amount']
try:
numVideos = int(numVideos)
except:
validConfigSetting = False
print("Invalid number entered in config file for recent_videos_amount")
numVideos = None
else:
print(f"\nEnter the {F.YELLOW}number of most recent videos{S.R} to scan back-to-back:")
numVideos = input("\nNumber of Recent Videos: ")
print("")
if str(numVideos).lower() == "x":
return True # Return to main menu
try:
numVideos = int(numVideos)
if numVideos > 0 and numVideos <= 5000:
validEntry = True
validConfigSetting = True
else:
print("Error: Entry must be from 1 to 5000 (the YouTube API Limit)")
validEntry = False
validConfigSetting = False
except ValueError:
print(f"{F.LIGHTRED_EX}Error:{S.R} Entry must be a whole number greater than zero.")
validEntry = False
if validEntry == True and numVideos >= 1000:
print(f"\n{B.YELLOW}{F.BLACK} WARNING: {S.R} You have chosen to scan a large amount of videos. With the default API quota limit,")
print(f" every 1000 videos will use up 20% of the quota {F.YELLOW}just from listing the videos alone, before any comment scanning.{S.R}")
print(f" > Read more about the quota limits for this app here: {F.YELLOW}TJoe.io/api-limit-info{S.R}")
if validEntry == True:
# Fetch recent videos and print titles to user for confirmation
videosToScan = operations.get_recent_videos(current, channelID, numVideos)
if str(videosToScan) == "MainMenu":
return True # Return to main menu
if len(videosToScan) == 0:
print(f"\n{F.LIGHTRED_EX}Error:{S.R} No scannable videos found in selected range! They all may have no comments and/or are live streams.")
if config['auto_close'] == True:
print("Auto-close enabled in config. Exiting in 5 seconds...")
time.sleep(5)
sys.exit()
else:
input("\nPress Enter to return to main menu...")
return True
# Get total comment count
miscData.totalCommentCount = 0
for video in videosToScan:
miscData.totalCommentCount += int(video['commentCount'])
if len(videosToScan) < numVideos:
print(f"\n{F.YELLOW} WARNING:{S.R} Only {len(videosToScan)} videos found. Videos may be skipped if there are no comments.")
print("\nRecent Videos To Be Scanned:")
for i in range(len(videosToScan)):
if config['skip_confirm_video'] == False:
if i == 10 and len(videosToScan) > 11:
remainingCount = str(len(videosToScan) - 10)
userChoice = choice(f"There are {remainingCount} more recent videos, do you want to see the rest?")
if userChoice == False:
break
elif userChoice == None:
return True # Return to main menu
print(f" {i+1}. {videosToScan[i]['videoTitle']}")
if config['skip_confirm_video'] == True and validConfigSetting == True:
confirm = True
else:
if userNotChannelOwner == True and moderator_mode == False:
print(f"{F.LIGHTRED_EX}NOTE: These aren't your videos. Enabling '{F.YELLOW}Not Your Channel Mode{F.LIGHTRED_EX}'. You can report spam comments, but not delete them.{S.R}")
elif userNotChannelOwner == True and moderator_mode == True:
print(f"{F.LIGHTRED_EX}NOTE: {F.YELLOW}Moderator Mode is enabled{F.LIGHTRED_EX}. You can hold comments for review when using certain modes{S.R}")
print("\nTotal number of comments to scan: " + str(miscData.totalCommentCount))
if miscData.totalCommentCount >= 100000:
print(f"\n{B.YELLOW}{F.BLACK} WARNING: {S.R} You have chosen to scan a large amount of comments. The default API quota limit ends up")
print(f" around {F.YELLOW}10,000 comment deletions per day{S.R}. If you find more spam than that you will go over the limit.")
print(f" > Read more about the quota limits for this app here: {F.YELLOW}TJoe.io/api-limit-info{S.R}")
if userNotChannelOwner == True or moderator_mode == True:
print(f"{F.LIGHTCYAN_EX}> Note:{S.R} You may want to disable 'check_deletion_success' in the config, as this doubles the API cost! (So a 5K limit)")
confirm = choice("Is everything correct?", bypass=config['skip_confirm_video'])
if confirm == None:
return True # Return to main menu
miscData.channelOwnerID = channelID
miscData.channelOwnerName = channelTitle
# ============================================================================= ENTIRE CHANNEL ============================================================================================================
# If chooses to scan entire channel - Validate Channel ID
elif scanMode == "entireChannel":
numVideos = 1 # Using this variable to indicate only one loop of scanning done later
# While loop to get max scan number, not an integer, asks again
validInteger = False
if config: validConfigSetting = True
while validInteger == False:
try:
if validConfigSetting == True and config and config['max_comments'] != 'ask':
maxScanNumber = int(config['max_comments'])
else:
maxScanNumber = input(f"Enter the maximum {F.YELLOW}number of comments{S.R} to scan: ")
if str(maxScanNumber).lower() == "x":
return True # Return to main menu
maxScanNumber = int(maxScanNumber)
if maxScanNumber >= 100000:
print(f"\n{B.YELLOW}{F.BLACK} WARNING: {S.R} You have chosen to scan a large amount of comments. The default API quota limit ends up")
print(f" around {F.YELLOW}10,000 comment deletions per day{S.R}. If you find more spam than that you will go over the limit.")
print(f" > Read more about the quota limits for this app here: {F.YELLOW}TJoe.io/api-limit-info{S.R}")
if userNotChannelOwner == True or moderator_mode == True:
print(f"{F.LIGHTCYAN_EX}> Note:{S.R} You may want to disable 'check_deletion_success' in the config, as this doubles the API cost! (So a 5K limit)")
userChoice = choice("Do you still want to continue?")
if userChoice == None:
return True # Return to main menu
if maxScanNumber > 0:
validInteger = True # If it gets here, it's an integer, otherwise goes to exception
else:
print("\nInvalid Input! Number must be greater than zero.")
validConfigSetting = False
except:
print("\nInvalid Input! - Must be a whole number.")
validConfigSetting = False
miscData.channelOwnerID = CURRENTUSER.id
miscData.channelOwnerName = CURRENTUSER.name
# ================================================================================ COMMUNITY POST =====================================================================================================
elif scanMode == 'communityPost':
print(f"\nNOTES: This mode is {F.YELLOW}experimental{S.R}, and not as polished as other features. Expect some janky-ness.")
print(" > It is also much slower to retrieve comments, because it does not use the API")
confirm = False
while confirm == False:
communityPostInput = input("\nEnter the ID or link of the community post: ")
if str(communityPostInput).lower() == "x":
return True # Return to main menu
# Validate post ID or link, get additional info about owner, and useable link
isValid, communityPostID, postURL, postOwnerID, postOwnerUsername = validation.validate_post_id(communityPostInput)
if isValid == True:
print("\nCommunity Post By: " + postOwnerUsername)
if postOwnerID != CURRENTUSER.id:
userNotChannelOwner = True
print(f"\n{F.YELLOW}Warning:{S.R} You are scanning someone else's post. '{F.LIGHTRED_EX}Not Your Channel Mode{S.R}' Enabled.")
confirm = choice("Continue?")
if confirm == None:
return True # Return to main menu
else:
print("Problem interpreting the post information, please check the link or ID.")
miscData.channelOwnerID = postOwnerID
miscData.channelOwnerName = postOwnerUsername
# Checking config for max comments in config
if config['max_comments'] != 'ask':
validInteger = False
try:
maxScanNumber = int(config['max_comments'])
if maxScanNumber > 0:
validInteger = True
else:
pass
except:
pass
if validInteger == False:
print("\nInvalid max_comments setting in config! Number must be a whole number greater than zero.")
while validInteger == False:
maxScanInput = input(f"\nEnter the maximum {F.YELLOW}number of comments{S.R} to scan: ")
if str(maxScanInput).lower() == "x":
return True # Return to main menu
try:
maxScanNumber = int(maxScanInput)
if maxScanNumber > 0:
validInteger = True # If it gets here, it's an integer, otherwise goes to exception
else:
print("\nInvalid Input! Number must be a whole number greater than zero.")
except:
print("\nInvalid Input! - Must be a whole number greater than zero.")
# ==================================================================== RECENT COMMUNITY POSTS =============================================================================================================
# Recent Community Posts
elif scanMode == 'recentCommunityPosts':
print(f"\nNOTES: This mode is {F.YELLOW}experimental{S.R}, and not as polished as other features. Expect some janky-ness.")
print(" > It is also much slower to retrieve comments, because it does not use the API")
confirm = False
validEntry = False
validChannel = False
while validChannel == False:
# Get and verify config setting for channel ID
if config['channel_to_scan'] != 'ask':
if config['channel_to_scan'] == 'mine':
channelID = CURRENTUSER.id
channelTitle = CURRENTUSER.name
validChannel = True
break
else:
validChannel, channelID, channelTitle = validation.validate_channel_id(config['channel_to_scan'])
if validChannel == True:
break
else:
print("Invalid Channel ID or Link in config file!")
print(f"\nEnter a {F.YELLOW}channel ID or Link{S.R} to scan {F.LIGHTCYAN_EX}recent community posts{S.R} from")
print(f" > If scanning {F.YELLOW}your own channel{S.R}, just hit {F.LIGHTGREEN_EX}Enter{S.R}")
inputtedChannel = input("\nEnter Here: ")
if inputtedChannel == "":
channelID = CURRENTUSER.id
channelTitle = CURRENTUSER.name
validChannel = True
elif str(inputtedChannel).lower() == "x":
return True # Return to main menu
else:
validChannel, channelID, channelTitle = validation.validate_channel_id(inputtedChannel)
if CURRENTUSER.id != channelID:
userNotChannelOwner = True
# Get and print community posts
recentPostsListofDicts = community_downloader.fetch_recent_community_posts(channelID)
print("\n------------------------------------------------------------")
print(f"Retrieved {F.YELLOW}{len(recentPostsListofDicts)} recent posts{S.R} from {F.LIGHTCYAN_EX}{channelTitle}{S.R}")
print(f"\n Post Content Samples:")
for i in range(len(recentPostsListofDicts)):
# recentPostsListofDicts = {post id : post text} - Below prints sample of post text
print(f" {i+1}.".ljust(9, " ") + f"{list(recentPostsListofDicts[i].values())[0][0:50]}")
if userNotChannelOwner == True:
print(f"\n > {F.LIGHTRED_EX}Warning:{S.R} You are scanning someone else's post. {F.LIGHTRED_EX}'Not Your Channel Mode'{S.R} Enabled.")
print(f"\n{F.YELLOW}How many{S.R} of the most recent posts do you want to scan?")
inputStr = ""
while True:
if config['recent_videos_amount'] != 'ask' and inputStr == "":
inputStr = config['recent_videos_amount']
else:
inputStr = input("\nNumber of Recent Posts: ")
if str(inputStr).lower() == "x":
return True
try:
numRecentPosts = int(inputStr)
if numRecentPosts > len(recentPostsListofDicts):
print("Number entered is more than posts available. Will just scan all posts available.")
numRecentPosts = len(recentPostsListofDicts)
break
elif numRecentPosts <= 0:
print("Please enter a whole number greater than zero.")
else:
break
except ValueError:
print("Invalid Input! - Must be a whole number.")
miscData.channelOwnerID = channelID
miscData.channelOwnerName = channelTitle
# =============================================================================== OTHER MENU OPTIONS =============================================================================================
# Create config file
elif scanMode == "makeConfig":
result = files.create_config_file(configDict=config)
if str(result) == "MainMenu":
return True
# Check for latest version
elif scanMode == "checkUpdates":
files.check_lists_update(spamListDict)
files.check_for_update(version, updateReleaseChannel)
files.check_for_filter_update(filterListDict, silentCheck=True)
input("\nPress Enter to return to main menu...")
return True
# Recove deleted comments mode
elif scanMode == "recoverMode":
result = modes.recover_deleted_comments(config)
if str(result) == "MainMenu":
return True
elif scanMode == "commentList":
result = modes.delete_comment_list(config)
if str(result) == "MainMenu":
return True
elif scanMode == "tools":
result = user_tools.user_tools_menu(config)
if str(result) == "MainMenu":
return True
# ====================================================================================================================================================================================================
# ====================================================================================================================================================================================================
# Set Menu Colors
autoSmartColor = F.YELLOW
sensitiveColor = F.YELLOW
IDColor = F.LIGHTRED_EX
usernameColor = F.LIGHTBLUE_EX
textColor = F.CYAN
usernameTextColor = F.LIGHTBLUE_EX
asciiColor = F.LIGHTMAGENTA_EX
styleID = S.BRIGHT
styleOther = S.BRIGHT
a1 = ""
a2 = ""
# Change menu display & colors of some options depending on privileges
if userNotChannelOwner:
styleOther = S.DIM
a2 = f"{F.LIGHTRED_EX}*{S.R}" # a = asterisk
if not moderator_mode and userNotChannelOwner:
styleID = S.DIM
a1 = f"{F.LIGHTRED_EX}*{S.R}"
# User inputs filtering mode
print("\n-------------------------------------------------------")
print(f"~~~~~~~~~~~ Choose how to identify spammers ~~~~~~~~~~~")
print("-------------------------------------------------------")
print(f"{S.BRIGHT} 1. {S.R}{F.BLACK}{B.LIGHTGREEN_EX}(RECOMMENDED):{S.R} {S.BRIGHT}{autoSmartColor}Auto-Smart Mode{F.R}: Automatically detects multiple spammer techniques{S.R}")
print(f"{S.BRIGHT} 2. {sensitiveColor}Sensitive-Smart Mode{F.R}: Much more likely to catch all spammers, but with significantly more false positives{S.R}")
print(f"{a1}{styleID} 3. Enter Spammer's {IDColor}channel ID(s) or link(s){F.R}{S.R}")
print(f"{a2}{styleOther} 4. Scan {usernameColor}usernames{F.R} for criteria you choose{S.R}")
print(f"{a2}{styleOther} 5. Scan {textColor}comment text{F.R} for criteria you choose{S.R}")
print(f"{a2}{styleOther} 6. Scan both {usernameTextColor}usernames{F.R} and {textColor}comment text{F.R} for criteria you choose{S.R}")
print(f"{a2}{styleOther} 7. ASCII Mode: Scan usernames for {asciiColor}ANY non-ASCII special characters{F.R} (May cause collateral damage!){S.R}")
if userNotChannelOwner == True and moderator_mode == False:
print(f" {F.LIGHTRED_EX}*Note: With 'Not Your Channel Mode' enabled, you can only report matched comments while using 'Auto-Smart Mode' \n or 'Sensitive-Smart Mode'.{S.R}") # Based on filterModesAllowedforNonOwners
elif userNotChannelOwner == True and moderator_mode == True:
print(f" {F.LIGHTRED_EX}*Note: With 'Moderator Mode', you can Hold and/or Report using: 'Auto-Smart', 'Sensitive-Smart', and Channel ID modes.{S.R}")
# Make sure input is valid, if not ask again
validFilterMode = False
validFilterSubMode = False
filterSubMode = None
validConfigSetting = True
validConfigSetting = True