forked from FAForever/QAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqai_plugin.py
952 lines (849 loc) · 37.2 KB
/
qai_plugin.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
# vim: ts=4 et sw=4 sts=4
# -*- coding: utf-8 -*-
import json
import random
import asyncio
import re
import aiohttp
import aiomysql
import itertools
import irc3
from irc3.plugins.command import command
import time
from urllib.parse import urlparse, parse_qs
import threading
import slack
import challonge
import repetition
from taunts import TAUNTS, SPAM_PROTECT_TAUNTS, KICK_TAUNTS
from links import LINKS, LINKS_SYNONYMES, WIKI_LINKS, WIKI_LINKS_SYNONYMES, OTHER_LINKS
ALL_TAUNTS = [] # extended in init
BADWORDS = {}
REACTIONWORDS = {}
REPETITIONS = {}
OFFLINEMESSAGE_RECEIVERS = {}
NICKSERVIDENTIFIEDRESPONSES = {}
NICKSERVIDENTIFIEDRESPONSESLOCK = None
MAIN_CHANNEL = "#aeolus"
TWITCH_STREAMS = "https://api.twitch.tv/kraken/streams/?game=Supreme+Commander:+Forged+Alliance" #add the game name at the end of the link (space = "+", eg: Game+Name)
HITBOX_STREAMS = "https://api.hitbox.tv/media/live/list?filter=popular&game=811&hiddenOnly=false&limit=30&liveonly=true&media=true"
YOUTUBE_NON_API_SEARCH_LINK = "https://www.youtube.com/results?search_query=supreme+commander+%7C+forged+alliance&search_sort=video_date_uploaded&filters=video"
YOUTUBE_SEARCH = "https://www.googleapis.com/youtube/v3/search?order=date&type=video&part=snippet&q=Forged%2BAlliance|Supreme%2BCommander&relevanceLanguage=en&maxResults=15&key={}"
YOUTUBE_DETAIL = "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id={}&key={}"
LETMEGOOGLE = "http://lmgtfy.com/?q="
URL_MATCH = ".*(https?:\/\/[^ ]+\.[^ ]*).*"
REPLAY_MATCH = ".*(#[0-9]+).*"
@irc3.extend
def action(bot, *args):
bot.privmsg(args[0], '\x01ACTION ' + args[1] + '\x01')
@irc3.plugin
class Plugin(object):
requires = [
'irc3.plugins.userlist'
]
def __init__(self, bot):
self.bot = bot
self.timers = {}
self._rage = {}
global ALL_TAUNTS, NICKSERVIDENTIFIEDRESPONSESLOCK
ALL_TAUNTS.extend(TAUNTS)
ALL_TAUNTS.extend(SPAM_PROTECT_TAUNTS)
challonge.setChallongeData(self.bot.config['challonge_username'], self.bot.config['challonge_api_key'])
NICKSERVIDENTIFIEDRESPONSESLOCK = threading.Lock()
self.slackThread = slack.slackThread(self.bot.config['slack_api_key'])
self.slackThread.daemon = True
self.slackThread.start()
@classmethod
def reload(cls, old):
return cls(old.bot)
def after_reload(self):
self._taunt('#qai_channel')
@irc3.event(irc3.rfc.CONNECTED)
def nickserv_auth(self, *args, **kwargs):
self.bot.privmsg('nickserv', 'identify %s' % self.bot.config['nickserv_password'])
global REPETITIONS, BADWORDS, REACTIONWORDS, OFFLINEMESSAGE_RECEIVERS
self.__dbAdd([], 'chatlists', {}, overwriteIfExists=False)
self.__dbAdd([], 'offlinemessages', {}, overwriteIfExists=False)
self.__dbAdd(['repetitions'], 'text', {}, overwriteIfExists=False)
self.__dbAdd(['blacklist'], 'users', {}, overwriteIfExists=False)
self.__dbAdd(['groups'], 'playergroups', {}, overwriteIfExists=False)
self.__dbAdd(['badwords'], 'words', {}, overwriteIfExists=False)
self.__dbAdd(['reactionwords'], 'words', {}, overwriteIfExists=False)
BADWORDS = self.__dbGet(['badwords', 'words'])
REACTIONWORDS = self.__dbGet(['reactionwords', 'words'])
for r in self.__dbGet(['offlinemessages']).keys():
OFFLINEMESSAGE_RECEIVERS[r] = True
self._tryDeliverOfflineMessages(r)
repetitions = self.__dbGet(['repetitions', 'text'])
for t in repetitions.keys():
REPETITIONS[t] = repetition.repetitionThread(self.bot, repetitions[t].get('channel'), repetitions[t].get('text'), int(repetitions[t].get('seconds')))
REPETITIONS[t].daemon = True
REPETITIONS[t].start()
@irc3.event(irc3.rfc.JOIN)
def on_join(self, channel, mask):
if channel == MAIN_CHANNEL:
for channel in self.__dbGet(['chatlists']):
if mask.nick in self.__dbGet(['chatlists', channel]).keys():
self.move_user(channel, mask.nick)
if OFFLINEMESSAGE_RECEIVERS.get(mask.nick, False):
self._tryDeliverOfflineMessages(mask.nick)
def move_user(self, channel, nick):
self.bot.privmsg('OperServ', 'svsjoin %s %s' % (nick, channel))
@irc3.event(irc3.rfc.PRIVMSG)
@asyncio.coroutine
def on_privmsg(self, *args, **kwargs):
msg, channel, sender = kwargs['data'], kwargs['target'], kwargs['mask']
if self.bot.config['nick'] in sender.nick:
return
try:
link_url = re.match(URL_MATCH, msg).groups()[0]
uri = urlparse(link_url)
ytid = parse_qs(uri.query).get('v', '')[0]
if len(ytid) > 0:
req = yield from aiohttp.request('GET', YOUTUBE_DETAIL.format(ytid, self.bot.config['youtube_key']))
data = json.loads((yield from req.read()).decode())['items'][0]
self.bot.privmsg(channel, "{title} - {views} views - {likes} likes (Linked above by {sender})".format(title=data['snippet']['title'],
views=data['statistics']['viewCount'],
likes=data['statistics']['likeCount'],
sender=sender.nick))
except (KeyError, ValueError, AttributeError, IndexError):
pass
try:
replayId = re.match(REPLAY_MATCH, msg).groups()[0]
replayId = replayId.replace('#', '')
rId = int(replayId)
if rId >= 1000000 and rId < 100000000:
url = LINKS["replay"].replace("ID", replayId)
self.bot.privmsg(channel, url)
except:
pass
if channel.startswith("#"):
lowercaseMsg = msg.lower()
for reactionword in REACTIONWORDS:
if reactionword in lowercaseMsg:
self.bot.privmsg(channel, REACTIONWORDS[reactionword].format(**{
"sender" : sender.nick,
}))
for badword in BADWORDS:
if badword in lowercaseMsg:
self.report(sender.nick, badword, channel, msg, BADWORDS[badword])
if sender.startswith("NickServ!"):
self.__handleNickservMessage(msg)
@command(permission='admin', public=False)
@asyncio.coroutine
def hidden(self, mask, target, args):
"""Actually shows hidden commands
%%hidden
"""
words = ["join", "leave", "puppet", "reload", "groupmanage", "blacklist", "badwords", "reactionwords", "repeat", "move", "chatlist"]
self.bot.privmsg(mask.nick, "Hidden commands (!help <command> for more info):")
for word in words:
self.bot.privmsg(mask.nick, "- " + word)
@command(permission='admin')
@asyncio.coroutine
def taunt(self, mask, target, args):
"""Send a taunt
%%taunt
%%taunt <person>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
p = args.get('<person>')
if p == self.bot.config['nick']:
p = mask.nick
self._taunt(channel=target, prefix=p, tauntTable=TAUNTS)
@command(permission='admin')
@asyncio.coroutine
def explode(self, mask, target, args):
"""Explode
%%explode
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
self.bot.action(target, "explodes")
@command(permission='admin')
@asyncio.coroutine
def hug(self, mask, target, args):
"""Hug someone
%%hug
%%hug <someone>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
someone = args['<someone>']
if someone == None:
someone = mask.nick
elif someone == self.bot.config['nick']:
self._taunt(channel=target, prefix=mask.nick)
return
self.bot.action(target, "hugs " + someone)
@command(permission='admin')
@asyncio.coroutine
def flip(self, mask, target, args):
"""Flip table
%%flip
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
self.bot.privmsg(target, "(╯°□°)╯︵ ┻━┻")
@command(permission='admin', show_in_help_list=False)
@asyncio.coroutine
def join(self, mask, target, args):
"""Overtake the given channel
%%join <channel>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
self.bot.join(args['<channel>'])
@command(permission='admin', show_in_help_list=False)
@asyncio.coroutine
def leave(self, mask, target, args):
"""Leave the given channel
%%leave
%%leave <channel>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
channel = args['<channel>']
if channel is None:
channel = target
self.bot.part(channel)
@command
def gullible(self, mask, target, args):
"""Display additional commands
%%gullible
"""
self._taunt(channel=target, prefix=mask.nick, tauntTable=SPAM_PROTECT_TAUNTS)
@command
def link(self, mask, target, args):
"""Link to a website
%%link
%%link <argument>
%%link <argument> WORDS...
"""
try:
self.bot.privmsg(target, LINKS_SYNONYMES[args['<argument>']])
return
except:
pass
try:
self.bot.privmsg(target, LINKS[args['<argument>']])
except:
if self.spam_protect('links', mask, target, args):
return
msg = ""
if not args['<argument>'] is None:
msg = "Unknown link: \"" + args['<argument>'] + "\". "
msg += "Do you mean one of these: " + " / ".join(LINKS.keys()) + " ?"
self.bot.privmsg(target, msg)
@command
def wiki(self, mask, target, args):
"""Link to a wiki page
%%wiki
%%wiki <argument>
%%wiki <argument> WORDS...
"""
try:
self.bot.privmsg(target, WIKI_LINKS_SYNONYMES[args['<argument>']])
return
except:
pass
try:
self.bot.privmsg(target, WIKI_LINKS[args['<argument>']])
except:
if self.spam_protect('wiki', mask, target, args):
return
msg = ""
if not args['<argument>'] is None:
msg = "Unknown wiki link: \"" + args['<argument>'] + "\". Do you mean one of these: "
else:
msg = LINKS["wiki"] + " For better matches try !wiki "
msg += " / ".join(WIKI_LINKS.keys())
if not args['<argument>'] is None:
msg += " ?"
self.bot.privmsg(target, msg)
@command(public=False)
@asyncio.coroutine
def offlinemessage(self, mask, target, args):
"""Store an offline message, it is delivered once the person logs on
%%offlinemessage <playername> WORDS ...
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
playername, message = args.get('<playername>'), " ".join(args.get('WORDS'))
if mask.nick == playername:
self._taunt(mask.nick)
return
isOnline, channel = self.__isInBotChannel(playername)
if isOnline:
return "The player is online in " + channel + ", tell him yourself."
self.__dbAdd(['offlinemessages', playername], mask.nick, {'message':message, 'sender':mask.nick, 'time':str(time.strftime("%d.%m.%Y %H:%M:%S"))}, overwriteIfExists=False, trySavingWithNewKey=True)
OFFLINEMESSAGE_RECEIVERS[playername] = True
self.bot.privmsg(mask.nick, "The message is saved and will be delivered once " + playername + " is online again.")
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def puppet(self, mask, target, args):
"""Puppet
%%puppet <target> WORDS ...
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
t = args.get('<target>')
m = " ".join(args.get('WORDS'))
self.bot.privmsg(t, m)
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def reload(self, mask, target, args):
"""Reboot the mainframe
%%reload
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
self.bot.reload(self.bot.config['nick'])
@command(permission='admin')
@asyncio.coroutine
def slap(self, mask, target, args):
"""Slap this guy
%%slap <guy>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
self.bot.action(target, "slaps %s " % args['<guy>'])
def _taunt(self, channel=None, prefix=None, tauntTable=None):
if channel is None:
channel = "#qai_channel"
if tauntTable is None:
tauntTable = ALL_TAUNTS
if prefix is None:
prefix = ''
else:
prefix = '%s: ' % prefix
self.bot.privmsg(channel, "%s%s" % (prefix, random.choice(tauntTable)))
def _tryDeliverOfflineMessages(self, receiver):
if OFFLINEMESSAGE_RECEIVERS.get(receiver, False):
isOnline, _ = self.__isInBotChannel(receiver)
if isOnline:
if self.__isNickservIdentified(receiver):
messages = self.__dbGet(['offlinemessages', receiver]).values()
for m in messages:
self.bot.privmsg(receiver, '"{message}" - Sent by {sender}, {time}'.format(**{
'message':m.get('message', "<message>"),
'sender':m.get('sender', "<sender>"),
'time':m.get('time', "<time>"),
}))
del OFFLINEMESSAGE_RECEIVERS[receiver]
self.__dbDel(['offlinemessages'], receiver)
@asyncio.coroutine
def hitbox_streams(self):
req = yield from aiohttp.request('GET', HITBOX_STREAMS)
data = yield from req.read()
try:
data = json.loads(data.decode())
livestreams = data.get('livestreams', None)
if not livestreams:
livestreams = data['livestream']
return livestreams
except (KeyError, ValueError):
return []
@asyncio.coroutine
def twitch_streams(self):
req = yield from aiohttp.request('GET', TWITCH_STREAMS)
data = yield from req.read()
try:
return json.loads(data.decode())['streams']
except (KeyError, ValueError):
return []
@command
@asyncio.coroutine
def casts(self, mask, target, args):
"""List recent casts
%%casts
"""
if self.spam_protect('casts', mask, target, args):
return
req = yield from aiohttp.request('GET', YOUTUBE_SEARCH.format(self.bot.config['youtube_key']))
data = json.loads((yield from req.read()).decode())
casts = []
try:
for item in itertools.takewhile(lambda _: len(casts) < 5, data['items']):
channel_title = item['snippet']['channelTitle']
if channel_title not in self.__dbGet(['blacklist', 'users']) and channel_title != '':
casts.append(item)
try:
self.bot.action(target,
"{channel}: {title} - {date}: {link}".format(
**{
"id": item['id']['videoId'],
"title": item['snippet']['title'],
"channel": channel_title,
"description": item['snippet']['description'],
"date": time.strftime("%x",
time.strptime(item['snippet']['publishedAt'],
self.bot.config['youtube_time_fmt'])),
"link": "http://youtu.be/{}".format(item['id']['videoId'])
}))
except (KeyError, ValueError):
pass
except (KeyError):
pass
self.bot.action(target, "Find more here: {}".format(YOUTUBE_NON_API_SEARCH_LINK))
def spam_protect(self, cmd, mask, target, args):
if not cmd in self.timers:
self.timers[cmd] = {}
if not target in self.timers[cmd]:
self.timers[cmd][target] = 0
if time.time() - self.timers[cmd][target] <= self.bot.config['spam_protect_time']:
try:
self._rage[mask.nick] += 1
except:
self._rage[mask.nick] = 1
if self._rage[mask.nick] >= self.bot.config['rage_to_kick']:
self._taunt(channel=target, prefix=mask.nick, tauntTable=KICK_TAUNTS)
self.bot.privmsg(target, "!kick {}".format(mask.nick))
self._rage[mask.nick] = 1
else:
self._taunt(channel=target, prefix=mask.nick, tauntTable=SPAM_PROTECT_TAUNTS)
return True
self._rage = {}
self.timers[cmd][target] = time.time()
def __handleNickservMessage(self, message):
if message.startswith('STATUS'):
words = message.split(" ")
global NICKSERVIDENTIFIEDRESPONSES, NICKSERVIDENTIFIEDRESPONSESLOCK
NICKSERVIDENTIFIEDRESPONSESLOCK.acquire()
NICKSERVIDENTIFIEDRESPONSES[words[1]] = words[2]
NICKSERVIDENTIFIEDRESPONSESLOCK.release()
@asyncio.coroutine
def __isNickservIdentified(self, nick):
self.bot.privmsg('nickserv', "status {}".format(nick))
remainingTries = 20
while remainingTries > 0:
if NICKSERVIDENTIFIEDRESPONSES.get(nick):
value = NICKSERVIDENTIFIEDRESPONSES[nick]
NICKSERVIDENTIFIEDRESPONSESLOCK.acquire()
del NICKSERVIDENTIFIEDRESPONSES[nick]
NICKSERVIDENTIFIEDRESPONSESLOCK.release()
if int(value) == 3:
return True
return False
remainingTries -= 1
yield from asyncio.sleep(0.1)
return False
def __isInBotChannel(self, player):
for channel in self.bot.channels:
if self.__isInChannel(player, self.bot.channels[channel]):
return True, channel
return False, ""
def __isInChannel(self, player, channel):
if player in channel:
return True
return False
def __filterForPlayersInChannel(self, playerlist, channelname):
players = {}
if not channelname in self.bot.channels:
return players
channel = self.bot.channels[channelname]
for p in playerlist.keys():
if self.__isInChannel(p, channel):
players[p] = True
return players
@command
@asyncio.coroutine
def streams(self, mask, target, args):
"""List current live streams
%%streams
"""
if self.spam_protect('streams', mask, target, args):
return
streams = yield from self.hitbox_streams()
streams.extend((yield from self.twitch_streams()))
blacklist = self.__dbGet(['blacklist', 'users'])
for stream in streams:
try:
if stream["media_display_name"] in blacklist:
streams.remove(stream)
except:
if stream["channel"]["display_name"] in blacklist:
streams.remove(stream)
if len(streams) > 0:
self.bot.privmsg(target, "%i streams online:" % len(streams))
for stream in streams:
t = stream["channel"].get("updated_at", "T0")
date = t.split("T")
hour = date[1].replace("Z", "")
try:
self.bot.action(target,
"%s - %s - %s Since %s (%s viewers) "
% (stream["media_display_name"],
stream["media_status"],
stream["channel"]["channel_link"],
stream["media_live_since"],
stream["media_views"]))
except KeyError:
self.bot.action(target,
"%s - %s - %s since %s (%i viewers) "
% (stream["channel"]["display_name"],
stream["channel"]["status"],
stream["channel"]["url"],
hour,
stream["viewers"]))
else:
self.bot.privmsg(target, "Nobody is streaming :'(")
@command
@asyncio.coroutine
def groupping(self, mask, target, args):
"""Pings people in this group
%%groupping <groupname>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
groupname = args.get('<groupname>')
playergroups = self.__dbGet(['groups', 'playergroups'])
if not playergroups.get(groupname):
return
players, text = playergroups[groupname].get('players', {}), playergroups[groupname].get('text', "")
playerlist = self.__filterForPlayersInChannel(players, target)
if not players.get(mask.nick):
self._taunt(channel=target, prefix=mask.nick, tauntTable=TAUNTS)
return
if self.spam_protect('groupping_' + groupname, mask, target, args):
return
self.bot.privmsg(target, text + " " + mask.nick + " requests your presence!")
self.bot.privmsg(target, ", ".join(playerlist))
@command(public=False)
@asyncio.coroutine
def group(self, mask, target, args):
"""Allows joining and leaving ping groups
%%group get
%%group join <groupname>
%%group leave <groupname>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
get, join, leave, groupname = args.get('get'), args.get('join'), args.get('leave'), args.get('<groupname>')
playergroups = self.__dbGet(['groups', 'playergroups'])
if get:
self.bot.privmsg(mask.nick, str(len(playergroups)) + " groups: ")
for g in playergroups.keys():
players = playergroups[g].get('players', {})
isMember = ""
if players.get(mask.nick):
isMember = " You are member of this group."
self.bot.privmsg(mask.nick, 'Group {name} with {num} users.{ismember}'.format(**{
"name": g,
"num": len(players),
"ismember" : isMember,
}))
return
if not playergroups.get(groupname):
return "Group does not exist."
players = playergroups[groupname].get('players', {})
if join:
self.__dbAdd(['groups', 'playergroups', groupname, 'players'], mask.nick, True)
elif leave:
if not players.get(mask.nick):
return "You are not in this group."
self.__dbDel(['groups', 'playergroups', groupname, 'players'], mask.nick)
return "Done."
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def groupmanage(self, mask, target, args):
"""Allows admins to manage groups
%%groupmanage get
%%groupmanage add <groupname> TEXT ...
%%groupmanage del <groupname>
%%groupmanage join <groupname> <playername>
%%groupmanage leave <groupname> <playername>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
get, add, delete, join, leave, groupname, playername, TEXT = args.get('get'), args.get('add'), args.get('del'), args.get('join'), args.get('leave'), args.get('<groupname>'), args.get('<playername>'), " ".join(args.get('TEXT'))
playergroups = self.__dbGet(['groups', 'playergroups'])
if get:
self.bot.privmsg(mask.nick, str(len(playergroups)) + " groups: ")
for g in playergroups.keys():
players = playergroups[g].get('players', {})
self.bot.privmsg(mask.nick, 'Group {name} with {num} users: {players}'.format(**{
"name": g,
"num": len(players),
"players": ", ".join(players),
}))
return
if add:
if groupname in playergroups.keys():
self.__dbAdd(['groups', 'playergroups', groupname], 'text', TEXT, overwriteIfExists=True)
return "Group with that name already exists. The old message was replaced, player list stays."
self.__dbAdd(['groups', 'playergroups'], groupname, {'text' : TEXT, 'players' : {}})
return "Done."
if not playergroups.get(groupname):
return "Group does not exist."
players = playergroups[groupname].get('players', {})
if delete:
self.__dbDel(['groups', 'playergroups'], groupname)
elif join:
self.__dbAdd(['groups', 'playergroups', groupname, 'players'], playername, True)
elif leave:
if not players.get(playername):
return "The player is not in this group."
self.__dbDel(['groups', 'playergroups', groupname, 'players'], playername)
return "Done."
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def blacklist(self, mask, target, args):
"""Blacklist given channel/user from !casts, !streams
%%blacklist get
%%blacklist add USER ...
%%blacklist del USER ...
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
add, delete, get, user = args.get('add'), args.get('del'), args.get('get'), " ".join(args.get('USER'))
if get:
for user in self.__dbGet(['blacklist', 'users']).keys():
self.bot.privmsg(mask.nick, '- '+user)
return
if user is not None:
users = self.__dbGet(['blacklist', 'users'])
if add:
self.__dbAdd(['blacklist', 'users'], user, True)
return "Added {} to blacklist".format(user)
if delete:
if users.get(user):
self.__dbDel(['blacklist', 'users'], user)
return "Removed {} from the blacklist".format(user)
return "{} is not on the blacklist.".format(user)
return "Something went wrong."
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def badwords(self, mask, target, args):
"""Adds/removes a given keyword from the checklist
%%badwords get
%%badwords add <word> <gravity>
%%badwords del <word>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
global BADWORDS
add, delete, get, word, gravity = args.get('add'), args.get('del'), args.get('get'), args.get('<word>'), args.get('<gravity>')
if add:
try:
word = word.lower()
BADWORDS, _, _ = self.__dbAdd(['badwords', 'words'], word, int(gravity), True)
return 'Added "{word}" to watched badwords with gravity {gravity}'.format(**{
"word": word,
"gravity": gravity,
})
except:
return "Failed adding the word. Did you not use a number for the gravity?"
elif delete:
if BADWORDS.get(word):
BADWORDS = self.__dbDel(['badwords', 'words'], word)
return 'Removed "{word}" from watched badwords'.format(**{
"word": word,
})
else:
return 'Word not found in the list.'
elif get:
words = BADWORDS
self.bot.privmsg(mask.nick, str(len(words)) + " checked badwords:")
for word in words.keys():
self.bot.privmsg(mask.nick, '- word: "%s", gravity: %s' % (word, words[word]))
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def reactionwords(self, mask, target, args):
"""Adds/removes a given keyword from the checklist.
"{sender}" in the reply text will be replaced by the name of the person who triggered the response.
%%reactionwords get
%%reactionwords add <word> REPLY ...
%%reactionwords del <word>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
global REACTIONWORDS
add, delete, get, word, reply = args.get('add'), args.get('del'), args.get('get'), args.get('<word>'), " ".join(args.get('REPLY'))
if add:
try:
REACTIONWORDS, _, _ = self.__dbAdd(['reactionwords', 'words'], word.lower(), reply)
return 'Added "{word}" to watched reactionwords with reply: "{reply}"'.format(**{
"word": word,
"reply": reply,
})
except:
return "Failed adding the word."
elif delete:
words = self.__dbGet(['reactionwords', 'words'])
if words.get(word):
REACTIONWORDS = self.__dbDel(['reactionwords', 'words'], word)
return 'Removed "{word}" from watched reactionwords'.format(**{
"word": word,
})
else:
return 'Word not found in the list.'
elif get:
words = self.__dbGet(['reactionwords', 'words'])
self.bot.privmsg(mask.nick, str(len(words)) + " checked reactionwords:")
for word in words.keys():
self.bot.privmsg(mask.nick, '- word: "%s", reply: %s' % (word, words[word]))
@command(permission='admin', public=False, show_in_help_list=False)
@asyncio.coroutine
def repeat(self, mask, target, args):
"""Makes QAI repeat WORDS in <channel> each <seconds>. Use <ID> to remove them again.
%%repeat get
%%repeat add <ID> <seconds> <channel> WORDS ...
%%repeat del <ID>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
global REPETITIONS
add, delete, get, ID, seconds, channel, WORDS = args.get('add'), args.get('del'), args.get('get'), args.get('<ID>'), args.get('<seconds>'), args.get('<channel>'), " ".join(args.get('WORDS'))
text = self.__dbGet(['repetitions', 'text'])
if get:
self.bot.privmsg(mask.nick, str(len(text)) + " texts repeating:")
for t in text.keys():
self.bot.privmsg(mask.nick, ' ID: "%s", each %i seconds, channel: %s, text: %s' % (t, text[t].get('seconds'), text[t].get('channel'), text[t].get('text')))
elif add:
try:
if text.get(ID):
return "ID already exists. Pick another."
self.__dbAdd(['repetitions', 'text'], ID, {
"seconds": int(seconds),
"text": WORDS,
"channel": channel,
})
REPETITIONS[ID] = repetition.repetitionThread(self.bot, channel, WORDS, int(seconds))
REPETITIONS[ID].daemon = True
REPETITIONS[ID].start()
return 'Done.'
except:
return "Failed adding the text."
elif delete:
try:
if text.get(ID):
self.__dbDel(['repetitions', 'text'], ID)
REPETITIONS[ID].stop()
del REPETITIONS[ID]
return 'Done.'
else:
return "Not repeating something with ID <" + ID + ">"
except:
return "Failed deleting."
@command(permission='chatlist', show_in_help_list=False)
@asyncio.coroutine
def move(self, mask, target, args):
"""Move nick into channel
%%move <nick> <channel>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
channel, nick = args.get('<channel>'), args.get('<nick>')
self.move_user(channel, nick)
self.bot.privmsg(mask.nick, "OK moved %s to %s" % (nick, channel))
@command(permission='chatlist', show_in_help_list=False)
@asyncio.coroutine
def chatlist(self, mask, target, args):
"""Chat lists
%%chatlist
%%chatlist <channel>
%%chatlist add <channel> <user>
%%chatlist del <channel> <user>
"""
if not (yield from self.__isNickservIdentified(mask.nick)):
return
channel, user, add, remove = args.get('<channel>'), args.get('<user>'), args.get('add'), args.get('del')
if not add and not remove:
if not channel:
self.bot.privmsg(mask.nick, ", ".join(self.__dbGet(['chatlists'])))
else:
self.bot.privmsg(mask.nick, ", ".join(self.__dbGet(['chatlists', channel]).keys()))
elif add:
self.__dbAdd(['chatlists', channel], user, True)
self.move_user(channel, user)
self.bot.privmsg(mask.nick, "OK added and moved %s to %s" % (user, channel))
elif remove:
remaining = self.__dbDel(['chatlists', channel], user)
if len(remaining) == 0:
self.__dbDel(['chatlists'], channel)
self.bot.privmsg(mask.nick, "OK removed %s from %s" % (user, channel))
@command
def google(self, mask, target, args):
"""google
%%google WORDS ...
"""
link = LETMEGOOGLE + "+".join(args.get('WORDS'))
self.bot.privmsg(target, link)
@command
def name(self, mask, target, args):
"""name
%%name
%%name <username>
%%name <username> WORDS ...
"""
name = args.get('<username>')
if name == None:
self.bot.privmsg(target, LINKS["namechange"])
return
link = OTHER_LINKS["oldnames"] + name
self.bot.privmsg(target, link)
@command
@asyncio.coroutine
def tourneys(self, mask, target, args):
"""Check tourneys
%%tourneys
"""
if self.spam_protect('tourneys', mask, target, args):
return
tourneys = yield from challonge.printable_tourney_list()
if len(tourneys) < 1:
self.bot.privmsg(target, "No tourneys found!")
self.bot.privmsg(target, str(len(tourneys)) + " tourneys:")
for tourney in tourneys:
self.bot.action(target, tourney)
def report(self, name, word, channel, text, gravity):
reportMsg = 'User "{name}" used bad word "{word}" in irc channel "{channel}". Full text: "{text}". (Gravity {gravity})'.format(**{
'name' : name,
'word' : word,
'channel' : channel,
'text' : text,
'gravity' : gravity,
})
if gravity >= self.bot.config['report_to_irc_threshold']:
self.bot.privmsg('#' + self.bot.config['report_to_irc_channel'], reportMsg)
if gravity >= self.bot.config['report_to_slack_threshold']:
self.slackThread.sendMessageToChannel(self.bot.config['report_to_slack_channel'], reportMsg)
if gravity >= self.bot.config['report_instant_kick_threshold']:
self._taunt(channel=channel, prefix=name, tauntTable=KICK_TAUNTS)
self.bot.privmsg(channel, "!kick {}".format(name))
def __dbAdd(self, path, key, value, overwriteIfExists=True, trySavingWithNewKey=False):
cur = self.bot.db
for p in path:
if p not in cur:
cur[p] = {}
cur = cur[p]
exists, addedWithNewKey = cur.get(key), False
if overwriteIfExists:
cur[key] = value
elif not exists:
cur[key] = value
elif exists and trySavingWithNewKey:
for i in range(0, 1000):
if not cur.get(key+str(i)):
cur[key+str(i)] = value
addedWithNewKey = True
break
self.__dbSave()
return cur, exists, addedWithNewKey
def __dbDel(self, path, key):
cur = self.bot.db
for p in path:
cur = cur.get(p, {})
if not cur.get(key) is None:
del cur[key]
self.__dbSave()
return cur
def __dbGet(self, path):
reply = self.bot.db
for p in path:
reply = reply.get(p, {})
return reply
def __dbSave(self):
self.bot.db.set('misc', lastSaved=time.time())