-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtunebot.py
More file actions
4020 lines (3399 loc) · 111 KB
/
tunebot.py
File metadata and controls
4020 lines (3399 loc) · 111 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
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 python2.7
# -*- coding: utf-8 -*-
# The friendly Tunebot! [ by James Koss phuein@gmail.com ] January 24th, 2016.
# -------------------------------------------------------------------
# Started as Qbot in PHP, which was extensively modified and fixed,
# And then translated into Python, using the core code from Pinychat.
# This is a tinychat.py extension module,
# Expecting a patched version of tinychat.py to try/except its functions,
# Which are patched into it as globals.
# Unicode support is troublesome, and therefore not official.
# Coded in Sublime Text 3 beta, latest.
import tinychat
import requests # http://www.python-requests.org/
try:
requests.packages.urllib3.disable_warnings() # For python < 2.7.9
except:
pass
import random
import traceback # https://docs.python.org/2/library/traceback.html
import re # https://docs.python.org/2/library/re.html
import threading
import time
import os
import sys
from urllib import quote_plus # Handles URLs.
# Return an unscaped string from an HTML string.
import HTMLParser
unescape = HTMLParser.HTMLParser().unescape
# Converts words to plural form.
from pluralize import pluralize
# The prefix for commands.
try:
CMD = tinychat.SETTINGS["CMD"]
except:
CMD = "!"
NICKNAME = "Tunebox" # Default nickname.
# Absolute directory, so no confusion when loaded as a module.
try:
LOCAL_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "")
except:
LOCAL_DIRECTORY = ""
# Holds further private modules and settings files.
SETTINGS_DIRECTORY = os.path.join(LOCAL_DIRECTORY, "settings", "")
START_TIME = time.time() # Remember when script began, for !uptime.
SC_MIN_ID = 100000 # Number representing the minimum value for SoundCloud track ID.
# Further settings are loaded with the settings file, and maybe otherwise.
CONTROLS = {
# Basics.
"greet": False, # Smartly respond to people saying greetings.
"defaultTopic": "", # Make it easier to revert topic.
"botActive": True, # Whether bot responds to commands, at all.
"playLock": False, # Doesn't let threads override each others startYT().
"ReadyMessage": None, # Message room when bot is ready (joinsdone().)
"BroadcastMessage": None, # Message room when someone cams up.
# Defenses.
"camclose": False,
"camban": False,
"autoban": False,
"autokick": False,
"autoforgive": False,
"banSnapshots": True,
"banNewusers": False,
"banGuests": True, # Catches fakers who change nick to guest-#.
"banPhones": {
"android": False,
"iphone": False
},
"banCaps": False,
# Extras.
"listUpdater": None, # Thread object for automatic list updater.
"settingsUpdater": None, # Thread object for automatic settings updater.
"filesUpdater": None,
"PrivateMode": False, # Kicks (not ban) any non-botter and non-modder.
"AccountMode": False, # ... any non-logged in user.
"gamesMode": True # Whether users can play games.
}
# Holds all the lists the bot users.
# All online lists will overwrite local ones!
class lists():
def __init__(self):
self.botters = [] # Users that can use basic bot commands.
self.ignored = [] # Users denied from using room commands.
self.commands = {} # Commands that play YT/SC.
self.playlists = {} # Play from preset playlists.
self.roomMessages = {} # Sends a message to the room.
self.asciiMessages = {} # Sends an ASCII message to the room.
self.randomMessages = {} # Sends a random-selection response message to the room.
self.dox = {} # Sends a DOX message to the room.
self.nickBans = [] # Nicknames (complex matching) to autoban.
self.accountBans = [] # Accounts to autoban.
self.autoForgives = [] # Nicknames & accounts (complex matching) to autoforgive.
self.banWords = [] # Words (complex matching) to autoban.
self.chucks = [] # Sends a random Chuck Norris joke to the room.
# Store previously loaded lists,
# to be able to filter out manually added items.
self.sessionLists = {
"botters": [],
"nickBans": [],
"accountBans": [],
"autoForgives": [],
"banWords": []
}
# Adds an item to a list. Expects valid list name.
# Won't add duplicates.
def addItem(self, lst, item):
# Get list by name.
l = getattr(self, lst)
if item not in l:
l.append(item)
# Match in session list.
if item not in self.sessionLists[lst]:
self.sessionLists[lst].append(item)
# Removes an item from a list. Expects valid list name.
# Does nothing, if not found.
def removeItem(self, lst, item):
# Get list by name.
l = getattr(self, lst)
if item in l:
l.remove(item)
# Match in session list.
if item in self.sessionLists[lst]:
self.sessionLists[lst].remove(item)
# Clearing a list means clearing the session list, only.
# The file list is reloaded, anyways, so clearing it has little effect.
# Expects only valid values!
def clearList(self, lst):
self.sessionLists[lst] = []
# Initialize.
LISTS = lists()
# Get extra (overriding) arguments from command-line.
try:
for item in sys.argv:
match = item.lower()
if match.find("bot=") == 0:
val = item.split("=")[1]
try:
CONTROLS["botActive"] = bool(int(val))
except:
print("Argument BOT must be 0 or 1, only.")
continue
# Display a ready message, when connected to room.
elif name == "ready":
try:
CONTROLS["ReadyMessage"] = bool(int(val))
except:
CONTROLS["ReadyMessage"] = val
if match.find("greet=") == 0:
val = item.split("=")[1]
try:
CONTROLS["greet"] = bool(int(val))
except:
print("Argument GREET must be 0 or 1, only.")
continue
if match.find("snap=") == 0:
val = item.split("=")[1]
try:
BAN_SNAPSHOTS = bool(int(val))
except:
print("Argument SNAP must be 0 or 1, only.")
continue
if match.find("private=") == 0:
val = item.split("=")[1]
try:
CONTROLS["PrivateMode"] = bool(int(val))
except:
print("Argument PRIVATE must be 0 or 1, only.")
continue
if match.find("games=") == 0:
val = item.split("=")[1]
try:
CONTROLS["gamesMode"] = bool(int(val))
except:
print("Argument GAMES must be 0 or 1, only.")
continue
except:
pass
# Get overrides from tinychat settings [file.]
for name in tinychat.SETTINGS:
if name in CONTROLS:
CONTROLS[name] = tinychat.SETTINGS[name]
# Timed thread checks for next track to play in list.
class party():
def __init__(self):
self.thread = None # Holds the partyCheck() thread.
self.room = None # Holds the calling room() reference.
self.list = [] # Currently queued items (tracks and playlists.)
self.history = [] # Previously queued (played and removed) tracks.
self.nextIndex = 0 # Mark the index to append() !next track into.
self.mode = False # Whether autoplay is active.
self.locked = False # True = Locks queue and plays for one track. 1 = Until toggled.
self.shuffle = False # Shuffle item selection in playlists.
# When active, plays the next item in the playlist.
def partyCheck(self):
while True:
time.sleep(5)
# Must be active, and have track in list.
if not self.mode or not self.list:
continue
# Room must be connected.
if not self.room.connected:
continue
# If nothing is currently playing.
if not tinychat.getTimeYT() and not tinychat.getTimeSC():
# Permenant lock. Wait for unlocking.
while self.locked is 1:
time.sleep(0.1)
# Reset regular lock.
if self.locked is True:
self.locked = False
# Each item is a track{} or track str().
itemType = type(self.list[0])
if itemType is dict:
# Remove single track{} from playlist.
item = self.list.pop(0)
track = item["track"]
skip = item["skip"]
else:
# Remove single track str() from playlist.
track = self.list.pop(0)
skip = 0
# Turn to proper item.
item = self.makeItem(track, skip)
# Verify skip value.
try:
skip = int(skip)
except:
skip = 0
# Update !next index.
if self.nextIndex > 0:
self.nextIndex -= 1
# Play next.
res = playTrack(self.room, track, skip)
# Skip tracks not tracked for duration, or other more severe failures.
if type(res) is str:
self.room._chatlog("Playlist queue skipping track " + track + ": " + res, True)
self.queueSkip(self.room)
continue
# Specifically, skip non-embeddable videos or non-streamable tracks.
# if type(res) is str:
# if "not embeddable" in res or "not streamable" in res:
# self.room._chatlog("Playlist queue skipping track "+track+
# " as non-embeddable/non-streamable...", True)
# self.queueSkip(self.room)
# continue
# Save in history, if played, and not same as last item in history.
if not self.history or self.history[-1] != item:
self.history.append(item)
time.sleep(3) # Extra time to catch up.
# Adds a single track [track, skip] or track-list[] to the playlist.
# nexted tracks get priority in the queue.
# Returns track position (not index) of added item.
def addItem(self, room, item, position=None, skip=0, nexted=False):
beforeLength = len(self.list)
# Position of adding.
if position is None:
position = beforeLength
else:
# Verify given position. Default to LAST.
try:
position = int(position)
if position < 0:
raise Exception()
except:
position = beforeLength
# A dict{}.
# Smart nexting. Overrides position!
if nexted:
position = self.nextIndex
self.nextIndex += 1
# An item within nextIndex adds one to it.
elif position <= self.nextIndex:
self.nextIndex += 1
track = {"track": item, "skip": skip}
self.list.insert(position, track)
# Activate, if first item(s) added.
if beforeLength == 0:
self.mode = True
# Return track number, not index.
return position + 1
# Removes a single track, or a range of tracks, by relative (track) indexes int().
# Returns str() info message.
def removeItem(self, room, track1=False, track2=False, inclusive=False):
# Nothing to remove with empty playlist.
l = self.getLength()
ls = str(l)
if not l:
return "No tracks to remove. The playlist is already *empty*."
# Range of tracks. Reverse, in case of, like: 7-3.
if type(track1) is int and type(track2) is int and track1 > track2:
t = track1
track1 = track2
track2 = t
# Verify index values.
if type(track1) is int:
if track1 < 0:
return "Track numbers must be 1 or greater!"
if track1 >= l:
return "The playlist only has " + ls + " " + pluralize("track", l) + " in it!"
if type(track2) is int:
if track2 < 0:
return "Track numbers must be 1 or greater!"
if track2 >= l:
track2 = l - 1
# Single track.
if track2 is False or (track1 == track2 != None):
# Pause queue.
PARTY.mode = False
# Remove it.
del self.list[track1]
# Update nextIndex.
if track1 < self.nextIndex:
self.nextIndex -= 1
# Unpause queue.
PARTY.mode = True
l -= 1
return ("Removed track #" + str(track1 + 1) + " from the playlist, with " +
str(l) + " " + pluralize("track", l) + " left. (Next slot at #" +
str(self.nextIndex + 1) + ")")
# Tracks range.
if track1 == track2 == None:
# Simple case of removing entire playlist.
self.list = []
self.nextIndex = 0
else:
# Convert None to index.
if track1 is None:
track1 = 0
if track2 is None:
track2 = l - 1
# Update index to include last item.
if inclusive:
track2 += 1
# Pause queue.
PARTY.mode = False
# Delete items from playlist.
for i in range(track2 - 1, track1 - 1, -1):
# Null it.
self.list[i] = None
# Update nextIndex.
if i < self.nextIndex:
self.nextIndex -= 1
# Remove emptied tracks.
self.list = filter(None, self.list)
# Unpause queue.
PARTY.mode = True
# Revert for both-case handling.
if inclusive:
track2 -= 1
# Set for verbosity.
if track1 == None or track1 == 0:
track1 = "*start*"
else:
track1 = "#" + str(track1 + 1)
if track2 == None or track2 == l - 1:
track2 = "*end*"
else:
track2 = "#" + str(track2 + 1)
l = self.getLength()
return ("Removed tracks from " + track1 + " to " + track2 +
" from the playlist, with " + str(l) + " " + pluralize("track", l) +
" left. (Next slot at #" + str(self.nextIndex + 1) + ")")
# Close all currently playing YT and SC,
# so queue can continue to the next item.
def queueSkip(self, room):
# Close current, if any playing.
if tinychat.getTimeYT():
room.closeYT()
if tinychat.getTimeSC():
room.closeSC()
# Returns the number int() of tracks in the list, in total.
def getLength(self):
return len(self.list)
# Converts a keyword into a track index int(),
# or convert track position number into index int().
# Returns None if no match.
def keywordPosition(self, word):
if word in {"last", "end"}:
return self.getLength() - 1
if word in {"first", "next"}:
return 0
try:
n = int(word) - 1
return n
except:
pass
# Returns a playlist item dict.
def makeItem(self, track, skip=0):
return {"track": track, "skip": skip}
# Initialize.
PARTY = party()
# Games module.
try:
import games as GAMES
except:
GAMES = None
class tokes():
def __init__(self):
self.room = None
self.mode = False
self.paused = False
self.announce = 0 # Interval in seconds, announcing tokes incoming. Reusable.
self.announceCheck = 0
self.joined = [] # Nicks who joined in tokes.
self.start = 0 # time() started.
self.end = 0 # seconds from start() to end. Reusable.
self.thread = threading.Thread(target=self.count, args=())
self.thread.daemon = True
self.thread.start()
# Returns the time in minutes, until tokes.
# Part of minute is a minute.
def until(self):
t = int(time.time())
# Gets best minute approximation.
d = int(round(float(self.start+self.end - t) / 60))
# Left time minimum 1 minute rounding.
if d == 0:
d = 1
return d
# Start a new count!
# end is in minutes -> seconds.
# announce is in minutes -> seconds. Falsy value is no announcements.
def startCount(self, room, end, announce=0):
self.room = room
self.mode = True
t = int(time.time())
self.announce = int(announce)*60
self.announceCheck = t + self.announce
self.joined = []
self.start = t
self.end = int(end) * 60
# Clears out current count.
def clearOut(self):
self.room = None
self.mode = False
self.announceCheck = 0
self.joined = []
self.start = 0
# At end, announces it's time for tokes!
def count(self):
while True:
time.sleep(1)
if not self.mode:
time.sleep(5)
continue
t = time.time()
# Count finished!
if t > self.start+self.end:
start = int((t - self.start) / 60)
if len(self.joined) > 1:
if len(self.joined) == 2:
# Just one other person joined.
joined = self.joined[1]
else:
# Many joined.
joined = ""
j = 0
for name in self.joined[1:]:
if j == len(self.joined) - 2:
joined += "and " + name
else:
joined += name + ", "
j += 1
self.room.notice(self.joined[0] + " called tokes " + str(start) +
" " + pluralize("minute", start) +
" ago, and *" + joined + "* joined in. *TOKES NOW!*")
else:
# Lonely toke.
self.room.notice(self.joined[0] + ", you called tokes " + str(start) +
" " + pluralize("minute", start) +
" ago, and nobody joined in. Who cares... *TOKES NOW!*")
# Clear out counter.
self.clearOut()
continue
# Optional periodical announcements.
if self.announce and t > self.announceCheck:
self.announceCheck = t + self.announce
start = int((t - self.start) / 60)
self.room.notice(self.joined[0] + " called tokes " + str(start) +
" " + pluralize("minute", start) + " ago. Y'all better *!JOIN* in.")
# Initalize.
TOKES = tokes()
# Return an online or local file converted to a list or dictionary:
# Parts = 3: [cmd: [method, msg], ...] 2: [cmd: msg] 1: [item].
# Ignores empty lines and // comments. online=True for online files.
# One per line. Indexes 0 and 1 are forced lower-case.
# word Takes only one word per line. youtubes Allows many command words, lowercased.
# Returns None on failure. Returns empty list or dict, if no content.
def listLoader(link, online=False, parts=1, word=False, youtubes=False, unicode=False):
if not link:
return
try:
# Online file.
if online:
raw = requests.get(link, timeout=15)
if not unicode:
lines = raw.text.encode("ascii", "ignore").splitlines()
else:
lines = raw.text.splitlines()
try:
lines = lines.decode("utf-8", "replace")
except:
pass
# Local file.
else:
with open(link) as raw:
if not unicode:
lines = raw.read().encode("ascii", "ignore").splitlines()
else:
lines = raw.read().splitlines()
try:
lines = lines.decode("utf-8", "replace")
except:
pass
except:
return
# Remove BOM character. Incomplete.
# https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
# codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE, codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE
if unicode:
try:
if lines[0][0] in {u'\ufeff', u'\ufffe'}:
raise Exception()
except:
lines[0] = lines[0][1:]
# Treat Google Docs page-break string as empty line.
lines = map(lambda x: '' if x == '________________' else x, lines)
result = None
if parts == 1:
result = []
for line in lines:
# Remove whitespaces.
line = line.strip()
# Skip comments and empty lines.
if line.find("//") == 0 or line == "":
continue
# Only grab a word.
if word:
line = line.split()[0]
# Otherwise, add it.
result.append(line)
if parts == 2:
result = {}
for line in lines:
# Remove whitespaces.
line = line.strip()
# Skip comments and empty lines.
if line.find("//") == 0 or line == "":
continue
# Get words.
words = line.split()
count = len(words)
# Must have the command and msg.
if count < 2:
continue
# Command must be lower-case.
# Remove cmd from list.
cmd = words.pop(0).lower()
msg = " ".join(words)
# Overrides.
result[cmd] = msg
if parts == 3:
result = {}
for line in lines:
# Remove whitespaces.
line = line.strip()
# Skip comments and empty lines.
if line.find("//") == 0 or line == "":
continue
# Get words.
words = line.split()
count = len(words)
# For youtube video playlists.
if youtubes:
# Must have at least a command and video.
if count < 2:
continue
# Optional skip.
try:
skip = int(words[-1])
# SoundCloud IDs are large numbers.
if skip > SC_MIN_ID:
raise Exception()
del words[-1]
except:
skip = 0
# Video ID or link.
vid = words.pop()
# Optional many cmd words.
for word in words:
# Overrides.
result[word] = [vid, skip]
# Next.
continue
# Must have the command, method, and msg.
if count < 3:
continue
# Command and method must be lower-case.
# Remove cmd and method from list.
cmd = words.pop(0).lower()
method = words.pop(0).lower()
msg = " ".join(words)
# Overrides.
result[cmd] = [method, msg]
# Success.
return result
# Load botters that can access the bot.
filename = "botters.txt"
result = listLoader(SETTINGS_DIRECTORY + filename, word=True)
if result is None:
# print("Failed to load the Botters list from " + filename + ".")
pass
else:
LISTS.botters = result
# Load more botters from online list.
BottersText = {}
try:
BottersText = tinychat.SETTINGS["Botters"]
result = listLoader(BottersText, online=True, word=True)
if result is None:
# print("Failed to load the Extra Botters list from " + BottersText + ".")
pass
else:
LISTS.botters = result
except (SystemExit, KeyboardInterrupt):
sys.exit("Killed while loading lists...")
except:
pass
# Load Youtube commands from file.
filename = "youtubes.txt"
result = listLoader(SETTINGS_DIRECTORY + filename, parts=3, youtubes=True)
if result is None:
# print("Failed to load the Youtubes list from " + filename + ".")
pass
else:
LISTS.commands = result
# Load more Youtube commands from online file.
ExtraYTsText = {}
try:
ExtraYTsText = tinychat.SETTINGS["Commands"]
result = listLoader(ExtraYTsText, online=True, parts=3, youtubes=True)
if result is None:
# print("Failed to load the Extra Youtubes list from " + ExtraYTsText + ".")
pass
else:
LISTS.commands = result
except (SystemExit, KeyboardInterrupt):
sys.exit("Killed while loading lists...")
except:
pass
# Load the Playlists from online.
PlaylistsText = {}
try:
PlaylistsText = tinychat.SETTINGS["Playlists"]
except:
pass
def getPlaylists(PlaylistsText):
if not PlaylistsText:
return
try:
raw = requests.get(PlaylistsText, timeout=15)
lines = raw.text.encode("ascii", "ignore").splitlines()
except:
return
curPL = False
l = {}
for line in lines:
# Remove whitespaces.
line = line.strip()
# Skip comments.
if line.find("//") == 0:
continue
# Empty line marks end of playlist.
if line == "":
curPL = False
continue
# Get words.
parts = line.split()
# Start new playlist.
if curPL is False:
curPL = parts[0].lower()
l[curPL] = []
continue
# Video followed by Title, with optional skip in seconds.
count = len(parts)
if count >= 2:
# Remove video from list.
vid = parts.pop(0)
# Optional skip.
try:
skip = int(parts[-1])
if skip < 1:
raise Exception()
except:
skip = 0
# Reconstruct title.
title = " ".join(parts)
else:
# Video without title, default to video as title.
vid = parts.pop(0)
title = vid
skip = 0
# Add to playlist.
l[curPL].append([vid, title, skip])
# Apply list.
LISTS.playlists = l
getPlaylists(PlaylistsText)
# Dox commands from file. TODO: Replace with listLoader().
filename = "dox.txt"
doxLines = []
try:
with open(SETTINGS_DIRECTORY + filename) as doxFile:
doxLines = doxFile.read().encode("ascii", "ignore").splitlines()
except (SystemExit, KeyboardInterrupt):
sys.exit("Killed while loading lists...")
except:
# print("Failed to load the DOX list from " + filename + ".")
pass
curDox = False
d = {}
for line in doxLines:
# Skip comments.
if line.find("//") == 0: continue
# End of person.
if line == "":
curDox = False
continue
# New person.
if not curDox:
curDox = line
d[curDox] = []
continue
# Add msgs for person.
d[curDox].append(line)
# Apply list.
LISTS.dox = d
# Load more DOX from online.
moreDoxText = {}
try:
moreDoxText = tinychat.SETTINGS["DOX"]
except:
pass
def getExtraDOX(moreDoxText):
if not moreDoxText:
return
try:
raw = requests.get(moreDoxText, timeout=15)
lines = raw.text.encode("ascii", "ignore").splitlines()
except:
return
curDox = False
d = {}
for line in lines:
# Skip comments.
if line.find("//") == 0: continue
# End of person.
if line == "":
curDox = False
continue
# New person.
if not curDox:
curDox = line
d[curDox] = []
continue
# Add msgs for person. Override from file.
d[curDox].append(line)
# Apply list.
LISTS.dox = d
getExtraDOX(moreDoxText)
# Autobans from file.
filename = "autoban.txt"
result = listLoader(SETTINGS_DIRECTORY + filename)
if result is None:
# print("Failed to load the AUTOBANS list from " + filename + ".")
pass
else:
for name in result:
# Account ban.
if name[0] == "@":
n = name[1:]
if n not in LISTS.accountBans:
LISTS.accountBans.append(n)
# Nick ban.
else:
if name not in LISTS.nickBans:
LISTS.nickBans.append(name)
# Load more autobans from online list.
AutobansText = {}
try:
AutobansText = tinychat.SETTINGS["AutoBans"]
result = listLoader(AutobansText, online=True, word=True)
if result is None:
# print("Failed to load the Extra Autobans list from " + AutobansText + ".")
pass
else:
# Override local lists.
LISTS.accountBans = []
LISTS.nickBans = []
for name in result:
# Account ban.
if name[0] == "@":
n = name[1:]
if n not in LISTS.accountBans:
LISTS.accountBans.append(n)
# Nick ban.
else:
if name not in LISTS.nickBans:
LISTS.nickBans.append(name)
except (SystemExit, KeyboardInterrupt):
sys.exit("Killed while loading lists...")
except:
pass
# Autoforgives from file.
filename = "autoforgive.txt"
result = listLoader(SETTINGS_DIRECTORY + filename)
if result is None:
# print("Failed to load the AUTOFORGIVES list from " + filename + ".")
pass
else:
LISTS.autoForgives = result
# Load more autoforgives from online list.
AutoforgivesText = {}
try:
AutoforgivesText = tinychat.SETTINGS["AutoForgives"]
result = listLoader(AutoforgivesText, online=True, word=True)
if result is None:
# print("Failed to load the Extra Autoforgives list from " + AutoforgivesText + ".")
pass
else:
LISTS.autoForgives = result
except (SystemExit, KeyboardInterrupt):