-
Notifications
You must be signed in to change notification settings - Fork 1
/
streams.py
1628 lines (1497 loc) · 59.4 KB
/
streams.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
"""
streams.py - A willie module to track livestreams from popular services
Copyright 2013, Tim Dreyer
Licensed under the Eiffel Forum License 2.
http://bitbucket.org/tdreyer/fineline
"""
from __future__ import print_function
import json
import re
import shutil
from socket import timeout
from string import Template
import threading
import time
import willie.web as web
from willie.module import commands, interval
from willie.tools import Nick
# Bot framework is stupid about importing, so we need to override so that
# various modules are always available for import.
try:
import log
except:
1+1
try:
import colors
except:
1+1
_exc_regex = []
_twitch_client_id = None # Overwritten in setup()
_youtube_api_key = None # Overwritten in setup()
_ustream_dev_key = None # Overwritten in setup()
_re_jtv = re.compile('(?<=justin\.tv/)[^/(){}[\]]+')
_exc_regex.append(re.compile('justin\.tv/'))
_re_ttv = re.compile('(?<=twitch\.tv/)[^/(){}[\]]+')
_exc_regex.append(re.compile('twitch\.tv/'))
_re_ls = re.compile('(?<=livestream\.com/)[^/(){}[\]]+')
_exc_regex.append(re.compile('livestream\.com/'))
_re_us = re.compile('((?<=ustream\.tv/channel/)|(?<=ustream\.tv/))([^/(){}[\]]+)')
_exc_regex.append(re.compile('ustream\.tv/'))
_re_yt = re.compile('((youtube\.com/user/)|(youtube\.com/))([^\?/(){}[\]\s]+)')
_exc_regex.append(re.compile('youtube\.com/'))
# _url_finder = re.compile(r'(?u)(%s?(?:http|https)(?:://\S+))')
_services = ['justin.tv', 'twitch.tv', 'livestream.com', 'youtube.com',
'ustream.tv']
_SUB = ('?',) # This will be replaced in setup()
# TODO move this to memory
_include = ['#reddit-mlpds', '#fineline_testing']
class stream(object):
'''General stream object. To be extended for each individual API.'''
_alias = None
_url = None
_settings = {}
_live = False
_nsfw = False
_manual_nsfw = False
_last_update = None
_service = None
def __init__(self, name, alias=None):
super(stream, self).__init__()
self._name = name
self._alias = alias
def __str__(self):
# TODO parse unicode to str
return '%s on %s' % (self.name, self.service)
def __unicode__(self):
return u'%s on %s' % (self.name, self.service)
def __repr__(self):
return self._name
def __lt__(self, other):
return ((self.name, self.service) < (other.name, other.service))
def __le__(self, other):
return ((self.name, self.service) <= (other.name, other.service))
def __gt__(self, other):
return ((self.name, self.service) > (other.name, other.service))
def __ge__(self, other):
return ((self.name, self.service) >= (other.name, other.service))
def __eq__(self, other):
return ((self.name, self.service) == (other.name, other.service))
def __ne__(self, other):
return ((self.name, self.service) != (other.name, other.service))
def __hash__(self):
return hash((self.name, self.service))
@property
def live(self):
return self._live
@live.setter
def live(self, value):
assert isinstance(value, bool)
self._live = value
@property
def name(self):
return self._name
@property
def service(self):
return self._service
@property
def url(self):
return self._url
@property
def nsfw(self):
return self._nsfw
@property
def m_nsfw(self):
return self._manual_nsfw
@m_nsfw.setter
def m_nsfw(self, value):
assert isinstance(value, bool)
self._manual_nsfw = value
@m_nsfw.deleter
def m_nsfw(self):
self._manual_nsfw = None
@property
def alias(self):
return self._alias
@alias.setter
def alias(self, value):
assert isinstance(value, basestring)
self._alias = value
@alias.deleter
def alias(self):
self._alias = None
@property
def updated(self):
return self._last_update
def update(self):
# Dummy function to be extended by children. Use to hit the appropriate
# streaming site and update object variables.
return
class justintv(stream):
# http://www.justin.tv/p/api
_base_url = 'http://api.justin.tv/api/'
_service = 'justin.tv'
_last_update = time.time()
# _header_info = ''
def __init__(self, name, alias=None):
super(justintv, self).__init__(name, alias)
self.update()
def update(self):
# Update stream info - first grab chan, then try to grab stream
# Update channel info
try:
self._results = web.get(u'%schannel/show/%s.json' % (
self._base_url, self._name))
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
print("Bad Json loaded from justin.tv")
print("Raw data is:")
print(self._results)
raise
except IndexError:
raise
except TypeError:
raise
try:
raise ValueError(self._form_j['error'])
except KeyError:
pass
for s in self._form_j:
self._settings[s] = self._form_j[s]
self._form_j = None # cleanup
# Update stream info if available
try:
self._results = web.get(u'%sstream/list.json?channel=%s' % (
self._base_url, self._name))
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
print("Bad Json loaded from justin.tv")
print("Raw data is:")
print(self._results)
raise
except IndexError:
raise
except TypeError:
raise
if self._form_j:
# We got results here, it means the stream is live
if not self._live:
self._last_update = time.time()
self._live = True
try:
raise ValueError(self._form_j['error'])
except KeyError:
# the object has no key 'error' so nothing's wrong
pass
except TypeError:
# The object is probably valid, dict inside list
pass
# Load data [{...}]
for s in self._form_j[0]:
self._settings[s] = self._form_j[0][s]
else:
# No results means stream's not live if self._live:
self._live = False
self._last_update = time.time()
self._form_j = None # cleanup
self._url = self._settings['channel_url']
# NSFW flag is one of ['true', 'false', None]
if self._settings['mature'] == 'true':
self._nsfw = True
else:
self._nsfw = False
class livestream(stream):
# http://www.livestream.com/userguide/index.php?title=Channel_API_2.0
_base_url = '.api.channel.livestream.com/2.0/'
_service = 'livestream.com'
_last_update = time.time()
# _header_info = ''
def __init__(self, name, alias=None):
super(livestream, self).__init__(name, alias)
self._safename = re.sub('_', '-', self._name)
try:
self._results = web.get(u'x%sx%sinfo.json' % (
self._safename, self._base_url))
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
if re.findall('400 Bad Request', self._results):
print('Livestream Error: 400 Bad Request')
raise ValueError('400 Bad Request')
elif re.findall('404 Not Found', self._results):
print('Livestream Error: 404 Not Found')
raise ValueError('404 Not Found')
elif re.findall('500 Internal Server Error', self._results):
print('Livestream Error: 500 Internal Server Error')
raise ValueError('500 Internal Server Error')
elif re.findall('503 Service Unavailable', self._results):
print('Livestream Error: 503 Service Unavailable')
raise ValueError('503 Service Unavailable')
else:
print("Bad Json loaded from livestream.com")
print("Raw data is:")
print(self._results)
raise
for s in self._form_j['channel']:
self._settings[s] = self._form_j['channel'][s]
if not self._live and self._settings['isLive']:
self._live = self._settings['isLive']
self._last_update = time.time()
self._url = self._settings['link']
# No integrated NSFW flags to parse!
def update(self):
try:
self._results = web.get(u'x%sx%slivestatus.json' % (
self._safename, self._base_url))
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
if re.findall('400 Bad Request', self._results):
print('Livestream Error: 400 Bad Request')
raise ValueError('400 Bad Request')
elif re.findall('404 Not Found', self._results):
print('Livestream Error: 404 Not Found')
raise ValueError('404 Not Found')
elif re.findall('500 Internal Server Error', self._results):
print('Livestream Error: 500 Internal Server Error')
raise ValueError('500 Internal Server Error')
elif re.findall('503 Service Unavailable', self._results):
print('Livestream Error: 503 Service Unavailable')
raise ValueError('503 Service Unavailable')
else:
print("Bad Json loaded from livestream.com")
print("Raw data is:")
print(self._results)
raise
for s in self._form_j['channel']:
self._settings[s] = self._form_j['channel'][s]
if bool(self._live) ^ bool(self._settings['isLive']):
self._live = self._settings['isLive']
self._last_update = time.time()
class ustream(stream):
# bot.memory['streamSet']['ustream_dev_key'] = bot.config.streams.ustream_dev_key
# http://developer.ustream.tv/data_api/docs
_base_url = 'http://api.ustream.tv/json'
_service = 'ustream.tv'
_last_update = time.time()
# _header_info = ''
def __init__(self, name, alias=None):
super(ustream, self).__init__(name, alias)
self._results = web.get(u'%s/channel/%s/getInfo?key=%s' % (
self._base_url, self._name, _ustream_dev_key))
self._form_j = json.loads(self._results)
if self._form_j['error']:
raise ValueError(self._form_j['error'])
if self._form_j['results']['status'] == 'online':
self._live = True
self._last_update = time.time()
self._url = self._form_j['results']['url']
# No integrated NSFW flags to parse
def update(self):
self._results = web.get(u'%s/channel/%s/getValueOf/status?key=%s' % (
self._base_url, self._name, _ustream_dev_key))
self._form_j = json.loads(self._results)
if self._form_j['error']:
raise ValueError(self._form_j['error'])
if self._live ^ bool(self._form_j['results'] == 'live'):
self._live = bool(self._form_j['results'] == 'live')
self._last_update = time.time()
class youtube(stream):
_base_url = 'https://gdata.youtube.com/feeds/api/'
_user_url = 'users/%s?alt=json'
_live_url = 'users/%s/live/events?alt=json&status=active'
_event_url = None
_service = 'youtube.com'
_header = {'GData-Version': 2}
_re_yturl = re.compile('[^/]+$')
if _youtube_api_key:
_header['X-GData-Key'] = 'key=%s' % _youtube_api_key
_last_update = time.time()
def __init__(self, name, alias=None):
super(youtube, self).__init__(name, alias)
self._results = web.get(self._base_url + self._user_url % self._name,
headers=self._header)
try:
self._form_j = json.loads(self._results)
except ValueError:
# TODO May not need to handle this here, but in calling code
raise
# self._name = self._form_j['entry']['author'][0]['name']['$t']
self._url_list = self._form_j['entry']['link']
# for d in [a for a in self._url_list if a['rel'] == 'alternate']:
# # TODO make sure this url is the live url, probably not
# self._url = d['href']
self._url = 'http://youtube.com/%s' % self._form_j['entry']['yt$username']['$t']
self.update()
@property
def url(self):
if self._event_url:
return self._event_url
else:
return self._url
def update(self):
self._results = web.get(self._base_url + self._live_url % self._name,
headers=self._header)
self._form_j = json.loads(self._results)
if bool('entry' in self._form_j['feed']) ^ bool(self._live):
if 'entry' in self._form_j['feed']:
self._live = True
else:
self._live = False
self._last_update = time.time()
if self._live:
# When going online, we should grab the live stream URL
print(self._form_j['feed']['entry'][0]['content']['src'])
self._event_url = 'http://youtube.com/watch?v=%s' % \
self._re_yturl.findall(self._form_j['feed']['entry'][0]['content']['src'])[0]
else:
# when going offline, we should reset the URL
self._event_url = None
class twitchtv(stream):
# https://github.com/justintv/twitch-api
_base_url = 'https://api.twitch.tv/kraken/'
_service = 'twitch.tv'
_header_info = {'Accept': 'application/vnd.twitchtv.v2+json'}
if _twitch_client_id:
_header_info['Client-ID'] = _twitch_client_id
_last_update = time.time()
def __init__(self, name, alias=None):
super(twitchtv, self).__init__(name, alias)
# Update channel info
try:
self._results = web.get(u'%schannels/%s' % (
self._base_url, self._name), headers=self._header_info)
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
print("Bad Json loaded from twitch.tv")
print("Raw data is:")
print(self._results)
raise
if 'error' in self._form_j:
raise ValueError('%s %s: %s' % (
self._form_j['status'],
self._form_j['error'],
self._form_j['message']))
# print('got json')
# print(json.dumps(self._form_j, indent=4))
try:
raise ValueError(self._form_j['error'])
except KeyError:
pass
for s in self._form_j:
self._settings[s] = self._form_j[s]
self._form_j = None # cleanup
self._url = self._settings['url']
# NSFW flag is one of ['true', 'false', None]
if self._settings['mature'] == 'true':
self._nsfw = True
else:
self._nsfw = False
self.update()
def update(self):
try:
self._results = web.get(u'%sstreams/%s' % (
self._base_url, self._name), headers=self._header_info)
except timeout:
raise
try:
self._form_j = json.loads(self._results)
except ValueError:
print("Bad Json loaded from twitch.tv")
print("Raw data is:")
print(self._results)
raise
if 'error' in self._form_j:
raise ValueError('%s %s %s' % (
self._form_j['error'],
self._form_j['status'],
self._form_j['message']))
for s in self._form_j:
self._settings[s] = self._form_j[s]
self._form_j = None # cleanup
# If stream is populated with data, then stream is live
if bool(self._live) ^ bool(self._settings['stream']):
self._live = bool(self._settings['stream'])
self._last_update = time.time()
class StreamFactory(object):
def newStream(self, channel, service, alias=None):
# TODO catch exceptions from object instantiations
if service == 'justin.tv':
return justintv(channel, alias)
elif service == 'twitch.tv':
return twitchtv(channel, alias)
elif service == 'livestream.com':
return livestream(channel, alias)
elif service == 'youtube.com':
return youtube(channel, alias)
elif service == 'ustream.tv':
return ustream(channel, alias)
else:
return None
#def configure(config):
# '''
# | [streams] | example | purpose |
# | --------- | ------- | ------- |
# | stream_help_file_path | /home/willie/.modules/help.html | Absolute path to HTML file to be displayed for help. |
# | stream_help_file_url | http://your.domain.com/help.html | URL pointing to the hosted help page. |
# | stream_list_template_path | /home/willie/.modules/list.html.template | Absolute path to the HTML template to be used for listing streams. |
# | stream_list_main_dest_path | /home/user/dropbox/main.html | Absolute path to where the bot should write the formatted main list HTML file. |
# | stream_list_feat_dest_path | /home/user/dropbox/featured.html | Absolute path to where the bot should write the formatted featured list HTML file. |
# | stream_list_main_url | http://your.domain.com/main.html | URL pointing to the hosted main list page. |
# | stream_list_feat_url | http://your.domain.com/feat.html | URL pointing to the hosted featured list page. |
# '''
# if config.option('Configure stream files and urls', False):
# config.interactive_add(
# 'streams',
# 'stream_help_file_path',
# 'Absolute path to HTML file to be displayed for help.'
# )
# config.interactive_add(
# 'streams',
# 'stream_help_file_url',
# 'URL pointing to the hosted help page.'
# )
# config.interactive_add(
# 'streams',
# 'stream_list_template_path',
# 'Absolute path to the HTML template to be used for listing streams.'
# )
# config.interactive_add(
# 'streams',
# 'stream_list_main_dest_path',
# 'Absolute path to where the bot should write the formatted main list HTML file.'
# )
# config.interactive_add(
# 'streams',
# 'stream_list_feat_dest_path',
# 'Absolute path to where the bot should write the formatted featured list HTML file.'
# )
# config.interactive_add(
# 'streams',
# 'stream_list_main_url',
# 'URL pointing to the hosted main list page.'
# )
# config.interactive_add(
# 'streams',
# 'stream_list_feat_url',
# 'URL pointing to the hosted featured list page.'
# )
def setup(bot):
global _twitch_client_id
_twitch_client_id = bot.config.streams.twitch_client_id
global _youtube_api_key
_youtube_api_key = bot.config.streams.youtube_api_key
global _ustream_dev_key
_ustream_dev_key = bot.config.streams.ustream_dev_key
bot.memory['streamSet'] = {}
bot.memory['streamSet']['help_file_source'] = bot.config.streams.stream_help_file_source
bot.memory['streamSet']['help_file_dest'] = bot.config.streams.stream_help_file_dest
bot.memory['streamSet']['help_file_url'] = bot.config.streams.stream_help_file_url
bot.memory['streamSet']['list_template_path'] = bot.config.streams.stream_list_template_path
bot.memory['streamSet']['list_main_dest_path'] = bot.config.streams.stream_list_main_dest_path
bot.memory['streamSet']['list_feat_dest_path'] = bot.config.streams.stream_list_feat_dest_path
bot.memory['streamSet']['list_main_url'] = bot.config.streams.stream_list_main_url
bot.memory['streamSet']['list_feat_url'] = bot.config.streams.stream_list_feat_url
try:
shutil.copyfile(
bot.memory['streamSet']['help_file_source'],
bot.memory['streamSet']['help_file_dest']
)
except:
bot.debug(__file__,
log.format(u'Unable to copy help file. Check configuration.'),
u'always')
raise
with open(bot.memory['streamSet']['list_template_path']) as f:
try:
bot.memory['streamListT'] = Template(''.join(f.readlines()))
except:
bot.debug(__file__,
log.format(u'Unable to load list template.'),
u'always')
raise
bot.debug(
__file__,
log.format(u'Starting stream setup, this may take a bit.'),
'always'
)
# TODO consider making these unique sets
if 'url_exclude' not in bot.memory:
bot.memory['url_exclude'] = []
bot.memory['url_exclude'].extend(_exc_regex)
if 'streams' not in bot.memory:
bot.memory['streams'] = []
if 'feat_streams' not in bot.memory:
bot.memory['feat_streams'] = []
if 'streamFac' not in bot.memory:
bot.memory['streamFac'] = StreamFactory()
if 'streamLock' not in bot.memory:
bot.memory['streamLock'] = threading.Lock()
if 'streamSubs' not in bot.memory:
bot.memory['streamSubs'] = {}
if 'streamMsg' not in bot.memory:
bot.memory['streamMsg'] = {}
# database stuff
global _SUB
_SUB = (bot.db.substitution,)
with bot.memory['streamLock']:
dbcon = bot.db.connect() # sqlite3 connection
cur = dbcon.cursor()
# If our tables don't exist, create them
try:
cur.execute('''CREATE TABLE IF NOT EXISTS streams
(channel text, service text,
m_nsfw int, alias text)''')
cur.execute('''CREATE TABLE IF NOT EXISTS feat_streams
(channel text, service text)''')
cur.execute('''CREATE TABLE IF NOT EXISTS sub_streams
(channel text, service text, nick text)''')
dbcon.commit()
finally:
cur.close()
dbcon.close()
if not bot.memory['streams']:
load_from_db(bot)
@commands('live_reload')
def load_from_db(bot, trigger=None):
"""ADMIN: Reload live streams from database"""
if trigger and not trigger.owner:
return
bot.debug(__file__, log.format(u'Reloading from DB'), 'verbose')
bot.memory['streams'] = []
bot.memory['feat_streams'] = []
dbcon = bot.db.connect() # sqlite3 connection
cur = dbcon.cursor()
try:
cur.execute('SELECT channel, service, m_nsfw, alias FROM streams')
stream_rows = cur.fetchall()
cur.execute('SELECT channel, service FROM feat_streams')
feat_rows = cur.fetchall()
cur.execute('SELECT channel, service, nick FROM sub_streams')
sub_rows = cur.fetchall()
finally:
cur.close()
dbcon.close()
for c, s, n, a in stream_rows:
time.sleep(0.25)
try:
bot.memory['streams'].append(
bot.memory['streamFac'].newStream(c, s, a))
except:
bot.debug(__file__,
log.format(u'Failed to initialize livestream: %s, %s, %s' % (c, s, a)),
u'warning')
if n:
nsfw(bot, 'nsfw', (c, s), quiet=True)
for c, s in feat_rows:
feature(bot, 'feature', (c, s), quiet=True)
for c, s, n in sub_rows:
subscribe(bot, 'subscribe', (c, s), Nick(n), quiet=True)
bot.debug(__file__, log.format(u'Done.'), 'verbose')
def alias(bot, switch, channel, value=None):
assert isinstance(channel, basestring) or type(channel) is tuple
try:
c, s = parse_service(channel)
except TypeError:
bot.say('Bad url or channel/service pair. See !help services.')
return
dbcon = bot.db.connect()
cur = dbcon.cursor()
with bot.memory['streamLock']:
if switch == 'alias':
i = None
for i in [a for a in bot.memory['streams']
if a.name == c and a.service == s]:
i.alias = value
try:
cur.execute('''UPDATE streams
SET alias = %s
WHERE channel = %s
AND service = %s
''' % (_SUB * 3), (value, c, s))
dbcon.commit()
finally:
cur.close()
dbcon.close()
bot.say(u'Set alias for %s to %s.' % (c, value))
return
else:
bot.say(u"I don't have that stream.")
elif switch == 'unalias':
i = None
for i in [a for a in bot.memory['streams']
if a.name == c and a.service == s]:
if i.alias:
del i.alias
try:
cur.execute('''UPDATE streams
SET alias = NULL
WHERE channel = %s
AND service = %s
''' % (_SUB * 2), (c, s))
dbcon.commit()
finally:
cur.close()
dbcon.close()
bot.say(u'Removed alias for %s.' % c)
return
else:
bot.say(u"That doesn't have an alias.")
return
else:
bot.say(u"I don't have that stream.")
else:
bot.say(u"Uh, that wasn't supposed to happen.")
bot.say(u"!tell tdreyer1 HEEEEEEEEEEELLLLLLP!")
def nsfw(bot, switch, channel, quiet=None):
assert isinstance(channel, basestring) or type(channel) is tuple
try:
c, s = parse_service(channel)
except TypeError:
msg = u'Bad url or channel/service pair. See !help services.'
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
return
dbcon = bot.db.connect()
cur = dbcon.cursor()
with bot.memory['streamLock']:
if switch == 'nsfw':
i = None
for i in [a for a in bot.memory['streams']
if a.name == c and a.service == s]:
i.m_nsfw = True
try:
cur.execute('''UPDATE streams
SET m_nsfw = 1
WHERE channel = %s
AND service = %s
''' % (_SUB * 2), (c, s))
dbcon.commit()
finally:
cur.close()
dbcon.close()
msg = u'Set NSFW tag for %s.' % c
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
return
else:
msg = u"I don't have that stream."
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
elif switch == 'unnsfw':
i = None
for i in [a for a in bot.memory['streams']
if a.name == c and a.service == s]:
if i.m_nsfw:
del i.m_nsfw
try:
cur.execute('''SELECT COUNT(*) FROM streams
WHERE channel = %s
AND service = %s
AND m_nsfw = 1
''' % (_SUB * 2), (c, s))
if cur.fetchone():
cur.execute('''UPDATE streams
SET m_nsfw = 0
WHERE channel = %s
AND service = %s
''' % (_SUB * 2), (c, s))
dbcon.commit()
finally:
cur.close()
dbcon.close()
msg = u'Removed NSFW tag for %s.' % c
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
return
else:
msg = u"That doesn't have a NSFW tag."
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
return
else:
msg = u"I don't have that stream."
if not quiet:
bot.say(msg)
else:
bot.debug(__file__, log.format(msg), 'warning')
else:
msg = u"Uh oh, that wasn't supposed to happen."
if not quiet:
bot.say(msg)
bot.say(u"!tell tdreyer1 FIIIIIXX MEEEEEEEE!")
else:
bot.debug(__file__, log.format(msg), 'warning')
def more_help(bot, trigger):
bot.reply(u'For detailed help, see %s' %
bot.memory['streamSet']['help_file_url'])
@commands('streams')
def streams_alias(bot, trigger):
# Don't do anything if the bot has been shushed
if bot.memory['shush']:
return
list_streams(bot, 'live')
@commands('live')
def sceencasting(bot, trigger):
'''Manage various livestreams from multiple services.
Usage: !live [list/add/del/[un]alias/[un]nsfw/[un]subscribe/]
[options] | See '!live help' for detailed usage.'''
# Don't do anything if the bot has been shushed
if bot.memory['shush']:
return
if len(trigger.args[1].split()) == 1: # E.G. "!live"
list_streams(bot, 'live')
return
if len(trigger.args[1].split()) == 2: # E.G. "!stream url"
arg1 = trigger.args[1].split()[1].lower()
if arg1 == 'list':
list_streams(bot, nick=Nick(trigger.nick))
return
if arg1 == 'stats':
stats(bot)
return
if arg1 == 'help':
more_help(bot, trigger)
return
else:
add_stream(bot, arg1)
return
elif len(trigger.args[1].split()) == 3: # E.G. "!stream add URL"
arg1 = trigger.args[1].split()[1].lower()
arg2 = trigger.args[1].split()[2].lower()
if arg1 == 'add':
add_stream(bot, arg2)
return
elif arg1 == 'del':
remove_stream(bot, arg2)
return
elif arg1 == 'subscribe' or arg1 == 'unsubscribe':
subscribe(bot, arg1, arg2, Nick(trigger.nick))
return
elif arg1 == 'feature' or arg1 == 'unfeature':
if trigger.admin:
feature(bot, arg1, arg2)
return
else:
bot.reply(u"Sorry, that's an admin only command.")
return
elif arg1 == 'list':
list_streams(bot, arg2, Nick(trigger.nick))
return
elif arg1 == 'info':
info(bot, arg2)
return
elif arg1 == 'unalias':
alias(bot, arg1, arg2)
return
elif arg1 == 'nsfw' or arg1 == 'unnsfw':
nsfw(bot, arg1, arg2)
return
elif len(trigger.args[1].split()) == 4: # E.G. "!stream add user service"
arg1 = trigger.args[1].split()[1].lower()
arg2 = trigger.args[1].split()[2].lower()
arg3 = trigger.args[1].split()[3].lower()
if arg1 == 'add':
add_stream(bot, (arg2, arg3))
return
elif arg1 == 'del':
remove_stream(bot, (arg2, arg3))
return
elif arg1 == 'subscribe' or arg1 == 'unsubscribe':
subscribe(bot, arg1, (arg2, arg3), Nick(trigger.nick))
return
elif arg1 == 'feature' or arg1 == 'unfeature':
if trigger.admin:
feature(bot, arg1, (arg2, arg3))
return
else:
bot.reply(u"Sorry, that's an admin only command.")
return
elif arg1 == 'list':
list_streams(bot, arg2, Nick(trigger.nick))
return
elif arg1 == 'info':
info(bot, (arg2, arg3))
return
elif arg1 == 'alias':
alias(bot, arg1, arg2, arg3)
return
elif arg1 == 'unalias':
alias(bot, arg1, (arg2, arg3))
return
elif arg1 == 'nsfw' or arg1 == 'unnsfw':
nsfw(bot, arg1, (arg2, arg3))
return
elif len(trigger.args[1].split()) == 5: # E.G. "!stream add user service"
arg1 = trigger.args[1].split()[1].lower()
arg2 = trigger.args[1].split()[2].lower()
arg3 = trigger.args[1].split()[3].lower()
arg4 = trigger.args[1].split()[4].lower()
if arg1 == 'alias':
alias(bot, arg1, (arg2, arg3), arg4)
return
# We either got nothing, or too much
bot.reply("I don't understand that, try '!help live' for info.")
def parse_service(service):
'''Takes a url string or tuple and returns (chan, service)'''
assert isinstance(service, basestring) or type(service) is tuple
if type(service) is tuple:
if service[0] in _services:
return (service[1], service[0])
if service[1] in _services:
return service
else:
return None
else:
if _re_jtv.search(service):
return (_re_jtv.findall(service)[0], 'justin.tv')
elif _re_ttv.search(service):
return (_re_ttv.findall(service)[0], 'twitch.tv')
elif _re_ls.search(service):
return (_re_ls.findall(service)[0], 'livestream.com')
elif _re_yt.search(service):
return (_re_yt.findall(service)[0][-1], 'youtube.com')
elif _re_us.search(service):
return (_re_us.findall(service)[-1][-1], 'ustream.tv')
else:
return None
def add_stream(bot, user):
assert isinstance(user, basestring) or type(user) is tuple
try:
u, s = parse_service(user)
except TypeError:
bot.say('Bad url or channel/service pair. See !help services.')
return
if [a for a in bot.memory['streams'] if a.name == u and a.service == s]:
bot.reply(u'I already have that one.')
return
else:
# TODO may need a try block here
dbcon = bot.db.connect()
cur = dbcon.cursor()
with bot.memory['streamLock']:
try:
bot.memory['streams'].append(
bot.memory['streamFac'].newStream(u, s))
except ValueError as txt:
if str(txt) == '400 Bad Request':
bot.reply(u'Oops, I did something bad so that did not ' +
u'work.')
bot.say('!tell tdreyer1 FIX IT FIX IT FIX IT FIX IT!')
return
elif str(txt) == '404 Not Found':
bot.reply(u'Channel not found.')
return
elif str(txt) == '500 Internal Server Error':
bot.reply(u'Service returned internal server error, try' +
u' again later.')
return
# Twitch.tv - user is a justin.tv user
elif str(txt).startswith('422 Unprocessable Entity: Channel'):
bot.reply(u'That is actually a justin.tv user.')
return
# Twitch.tv - user does not exist
elif str(txt).startswith('404 Not Found: Channel'):