-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsalty_bot.py
1765 lines (1531 loc) · 75.3 KB
/
salty_bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
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 -*-
import datetime
import difflib
import json
import logging
import Queue as Q
import random
import re
import socket
import sys
import threading
import time
import traceback
import isodate
import pytz
import requests
import modules.irc as irc
import salty_listener as SaltyListener
RESTART = "<restart>"
CHECK = "<check threads>"
UPDATE = "<update>"
TYPE = 0
DATA = 1
interface = Q.Queue()
#Set up all the global variables
with open('general_config.json', 'r') as data_file:
general_config = json.load(data_file, encoding='utf-8')
# API keys and sensitive info
lol_api_key = general_config['general_info']['lol_api_key']
youtube_api_key = general_config['general_info']['youtube_api_key']
osu_api_key = general_config['general_info']['osu']['osu_api_key']
osu_irc_nick = general_config['general_info']['osu']['osu_irc_nick']
osu_irc_pass = general_config['general_info']['osu']['osu_irc_pass']
db_url = general_config['general_info']['db_url']
default_nick = general_config['general_info']['default_nick']
default_oauth = general_config['general_info']['default_oauth']
# Debugging prints more stuff, development may do more in the future
debuging = general_config["general_info"]["debugging"]
development = general_config["general_info"]["development"]
# IP and port to listen for the website to talk to it when there is an update to the data
web_listen_ip = general_config["general_info"]["web_listen_ip"]
web_listen_port = general_config['general_info']["web_listen_port"]
web_secret = general_config["general_info"]["web_secret"]
# super users are used for bot breaking commands and beta commands
SUPER_USER = general_config['general_info']['super_users']
logging.basicConfig(
filename='debug.log',
filemode='w',
level=logging.DEBUG,
format="[%(levelname)s %(asctime)s] %(message)s",
datefmt="%m-%d %H:%M:%S"
)
logging.getLogger("requests").setLevel(logging.WARNING)
class SaltyBot(object):
# Possible values for "user-type" tag in messages
elevated_user = ["staff", "admin", "global_mod", "mod"]
def __init__(self, config_data, debug = False, irc_obj = None):
# Default rate limits for non-mods is 20 messages per 30 seconds.
# Start with this and elevate if find as mod
self.message_limit = 30
self.is_mod = False
# If the bot does not have a nickname set use the nick "TheSaltyBot"
# Oauth cannot be set unless it is valid, so only check for that
if config_data["bot_oauth"] == None:
config_data["bot_nick"] = default_nick
config_data["bot_oauth"] = default_oauth
self.twitch_nick = config_data["bot_nick"]
self.twitch_oauth = config_data["bot_oauth"]
if not self.twitch_oauth.startswith("oauth:"):
self.twitch_oauth = "oauth:" + self.twitch_oauth
self.__DB = debug
# Used to stop the bot from reviving itself if the user wishes for it to leave
self.running = True
# Used for social message tracking
self.messages_received = 0
# Used to stop us from getting globaled
self.rate_limit = 0
# Session key from the website, used to change settings and add/del stuff
self.session = config_data["session"]
# Associated ID of the user on the website
self.user_id = config_data["id"]
# Keep the rest of the data around just in case
self.config_data = config_data
# Only create a new IRC connection if the old one is toast
if not irc_obj:
self.irc = irc.IRC("irc.twitch.tv", 6667, self.twitch_nick, self.twitch_oauth)
else:
self.irc = irc_obj
self.channel = config_data["twitch_name"]
if config_data["speedruncom_nick"]:
self.speedruncom_nick = config_data["speedruncom_nick"].lower()
else:
self.speedruncom_nick = self.channel
# Various channel information from twitch
self.game = ""
self.title = ""
self.time_start = None
self.stream_online = False
# Active commands, custom commands, and commands that are admin only
self.commands = []
self.admin_commands = []
self.custom_commands = []
# User blacklist, bot will ignore all users in this list
self.blacklist = []
# Voting system built into the bot
self.votes = {}
# Highlight timestamp system
self.to_highlight = []
self.review = {"quote": [], "pun": []}
# Make sure quotes/puns aren't used twice in a row
self.last_text = {"quote": "", "pun": ""}
self.t_trig = None
with open('blacklists/{}_blacklist.txt'.format(self.channel), 'a+') as data_file:
blacklist = data_file.readlines()
for i in blacklist:
self.blacklist.append(i.split('\n')[0])
# Command rate limiting
self.command_times = {}
self.custom_command_times = {}
def start(self):
# Bots are started by calling this method after being initializedd
self.thread = threading.Thread(target=self.twitch_run)
self.thread.setDaemon(True)
self.thread.start()
return self.thread
def twitch_info(self, game, title, live, online_status):
# Called by the auto-updater only, sets the game playing, current title,
# if the stream is live, and when it started
if not game:
game = ""
if not title:
title = ""
self.game = game.lower()
self.game_normal = game
self.title = title.lower()
self.time_start = live
self.stream_online = online_status
def twitch_connect(self):
# Connect to Twitch IRC for new IRC instances
if not self.irc.connected:
if self.__DB:
print "Joining {} as {}.\n".format(self.channel, self.twitch_nick)
try:
#If it fails to conenct try again in 60 seconds
self.irc.connect()
self.irc.recv(4096)
except Exception:
print '{} failed to connect.'.format(self.channel)
traceback.print_exc(limit=4)
time.sleep(60)
self.twitch_connect()
# Request the needed capabilites to function correctly
self.irc.capability("twitch.tv/tags twitch.tv/commands")
self.irc.recv(1024)
self.irc.join(self.channel)
time.sleep(.5)
self.irc.recv(4096)
else:
if self.__DB:
print "{} already connected.\n".format(self.channel)
def twitch_commands(self):
# Initialize all commands
self.command_times["!bot_info"] = {"last": 0, "limit": 300}
self.commands.append("!bot_info")
self.command_times["!help"] = {"last": 0, "limit": 2}
self.commands.append("!help")
for i in self.config_data["commands"]:
if i["on"]:
curr_com = "!" + i["name"]
if i["admin"]:
self.admin_commands.append(curr_com)
else:
self.commands.append(curr_com)
self.command_times[curr_com] = {"last": 0, "limit": i["limit"] or 30}
# Setup the social feature if active
if self.config_data["social_active"]:
self.command_times["social"] = {"time_last": int(time.time()),
"messages": self.config_data["social_messages"] or 0,
"messages_last": self.messages_received,
"time": self.config_data["social_time"] or 0}
self.social_text = self.config_data["social_output"]
# Setup the toobou feature if active
if self.config_data["toobou_active"]:
self.t_trig = self.config_data["toobou_trigger"]
self.command_times["toobou"] = {"trigger": self.t_trig,
"last": 0,
"limit": self.config_data["toobou_limit"] or 1}
# Initialize all custom commands
for i in self.config_data["custom_commands"]:
if i["on"]:
self.custom_commands.append("!{}".format(i["trigger"]))
self.custom_command_times["!{}".format(i["trigger"])] = {"last": 0,
"limit": i["limit"] or 30,
"output": i["output"],
"admin": i["admin"]}
def live_commands(self):
# Remove any commands that would not currently work when !commands is used
# Type cast to not mess with the original lists
active_commands = list(self.commands) + list(self.custom_commands)
admin_commands_tmp = list(self.admin_commands)
if not self.time_start:
try:
active_commands.remove('!uptime')
except Exception:
pass
if self.config_data["voting_active"] and self.votes:
active_commands.append("!checkvotes")
else:
try:
active_commands.remove("!vote")
except Exception:
pass
if self.config_data["voting_active"]:
if self.config_data["voting_mods"]:
admin_commands_tmp.append("!createvote")
admin_commands_tmp.append("!endvote")
if self.game == '':
try:
active_commands.remove('!leaderboard')
except Exception:
pass
if self.game != 'osu!':
try:
active_commands.remove('!rank')
except Exception:
pass
try:
active_commands.remove('!song')
except Exception:
pass
if self.game != 'league of legends':
try:
active_commands.remove('!runes')
except Exception:
pass
try:
active_commands.remove('!masteries')
except Exception:
pass
if 'race' not in self.title and 'racing' not in self.title:
try:
active_commands.remove('!race')
except Exception:
pass
command_string = ', '.join(sorted(active_commands))
if self.admin_commands:
command_string += " | Mod Only Commands: " + ", ".join(sorted(admin_commands_tmp))
if command_string == '!bot_info, !commands':
self.twitch_send_message('There are no current active commands.', '!commands')
else:
self.twitch_send_message(command_string, '!commands')
def clear_limiter(self):
# Called every 30 seconds by the helper thread
# Resets how many messages have been sent
self.rate_limit = 0
def twitch_send_message(self, response, command = None):
# Sending any message to chat goes through this function
try:
response = response.encode('utf-8')
except Exception:
pass
if response.startswith('/me') or response.startswith('.me'):
# Grant exception for /me because it can't do any harm
pass
elif response.startswith('.') or response.startswith('/'):
# Prevent people from issuing server commands since bot is usually mod (aka /ban)
response = "Please stop trying to abuse me BibleThump (messages cannot start with '/' or '.')"
command = ''
if self.rate_limit < self.message_limit:
# Make sure we don't get globaled (this is a re-occuring theme), send message if under limit
self.irc.privmsg(self.channel, response)
self.rate_limit += 1
else:
print "{} has exceeded the IRC rate limit".format(self.channel)
return
if self.__DB == True:
try:
db_message = '#' + self.channel + ' ' + self.twitch_nick + ": " + response.decode('utf-8')
db_message = db_message.encode('utf-8')
print datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S] ') + db_message
except Exception:
print("Message contained unicode, could not display in terminal\n\n")
if command:
# Update when the command was last used for rate limiting
self.command_times[command]['last'] = int(time.time())
def command_check(self, c_msg, command):
# Determines if a user can use a given command, and the command is off cooldown
# Super users and channel owners do bypass cooldowns and admin
if command in self.commands or command in self.admin_commands:
if c_msg["sender"] == self.channel or c_msg["sender"] in SUPER_USER:
return True
if command in self.admin_commands:
if c_msg["tags"]["user-type"] in self.elevated_user:
return True
else:
if self.time_check(command):
return True
return False
def time_check(self, command):
# Determines if the command is off cooldown, True=available False=cooldown
return int(time.time()) - self.command_times[command]['last'] >= self.command_times[command]['limit']
def api_caller(self, url, headers = None):
# Call JSON api's for other functions
if self.__DB: print url
try:
data = requests.get(url, headers=headers)
if data.status_code == 200:
data_decode = data.json()
return data_decode
else:
print data
print data.text
return False
except Exception:
traceback.print_exc(limit=2)
return False
def osu_api_user(self, c_msg):
# Retrieve basic information about the osu player (!rank)
try:
user = c_msg["message"].split("rank ")[1]
except IndexError:
user = ""
osu_nick = user or self.config_data["osu_nick"]
url = 'https://osu.ppy.sh/api/get_user?k={}&u={}'.format(osu_api_key, osu_nick)
data_decode = self.api_caller(url)
if data_decode == False:
return
try:
data_decode = data_decode[0]
except IndexError:
self.twitch_send_message('User with name "{}" not found.'.format(user))
return
username = data_decode['username']
level = data_decode['level']
level = round(float(level))
level = int(level)
accuracy = data_decode['accuracy']
accuracy = round(float(accuracy), 2)
pp_rank = "{:,}".format(int(data_decode['pp_rank']))
response = '{} is level {} with {}% accuracy and ranked {}.'.format(username, level, accuracy, pp_rank)
self.twitch_send_message(response)
def osu_song_display(self):
url = 'https://leagueofnewbs.com/api/users/{}/songs'.format(self.channel)
data_decode = self.api_caller(url)
if data_decode:
self.twitch_send_message(data_decode["song"], "!song")
def osu_link(self, c_msg):
# Sends beatmaps linked in chat to you on osu, and then displays the map title and author in chat
osu_nick = self.config_data["osu_nick"]
if c_msg["message"].find('osu.ppy.sh/s/') != -1:
osu_number = 's=' + c_msg["message"].split('osu.ppy.sh/s/')[-1].split(' ')[0]
elif c_msg["message"].find('osu.ppy.sh/b/') != -1:
osu_number = 'b=' + c_msg["message"].split('osu.ppy.sh/b/')[-1].split(' ')[0]
osu_send_message(osu_nick, c_msg["message"], c_msg["sender"])
url = 'https://osu.ppy.sh/api/get_beatmaps?k={}&{}'.format(osu_api_key, osu_number)
data_decode = self.api_caller(url)
if data_decode == False:
self.twitch_send_message("There was a problem retrieving the map info from the Osu! API")
return
data_decode = data_decode[0]
response = '{} - {}, mapped by {}'.format(data_decode['artist'], data_decode['title'], data_decode['creator'])
self.twitch_send_message(response)
def format_sr_time(self, f_time):
# Format time in a pretty H:M:S, but removing hours if 0 and leading 0 in minutes
m, s = divmod(float(f_time), 60)
h, m = divmod(int(m), 60)
s = round(s, 2)
if s < 10:
s = '0' + str(s)
if m < 10:
m = '0' + str(m)
sr_time = '{}:{}:{}'.format(int(h), m, s)
if sr_time.endswith(".0"):
sr_time = sr_time[:-2]
if sr_time.startswith("0:"):
sr_time = sr_time[2:]
if sr_time.startswith("0"):
sr_time = sr_time[1:]
if self.__DB:
print sr_time
return sr_time
def get_number_suffix(self, number):
# Find the proper suffix for #'s'
return "th" if number in [11, 12, 13] else {1: "st", 2: "nd", 3: "rd"}.get(number % 10, "th")
def get_diff_ratio(self, user_supplied, checking_against):
# Retrieve the ratio of how close 2 strings match (fuzzy matching of category names since they have dumb names)
diff = difflib.SequenceMatcher(lambda x: x == " " or x == "_", user_supplied, checking_against)
return diff.ratio()
def find_category_title(self, game_categories, stream_title):
# Takes list of possible categories, and the stream title
# Returns True/False if successful, and the string with either the category or the error response
categories_in_title = []
category_position = {}
for i in game_categories:
if i.lower() in stream_title:
categories_in_title.append(i)
categories_in_title = list(set(categories_in_title))
if len(categories_in_title) == 0:
response = "It appears that no categories exist in the title {additional_info}"
return False, response
elif len(categories_in_title) == 1:
return True, categories_in_title[0]
else:
for j in categories_in_title:
category_position[j] = self.title.find(j.lower())
min_value = min(category_position.itervalues())
min_keys = [k for k in category_position if category_position[k] == min_value]
return True, sorted(min_keys, key=len)[-1]
def find_category_string(self, game_categories, string_search):
# Find the category given by a user
for i in game_categories:
if i.lower() == string_search.lower():
return True, i
best_ratio = {}
for i in game_categories:
ratio = self.get_diff_ratio(string_search.lower(), i.lower())
if ratio > .6:
best_ratio[i] = ratio
try:
return True, max(best_ratio, key=best_ratio.get)
except ValueError:
response = "I'm sorry, but I could not find the category supplied {additional_info}"
return False, response
def pb_retrieve(self, c_msg):
# Retrieves the users best time from speedrun.com (!pb)
msg_split = c_msg["message"].split(' ', 3)
infer_category = False
try:
url = "http://www.speedrun.com/api_records.php?user={}".format(msg_split[1])
user_name = msg_split[1]
try:
url += "&game=" + msg_split[2]
try:
msg_split[3]
except IndexError:
if self.title != '':
infer_category = True
else:
self.twitch_send_message("Please specify a category to look up.")
return
except IndexError:
if self.game != '':
url += "&game=" + self.game
infer_category = True
else:
self.twitch_send_message("Please specify a game shortcode to look up on speedrun.com")
return
except IndexError:
if self.game != '' and self.title != '':
url = "http://speedrun.com/api_records.php?user={}&game={}".format(self.speedruncom_nick, self.game)
user_name = self.speedruncom_nick
infer_category = True
else:
response = "Please either provide a player, game, and category or wait for the streamer to go live."
self.twitch_send_message(response, "!pb")
return
game_data = self.api_caller(url)
if game_data == False:
self.twitch_send_message("There was an error fetching info from speedrun.com", "!pb")
return
try:
sr_game = dict(game_data).keys()[0]
except (TypeError, IndexError):
self.twitch_send_message("This game/user does not seem to exist on speedrun.com")
return
game_cats = game_data[sr_game].keys()
if infer_category:
success, response_string = self.find_category_title(game_cats, self.title)
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the user's speedrun.com profile."), "!pb")
return
else:
active_cat = response_string
else:
success, response_string = self.find_category_string(game_cats, msg_split[3])
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the user's speedrun.com profile."), "!pb")
return
else:
active_cat = response_string
cat_record = game_data[sr_game][active_cat]
pb_time = self.format_sr_time(cat_record["time"])
try:
pb_time = self.format_sr_time(cat_record['time'])
except (TypeError, KeyError):
try:
pb_time = self.format_sr_time(cat_record["timewithloads"])
except (TypeError, KeyError):
pb_time = ""
try:
pb_ingame = self.format_sr_time(cat_record["timeigt"])
if pb_time:
pb_time = "{0} real time and {1} ingame time ".format(pb_time, pb_ingame)
else:
pb_time = pb_ingame
except KeyError:
pb_ingame = ""
place = str(cat_record["place"]) + self.get_number_suffix(int(cat_record["place"]))
msg = "{0}'s pb for {1} {2} is {3}. They are ranked {4} on speedrun.com".format(user_name.capitalize(), sr_game, active_cat, pb_time, place)
self.twitch_send_message(msg, "!pb")
def wr_retrieve(self, c_msg):
#Find the categories that are on file in the title, and then if more than one exist pick the one located earliest in the title
msg_split = c_msg["message"].split(' ', 2)
infer_category = False
try:
url = "http://www.speedrun.com/api_records.php?game=" + msg_split[1]
try:
msg_split[2]
except IndexError:
if self.title != "":
infer_category = True
else:
self.twitch_send_message("Please provide a category to search for.")
return
except IndexError:
if self.game != "" and self.title != "":
url = "http://www.speedrun.com/api_records.php?game=" + self.game
infer_category = True
else:
self.twitch_send_message("Please either provide a game and category or wait for the streamer to go live.")
return
game_records = self.api_caller(url)
if game_records == False:
self.twitch_send_message("There was an error fetching info from speedrun.com")
return
try:
sr_game = dict(game_records).keys()[0]
except (TypeError, IndexError):
self.twitch_send_message("This game/user does not seem to exist on speedrun.com", '!wr')
return
game_cats = game_records[sr_game].keys()
if infer_category:
success, response_string = self.find_category_title(game_cats, self.title)
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the game's speedrun.com page."), "!wr")
return
else:
active_cat = response_string
else:
success, response_string = self.find_category_string(game_cats, msg_split[2])
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the games's speedrun.com page."), "!wr")
return
else:
active_cat = response_string
cat_record = game_records[sr_game][active_cat]
try:
wr_time = self.format_sr_time(cat_record['time'])
except (TypeError, KeyError):
try:
wr_time = self.format_sr_time(cat_record["timewithloads"])
except (TypeError, KeyError):
wr_time = ""
try:
wr_ingame = self.format_sr_time(cat_record["timeigt"])
if wr_time:
wr_time = "{0} real time and {1} ingame time ".format(wr_time, wr_ingame)
else:
wr_time = wr_ingame
except KeyError:
wr_ingame = ""
msg = "The current world record for {0} {1} is {2} by {3}.".format(sr_game, active_cat, wr_time, cat_record['player'])
if cat_record['video']:
msg += " Video: {0}".format(cat_record['video'])
if cat_record["splitsio"]:
msg += " Splits: {0}".format(cat_record["splitsio"])
self.twitch_send_message(msg, '!wr')
def leaderboard_retrieve(self):
#Retrieve leaderboard for game as set on Twitch
game_no_spec = re.sub(' ', '_', self.game_normal)
game_no_spec = re.sub("[:]", '', game_no_spec)
url = 'http://speedrun.com/' + game_no_spec
self.twitch_send_message(url, '!leaderboard')
def splits_check(self, c_msg):
# Get pbs from splits.io, find the correct category
msg_split = c_msg["message"].split(' ', 3)
if msg_split[0] != "splits":
return
game_type = "name"
infer_category = False
try:
url = "https://splits.io/api/v3/users/{}/pbs".format(msg_split[1])
user_name = msg_split[1]
try:
input_game = msg_split[2]
game_type = "shortname"
try:
category = msg_split[3]
except IndexError:
if self.title != "":
infer_category = True
else:
self.twitch_send_message("Please wait for the streamer to go live or specify a category.")
return
except IndexError:
if self.game != "" and self.title != "":
input_game = self.game
infer_category = True
else:
self.twitch_send_message("Please wait for the streamer to go live or specify a game and category.")
return
except IndexError:
if self.game != "" and self.title != "":
url = "https://splits.io/api/v3/users/{}/pbs".format(self.channel)
user_name = self.channel
input_game = self.game
infer_category = True
else:
self.twitch_send_message("Please wait for the streamer to go live or specify a user, game, and category.")
return
splits_response = self.api_caller(url)
if splits_response == False:
self.twitch_send_message("Failed to retrieve data from splits.io, please try again.")
return
game_pbs = [x for x in splits_response["pbs"] if x["game"] and x["game"][game_type].lower() == input_game.lower()]
game_categories = [x["category"]["name"] for x in game_pbs if x["category"]]
print game_categories
if infer_category:
success, response_string = self.find_category_title(game_categories, self.title)
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the user's splits.io profile."), "!splits")
return
else:
active_cat = response_string
else:
success, response_string = self.find_category_string(game_categories, category)
if success == False:
self.twitch_send_message(response_string.format(additional_info="on the user's splits.io profile."), "!splits")
return
else:
active_cat = response_string
pb_splits = [x for x in game_pbs if x["category"]["name"].lower() == active_cat.lower()][0]
output_game = pb_splits["game"]["name"]
time = self.format_sr_time(pb_splits['time'])
link_to_splits = 'https://splits.io{}'.format(pb_splits['path'])
response = "{}'s best splits for {} {} is {} {}".format(user_name.capitalize(), output_game, active_cat, time, link_to_splits)
self.twitch_send_message(response, '!splits')
def add_text(self, c_msg, text_type):
#Add a pun or quote to the review file
text = c_msg["message"][(len(text_type) + 4):]
text = text.strip()
if text == 'add{}'.format(text_type) or text == 'add{} '.format(text_type):
self.twitch_send_message('Please input a {}.'.format(text_type))
else:
url = "https://leagueofnewbs.com/api/users/{}/{}s".format(self.channel, text_type)
data = {
"reviewed": 1 if c_msg["sender"] == self.channel else 0,
"text": text,
}
cookies = {"session": self.session}
success = requests.post(url, data=data, cookies=cookies)
try:
success.raise_for_status()
reviewed = "to the database" if c_msg["sender"] == self.channel else "for review"
response = "Your {} has been added {}.".format(text_type, reviewed)
except Exception:
traceback.print_exc(limit=2)
response = "I had problems adding this to the database."
self.twitch_send_message(response, "!add" + text_type)
def text_retrieve(self, text_type):
#Pull a random pun/quote from the database
#Will not pull the same one twice in a row
text_type_plural = text_type + 's'
url = "https://leagueofnewbs.com/api/users/{}/{}?limit=2".format(self.channel, text_type_plural)
text_lines = self.api_caller(url)
if text_lines:
try:
if text_lines[text_type_plural][0]["text"] != self.last_text[text_type]:
response = text_lines[text_type_plural][0]["text"]
else:
try:
response = text_lines[text_type_plural][1]["text"]
except IndexError:
response = text_lines[text_type_plural][0]["text"]
except IndexError:
response = "Please insert {} into the database before using this command.".format(text_type_plural)
else:
response = "There was a problem retrieving {}.".format(text_type_plural)
self.twitch_send_message(response, '!' + text_type)
self.last_text[text_type] = response
def srl_race_retrieve(self):
#Goes through all races, finds the race the user is in, gathers all other users in the race, prints the game, the
#category people are racing, the time racebot has, and either a multitwitch link or a SRL race room link
srl_nick = self.config_data["srl_nick"]
url = 'http://api.speedrunslive.com/races'
data_decode = self.api_caller(url)
if data_decode == False:
return
data_races = data_decode['races']
srl_race_entrants = []
for i in data_races:
if self.channel in [x["twitch"].lower() for x in i["entrants"].values()] or srl_nick in [x.lower() for x in i["entrants"]]:
race_channel = i
for k, v in race_channel["entrants"].iteritems():
if srl_nick == k.lower() or self.channel == v["twitch"].lower():
user_nick = k
for values in race_channel['entrants'].values():
if values['statetext'] == 'Ready' or values['statetext'] == 'Entered':
if values['twitch'] != '':
srl_race_entrants.append(values['twitch'].lower())
user_place = race_channel['entrants'][user_nick]['place']
user_time = race_channel['entrants'][user_nick]['time']
srl_race_status = race_channel['statetext']
srl_race_time = race_channel['time']
srl_race_link = 'http://www.speedrunslive.com/race/?id={}'.format(race_channel['id'])
srl_live_entrants = []
live_decoded = self.api_caller('https://api.twitch.tv/kraken/streams?channel=' + ','.join(srl_race_entrants))
for j in live_decoded['streams']:
srl_live_entrants.append(j['channel']['name'])
response = 'Game: {}, Category: {}, Status: {}'.format(race_channel['game']['name'], race_channel['goal'], srl_race_status)
if srl_race_time > 0:
if user_time > 0:
time_formatted = self.format_sr_time(user_time)
position_suffix = str(self.get_number_suffix(user_place))
response += ', Finished {}{} with a time of {}'.format(user_place, position_suffix, time_formatted)
else:
real_time = (int(time.time()) - srl_race_time)
time_formatted = self.format_sr_time(real_time)
response += ', RaceBot Time: {}'.format(time_formatted)
live_length = len(srl_live_entrants)
if srl_race_status == 'Complete':
response += '. {}'.format(srl_race_link)
elif live_length <= 6 and live_length > 1:
multitwitch_link = "http://kadgar.net/live/" + '/'.join(srl_live_entrants)
response += '. {}'.format(multitwitch_link)
else:
response += '. {}'.format(srl_race_link)
self.twitch_send_message(response, '!race')
return
def youtube_video_check(self, c_msg):
#Links the title and uploader of the youtube video in chat
video_ids = re.findall("(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})", c_msg["message"])
if not video_ids:
return
else:
seen_ids = set()
seen_add = seen_ids.add
video_ids = [x for x in video_ids if not (x in seen_ids or seen_add(x))]
final_list = []
for i in video_ids:
url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id={}&key={}'.format(i, youtube_api_key)
data_decode = self.api_caller(url)
if data_decode == False:
return
if len(data_decode['items']) != 0:
data_items = data_decode['items']
video_title = data_items[0]['snippet']['title'].encode("utf-8")
uploader = data_items[0]['snippet']['channelTitle'].encode("utf-8")
view_count = data_items[0]['statistics']['viewCount']
duration = isodate.parse_duration(data_items[0]["contentDetails"]["duration"])
duration_string = self.format_sr_time(duration.seconds)
final_list.append("[{}] {} uploaded by {}. Views: {}".format(duration_string, video_title, uploader, view_count))
else:
continue
self.twitch_send_message(" | ".join(final_list))
return
def create_vote(self, c_msg):
#Used to create polls in chat
#Creating polls requires a pretty specific syntax, but makes it easy to have different types
if self.votes:
self.twitch_send_message('There is already an open poll, please close it first.')
return
poll_type = c_msg["message"].split(' ')[1]
try:
poll = re.findall('"(.+)"', c_msg["message"])[0]
except Exception:
self.twitch_send_message('Please give the poll a name.')
return
self.votes = { 'name' : poll,
'type' : poll_type,
'options' : {},
'voters' : {}}
if poll_type == 'strict':
options = re.findall('\((.+?)\)', c_msg["message"])
if not options:
self.twitch_send_message('You did not supply any options, poll will be closed.')
self.votes.clear()
return
for i in options:
vote_option = i.lower()
self.votes['options'][vote_option] = 0
response = 'You may now vote for this poll using only the supplied options.'
elif poll_type == 'loose':
response = 'You may now vote for this poll with whatever choice you like.'
else:
response = "Please specify a poll type."
self.votes.clear()
self.twitch_send_message(response)
def end_vote(self):
#Ending a current poll will display the winning vote of the poll and close it
if self.votes:
try:
winning_amount = max(self.votes['options'].values())
winning_keys = [key for key, value in self.votes["options"] if value == winning_amount]
if len(winning_keys) == 0:
response = ""
elif len(winning_keys) == 1:
response = "{0} has won with {1} votes.".format(winning_keys[0], winning_amount)
else:
combined_keys = ", ".join(winning_keys)
response = "{0} have all tied with {1} votes!".format(combined_keys, winning_amount)
finally:
self.votes.clear()
if response:
self.twitch_send_message(response)
def vote(self, c_msg):
#Allows viewers to vote in a poll created by mods/broadcaster
try:
sender_bet = c_msg["message"].split('vote ')[-1]
sender_bet = sender_bet.lower()
except Exception:
return
if not self.votes:
return
if self.votes['type'] == 'strict':
if sender_bet not in self.votes['options']:
self.twitch_send_message('You must vote for one of the options specified: ' + ', '.join(self.votes['options'].keys()), '!vote')
return
if c_msg["sender"] in self.votes['voters']:
if sender_bet == self.votes['voters'][c_msg["sender"]]:
response = 'You have already voted for that {}.'.format(c_msg["sender"])
else:
previous = self.votes['voters'][c_msg["sender"]]
self.votes['options'][previous] -= 1
if self.votes['options'][previous] == 0 and self.votes['type'] == 'loose':
del self.votes['options'][previous]
try:
self.votes['options'][sender_bet] += 1
except KeyError:
self.votes['options'][sender_bet] = 1
self.votes['voters'][c_msg["sender"]] = sender_bet
response = '{} has changed their vote to {}'.format(c_msg["sender"], sender_bet)
else:
try:
self.votes['options'][sender_bet] += 1
except KeyError:
self.votes['options'][sender_bet] = 1
self.votes['voters'][c_msg["sender"]] = sender_bet
response = '{} now has {} votes for it.'.format(sender_bet, str(self.votes['options'][sender_bet]))
self.twitch_send_message(response, '!vote')
def check_votes(self):
#Allows you to see what is currently winning in the current poll w/o closing it
if not self.votes:
return
response = 'Current poll: "{}". '.format(self.votes["name"])
if not self.votes['options']:
response += "No one has bet yet. "
else:
for k, v in self.votes["options"].items():
response += "{}: {}; ".format(k, v)
self.twitch_send_message(response[:-2], '!vote')
def lister(self, c_msg, s_list):
#Add user to blacklist or remove them from it
#Blacklist will cause bot to completely ignore the blacklisted user
user = c_msg["message"].split(' ')[-1]
worked = False
if s_list == 'black':
self.blacklist.append(user)
with open('blacklists/{}_blacklist.txt'.format(self.channel), 'a+') as data_file:
data_file.write(user + '\n')
worked = True
elif s_list == 'white':
if user in self.blacklist:
self.blacklist.remove(user)
with open('blacklists/{}_blacklist.txt'.format(self.channel), 'w') as data_file:
try:
data_file.write(self.blacklist)
except Exception:
pass
worked = True
if worked == True:
self.twitch_send_message('{} has been {}listed'.format(user, s_list))
def add_custom_command(self, c_msg):
user = c_msg["sender"]
msg_split = c_msg["message"].split(" ", 4)
trigger = msg_split[1]
limit = msg_split[2]
admin_bool = 1 if (msg_split[3].lower() == "true" or msg_split[3].lower() == "t") else 0
output = msg_split[4]