forked from FAForever/QAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qai_plugin.py
528 lines (458 loc) · 18.9 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
# 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
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 = {}
TWITCH_STREAMS = "https://api.twitch.tv/kraken/streams/?api_version=5&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=eng&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):
def __init__(self, bot):
self.bot = bot
self.timers = {}
self._rage = {}
global ALL_TAUNTS
ALL_TAUNTS.extend(TAUNTS)
ALL_TAUNTS.extend(SPAM_PROTECT_TAUNTS)
challonge.setChallongeData(self.bot.config['challonge_username'], self.bot.config['challonge_api_key'])
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 BADWORDS
if 'badwords' in self.bot.db:
if 'words' in self.bot.db['badwords']:
global BADWORDSBADWORDS = self.bot.db['badwords'].get('words', {}) #doing this here to init BADWORDS after the bot got its db
@irc3.event(irc3.rfc.JOIN)
def on_join(self, channel, mask):
if channel == '#aeolus':
for channel in self.bot.db['chatlists']:
if mask.nick in self.bot.db['chatlists'].get(channel, {}).keys():
self.move_user(channel, 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('#', '')
if int(replayId) >= 1000000:
url = LINKS["replay"].replace("ID", replayId)
self.bot.privmsg(channel, url)
except:
pass
for badword in BADWORDS:
if badword in msg:
self.report(sender.nick, badword, channel, msg, BADWORDS[badword])
@command(permission='admin')
def taunt(self, mask, target, args):
"""Send a taunt
%%taunt
%%taunt <person>
"""
p = args.get('<person>')
if p == self.bot.config['nick']:
p = mask.nick
self._taunt(channel=target, prefix=p)
@command(permission='admin')
def explode(self, mask, target, args):
"""Explode
%%explode
"""
self.bot.action(target, "explodes")
@command(permission='admin')
def hug(self, mask, target, args):
"""Hug someone
%%hug
%%hug <someone>
"""
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')
def flip(self, mask, target, args):
"""Flip table
%%flip
"""
self.bot.privmsg(target, "(╯°□°)╯︵ ┻━┻")
@command
def join(self, mask, target, args):
"""Overtake the given channel
%%join <channel>
"""
self.bot.join(args['<channel>'])
@command(permission='admin')
def leave(self, mask, target, args):
"""Leave the given channel
%%leave
%%leave <channel>
"""
channel = args['<channel>']
if channel is None:
channel = target
self.bot.part(channel)
@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(permission='admin', public=False)
def puppet(self, mask, target, args):
"""Puppet
%%puppet <target> WORDS ...
"""
t = args.get('<target>')
m = " ".join(args.get('WORDS'))
self.bot.privmsg(t, m)
@command(permission='admin', public=False)
def reload(self, mask, target, args):
"""Reboot the mainframe
%%reload
"""
self.bot.reload(self.bot.config['nick'])
@command(permission='admin')
def slap(self, mask, target, args):
"""Slap this guy
%%slap <guy>
"""
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)))
@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 = []
for item in itertools.takewhile(lambda _: len(casts) < 5, data['items']):
channel_title = item['snippet']['channelTitle']
casts.append(item)
self.bot.action(target,
"{channel}: {title}: {link}".format(
**{
"id": item['id']['videoId'],
"title": item['snippet']['title'],
"channel": channel_title,
"description": item['snippet']['description'],
"link": "http://youtu.be/{}".format(item['id']['videoId'])
}))
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()
@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()))
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(permission='admin', public=False)
def blacklist(self, mask, target, args):
"""Blacklist given channel/user from !casts, !streams
%%blacklist
%%blacklist <user>
"""
if 'blacklist' not in self.bot.db:
self.bot.db['blacklist'] = {'users': {}}
user = args.get('<user>')
if user is not None:
users = self.bot.db['blacklist'].get('users', {})
users[user] = True
self.bot.db.set('blacklist', users=users)
return "Added {} to blacklist".format(user)
else:
return self.bot.db['blacklist'].get('users', {})
@command(permission='admin', public=False)
def badwords(self, mask, target, args):
"""Adds/removes a given keyword from the checklist
%%badwords get
%%badwords add <word> <gravity>
%%badwords del <word>
"""
global BADWORDS
if 'badwords' not in self.bot.db:
self.bot.db['badwords'] = {'words': {}}
add, delete, get, word, gravity = args.get('add'), args.get('del'), args.get('get'), args.get('<word>'), args.get('<gravity>')
if add:
try:
words = self.bot.db['badwords'].get('words', {})
words[word] = int(gravity)
self.bot.db.set('badwords', words=words)
BADWORDS = words
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:
words = self.bot.db['badwords'].get('words', {})
if words.get(word):
del self.bot.db['badwords']['words'][word]
BADWORDS = self.bot.db['badwords'].get('words', {})
return 'Removed "{word}" from watched badwords'.format(**{
"word": word,
})
else:
return 'Word not found in the list.'
elif get:
words = self.bot.db['badwords'].get('words', {})
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='chatlist')
def move(self, mask, target, args):
"""Move nick into channel
%%move <nick> <channel>
"""
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')
def chatlist(self, mask, target, args):
"""Chat lists
%%chatlist
%%chatlist <channel>
%%chatlist add <channel> <user>
%%chatlist del <channel> <user>
"""
print(args)
if 'chatlists' not in self.bot.db:
self.bot.db['chatlists'] = {}
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, repr(self.bot.db.get('chatlists')))
else:
self.bot.privmsg(mask.nick, repr(self.bot.db['chatlists'].get(channel, {}).keys()))
elif add:
if channel not in self.bot.db['chatlists']:
self.bot.db['chatlists'][channel] = {}
self.bot.db['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:
if channel not in self.bot.db['chatlists']:
self.bot.db['chatlists'][channel] = {}
del self.bot.db['chatlists'][channel][user]
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))