-
Notifications
You must be signed in to change notification settings - Fork 4
/
moderator-bot.py
1385 lines (1244 loc) · 58.2 KB
/
moderator-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 python3
# -*- coding: utf-8 -*-
#
# moderator-bot.py
#
# Copyright 2012 Zach McCullough <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import json
import urllib.request
import time
import re
import signal
import sys
from urllib.parse import urlencode
from collections import defaultdict
import random
from praw.handlers import MultiprocessHandler
import praw
import bz2
import operator
import requests
try:
from credentials import * # NOQA
except:
USERNAME = 'botname'
PASSWORD = 'botpass'
USERAGENT = 'moderator-bot.py v4'
SUBREDDIT = 'subtomonitor'
HEADER_TAGS = {'start': '[](#heditstart)', 'stop': '[](#heditstop)'}
SIDEBAR_TAGS = {'start': '[](#sbeditstart)', 'stop': '[](#sbeditstop)'}
GREENTEXT = "[](#status_green '{} is online')"
REDTEXT = "[](#status_red '{}' is offline')"
BOTSUB = 'botprivatesub'
LOGFILE = '/some/file/to/log/to.html'
SERVERDOMAINS = 'http://example.com/server_domain_list.csv'
DATABASEFILE = '/some/path'
CACHEFILE = '/some/other/path'
STATUS_JSON = 'http://somesite.com/some.json'
VERSION_JSON = 'http://someothersite.com/some.json'
IMGUR_CLIENT_ID = 'someid'
def p(data, end='\n', color_seed=None):
if color_seed:
random.seed(color_seed)
color = '\033[0;3{}m'.format(random.randint(1, 6))
else:
color = ''
print(time.strftime(
'\r\033[K\033[2K[\033[31m%y\033[39m/\033[31m%m\033[39m/\033[31m%d'
'\033[39m][\033[31m%H\033[39m:\033[31m%M\033[39m:\033[31m%S\033[39m] ')
+ color + data + '\033[39m', end=end)
def logToDisk(log_text):
log_start = (
"<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><titl"
"e>{username} modlog</title></head><body>".format(username=USERNAME))
log_end = "</body>"
entry_base = "<div class=\"entry\"><span>{time}</span> {data}</div>".format(
time=time.strftime('[%y/%m/%d][%H:%M:%S]'), data=log_text)
with open(LOGFILE) as l:
log = l.read().strip()
log = log[len(log_start):-len(log_end)]
split_log = log.split('\n')
if len(split_log) < 1000:
log = '\n'.join(split_log)
else:
log = '\n'.join(split_log[1:])
with open(LOGFILE, 'w') as l:
l.write(log_start + entry_base + log + log_end)
def sigint_handler(signal, frame):
'''Handles ^c'''
p('Recieved SIGINT! Exiting...')
sys.exit(0)
def sidebarUpdater():
'''Returns the status indicator for /r/Minecraft's sidebar'''
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USERAGENT)]
try:
with opener.open(STATUS_JSON, timeout=30) as w:
status = json.loads(w.read().decode('utf-8'))['report']
except:
return None
try:
with opener.open(VERSION_JSON, timeout=30) as w:
version = json.loads(w.read().decode('utf-8'))['latest']
except:
return None
text = []
for i in ('website', 'login', 'session', 'skins', 'realms'):
if status[i]['status'] == 'up':
text.append("> [{} is online.](#status_green_{} '{} - {}')".format(
i.title(), i, i.title(), status[i]['title'].split()[0]))
elif status[i]['status'] == 'problem':
text.append(
"> [{} is having a problem.]"
"(#status_green_{} '{} - {}')".format(
i.title(), i, i.title(), status[i]['title']))
elif status[i]['status'] == 'down':
text.append("> [{} is offline.](#status_red_{} '{} - {}')".format(
i.title(), i, i.title(), status[i]['title'].split('•')[0].strip()))
status_text = '\n{}\n'.format('\n'.join(text))
version_text = '\n>Stable: {} | Snapshot: {}'.format(version['release'], version['snapshot'])
return status_text + version_text
def cache_url():
"""Url caching decorator. For decorating class functions that take a single url as an arg
and return the response."""
def wrap(function):
def new_function(*args):
url = args[1]
expire_after = args[0].cache_time
try:
with bz2.open(CACHEFILE, 'rt') as f:
d = json.loads(f.read())
except (IOError, ValueError):
d = dict()
if 'cache' not in d:
d['cache'] = dict()
if url in d['cache']:
output = d['cache'][url]
expire_time = output['time'] + expire_after
if expire_after == 0 or time.time() < expire_time:
return output['data']
else:
del d['cache'][url]
output = function(*args)
if output:
to_cache = {'time': time.time(), 'data': output}
d['cache'][url] = to_cache
with bz2.open(CACHEFILE, 'wt') as f:
f.write(json.dumps(d))
return output
return new_function
return wrap
class Imgur(object):
def __init__(self, client_id, cache_time=86400):
self.opener = urllib.request.build_opener()
self.opener.addheaders = [
('User-agent', USERAGENT),
('Authorization', 'Client-id {}'.format(client_id))]
self.last_request = 0
self.cache_time = cache_time
@cache_url()
def _request(self, url):
try:
since_last = time.time() - self.last_request
if not since_last >= 2:
time.sleep(2 - since_last)
with self.opener.open(url, timeout=30) as w:
imgur = w.read().decode('utf-8')
imgur = json.loads(imgur)['data']
except:
self.last_request = 0
return None
if 'error' not in imgur:
return imgur
def _get_ids(self, url):
"""Turns a url into a set of imgur ids"""
url = url.split('#')[0]
if url.endswith('/'):
url = url[:-1]
if url.endswith('/all'):
url = url[:-4]
url = re.split(r'''imgur.com(?:/gallery|/a|/r/.*?)?/''', url)[1]
ids = set(re.split(r''',|&''', url))
return ids
def _get(self, imgur_id, use_gallery, force_single=False):
"""Returns a list containing a dicts of titles/descriptions for images and galleries."""
"""We try the imgur_id as a album first, and if that fails we assume it's an individual"""
"""image. If force_single is True, we skip the initial album try."""
p("Checking imgur id {}...".format(imgur_id), end="", color_seed=imgur_id)
if use_gallery:
urls = {
'album': 'https://api.imgur.com/3/gallery/album/{}.json',
'image': 'https://api.imgur.com/3/gallery/image/{}.json'}
else:
urls = {
'album': 'https://api.imgur.com/3/album/{}.json',
'image': 'https://api.imgur.com/3/image/{}.json'}
if not force_single:
output = list()
imgur = self._request(urls['album'].format(imgur_id))
if imgur:
output.append({'title': imgur['title'], 'description': imgur['description']})
for i in imgur['images']:
output.append({'title': i['title'], 'description': i['description']})
return output
imgur = self._request(urls['image'].format(imgur_id))
if imgur:
return [{'title': imgur['title'], 'description': imgur['description']}]
def get(self, url):
"""Returns a list of dicts of the title/description of images/galleries"""
output = list()
ids = self._get_ids(url)
if 'gallery' in url.lower():
use_g = True
else:
use_g = False
# we can assume that if we have a list, that they're all individual images
if len(ids) > 1:
for i in ids:
imgur = self._get(i, use_g)
if imgur:
output.extend(imgur)
else:
imgur = self._get(ids.pop(), use_g)
if imgur:
output = imgur
return output
class Youtube(object):
def __init__(self, cache_time=0):
self.opener = urllib.request.build_opener()
self.opener.addheaders = [('User-agent', USERAGENT)]
self.last_request = 0
self.cache_time = cache_time
@cache_url()
def _request(self, url):
try:
since_last = time.time() - self.last_request
if not since_last >= 2:
time.sleep(2 - since_last)
with self.opener.open(url, timeout=30) as w:
youtube = w.read().decode('utf-8')
yt_json = json.loads(youtube)
except:
self.last_request = time.time()
return None
if 'errors' not in yt_json:
return yt_json['entry']
def _get_id(self, url):
# regex via: http://stackoverflow.com/questions/3392993/php-regex-to-get-youtube-video-id
regex = re.compile(
r'''(?<=(?:v|i)=)[a-zA-Z0-9-]+(?=&)|(?<=(?:v|i)\/)[^&\n]+|(?<=embed\/)[^"&\n]+|'''
r'''(?<=(?:v|i)=)[^&\n]+|(?<=youtu.be\/)[^&\n]+''', re.I)
yt_id = regex.findall(
url.replace('%3D', '=').replace('%26', '&').replace('%2F', '?').replace('&', '&'))
if yt_id:
# temp fix:
yt_id = yt_id[0].split('#')[0]
yt_id = yt_id.split('?')[0]
return yt_id
def _get(self, url):
"""Decides if we're grabbing video info or a profile."""
urls = {
'profile': 'http://gdata.youtube.com/feeds/api/users/{}?v=2&alt=json',
'video': 'http://gdata.youtube.com/feeds/api/videos/{}?v=2&alt=json'}
yt_id = self._get_id(url)
if yt_id:
return self._request(urls['video'].format(yt_id))
else:
username = re.findall(r'''(?i)\.com\/(?:user\/|channel\/)?(.*?)(?:\/|\?|$)''', url)
if username:
return self._request(urls['profile'].format(username[0]))
def get_author(self, url):
"""Returns the author id of the youtube url"""
output = self._get(url)
if output:
# There has to be a reason for the list in there...
return output['author'][0]['yt$userId']['$t']
def get_info(self, url):
"""Returns the title and description of a video."""
output = self._get(url)
if output:
if 'media$group' in output:
title = output['title']['$t']
description = output['media$group']['media$description']['$t']
return {'title': title, 'description': description}
def is_video(self, url):
if self._get_id(url) is not None:
return True
else:
return False
class Filter(object):
"""Base filter class"""
def __init__(self):
self.regex = None
self.comment_template = (
"##This submission has been removed automatically.\nAccording to our [subreddit rules]("
"/r/{sub}/wiki/rules/) {reason}. If you feel this was in error, please [message the mo"
"derators](/message/compose/?to=/r/{sub}&subject=Removal%20Dispute&message={link}). If"
" this submission was removed in error, do not delete it. The moderators will fix this"
" submission.")
self.comment = ""
self.tag = ""
self.action = 'remove'
self.log_text = ""
self.ban = False
self.report_subreddit = None
self.nuke = True
self.reddit = None
def filterComment(self, comment):
raise NotImplementedError
def filterSubmission(self, submission):
raise NotImplementedError
def runFilter(self, post):
if 'title' in vars(post):
try:
if self.filterSubmission(post):
if self.log_text:
logToDisk(self.log_text)
return True
except NotImplementedError:
pass
elif 'body' in vars(post):
try:
if self.filterComment(post):
if self.log_text:
logToDisk(self.log_text)
return True
except NotImplementedError:
pass
class Suggestion(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(
r'''((?:\[|<|\(|{|\*|\|)?sug*estion(?:\s|s?\]|s?>|s?\)|:|}|\*|\|'''
r''')|(?:^|\[|<|\(|{|\*|\|)ideas?(?:\]|>|\)|:|}|\*|\|))''', re.I)
def filterSubmission(self, submission):
if self.regex.search(submission.title):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
if submission.domain != 'self.{}'.format(submission.subreddit):
reason = "suggestions must be self-post only"
self.log_text = "Found [Suggestion] submission that is not a self post"
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
elif not submission.selftext:
self.log_text = "Found [Suggestion] submission that has no self text"
reason = (
"suggestion posts must have a description along with them, which is something y"
"ou cannot convey with only a title")
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
class Fixed(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(
r'''[\[|<\({\*]fixed[\]|>\):}\*]|'''
r'''i(?:'?ll)? see you'?re?,? .*? and (?:i(?:'?ll)? )?raise you''', re.I)
self.log_text = "Found [Fixed] submission"
def filterSubmission(self, submission):
if self.regex.search(submission.title):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
reason = "[Fixed] submissions are not allowed"
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
class ServerAd(Filter):
def __init__(self, reddit, imgur, youtube):
self.last_update = 0
self.domain_list = []
Filter.__init__(self)
self.reddit = reddit
self.imgur = imgur
self.y = youtube
self.tag = "[Server Spam]"
self.regex = re.compile(
r'''(?:^|\s|ip(?:=|:)|\*)(\d{1,3}(?:\.\d{1,3}){3})\.?(?:\s|$|:|\*|!|\.|,|;|\?)''', re.I)
def _update_list(self):
if (time.time() - self.last_update) >= 1800:
self.last_update = time.time()
p('Updating domain blacklist...', end='')
blacklist = self.reddit.get_wiki_page(SUBREDDIT, 'server_blacklist')
blacklist = blacklist.content_md
domain_list = [
i.replace(' ', '') for i in re.split(r'''[\r\n]*''', blacklist) if not
i.startswith("//")]
domain_list = [i for i in domain_list if i]
if len(self.domain_list) < len(domain_list):
p('Found {} new domains in online blacklist.'.format(
len(domain_list) - len(self.domain_list)))
elif len(self.domain_list) > len(domain_list):
p('Removed {} domains from the online blacklist'.format(
len(self.domain_list) - len(domain_list)))
self.domain_list = domain_list
def _server_in(self, text):
self._update_list()
if text:
for i in self.domain_list:
if i.lower() in text.lower():
return True
try:
ips = self.regex.findall(text)
for ip in ips:
if ip:
split_ip = [int(i) for i in ip.split('.')]
if split_ip[0] == 10:
return False
elif split_ip[:3] == [127, 0, 0]:
return False
elif split_ip[:2] == [192, 168]:
return False
elif split_ip == [0] * 4:
return False
for i in split_ip:
if not i <= 255:
return False
return True
else:
return False
except ValueError:
return False
def _imgur_check(self, url):
'''Takes a imgur url and returns True if a server ad is found in the title or description'''
url = url.replace('&', '&')
image_list = self.imgur.get(url)
for i in image_list:
if i['description']:
if self._server_in(i['description']):
return True
if i['title']:
if self._server_in(i['title']):
return True
return False
def _planet_minecraft_check(self, url):
'''Takes a planet minecraft url and returns True if a server ad is found in its
description'''
url = url.replace('&', '&')
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USERAGENT)]
try:
with opener.open(url, timeout=30) as w:
page = w.read().lower().replace('\n', '')
page = re.findall(r'''r-text-block">(.*?)</div>''', page)[0]
except:
return None
if page:
if self._server_in(page):
return True
def _sidebar_check(self, subreddit):
try:
subreddit = self.reddit.get_subreddit(subreddit)
sidebar = subreddit.description
to_replace = (('&', '&'), ('>', '>'), ('<', '<'))
for i in to_replace:
sidebar = sidebar.replace(*i)
if self._server_in(sidebar):
return True
except praw.errors.InvalidSubreddit:
return None
def filterSubmission(self, submission):
self.comment = ''
reason = "server advertisements are not allowed; please use /r/mcservers"
if self._server_in(submission.title) or\
self._server_in(submission.selftext) or\
self._server_in(submission.url[7:]):
self.log_text = "Found server advertisement in submission"
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
elif submission.domain == 'imgur.com':
if self._imgur_check(submission.url):
self.log_text = "Found server advertisement in submission"
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link)
return True
elif submission.domain in ('m.youtube.com', 'youtube.com', 'youtu.be'):
yt = self.y.get_info(submission.url)
if yt:
if self._server_in(yt['title']) or self._server_in(yt['description']):
self.log_text = "Found server advertisement in submission"
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
elif submission.domain == 'planetminecraft.com':
if self._planet_minecraft_check(submission.url):
self.log_text = "Found server advertisement in submission"
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link)
return True
def filterComment(self, comment):
if self._server_in(comment.body):
self.comment = ''
self.log_text = "Found server advertisement in comment"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id)
return True
else:
try:
subreddits = re.findall(r'''/r/([\w-]+)''', comment.body)
for subreddit in subreddits:
if self._sidebar_check(subreddit):
self.comment = ''
self.log_text = "Found server advertisement in subreddit link"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id)
return True
except (praw.errors.RedirectException, requests.exceptions.HTTPError):
pass
class FreeMinecraft(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.tlds = r'''[\[\(\{]*?(?:\.|dot|\s)[\]\)\}]*?(?:me|info|com|net|org|ru|co\.uk|us)'''
self.regex = re.compile(
r'''(free|cracked)?-?minecraft-?(install|get|'''
r'''(?:gift-?)?codes?(?:-?gen(?:erator)?)?|rewards?|acc(?:t|ount)s?(?:free)?|now|'''
r'''forever)?(?:\.blogspot)?'''
+ self.tlds,
re.I)
self.domain_list = '''
epicfreeprizes
freemspointsforever
litekoin
ccincc
steampowers
cardcodes
minecraftpromotions
mojangpromotions
'''.split()
self.action = 'spammed'
self.ban = True
def check(self, thing):
result = self.regex.findall(thing)
if isinstance(result, list):
for i in result:
if i != ('', ''):
return True
if result:
return True
else:
for domain in self.domain_list:
if re.findall(domain + self.tlds, thing):
return True
def filterSubmission(self, submission):
for i in (submission.title, submission.selftext, submission.url):
if self.check(i):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.log_text = "Found free Minecraft link in submission"
reason = "free minecraft links are not allowed"
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
def filterComment(self, comment):
if self.check(comment.body):
self.comment = ''
self.log_text = "Found free minecraft link in comment"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id)
return True
class AmazonReferral(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(
r'''amazon\.(?:at|fr|com|ca|cn|de|es|it|co\.(?:jp|uk)).*?tag=[^&]*?-\d+''', re.I)
self.action = 'spammed'
def filterSubmission(self, submission):
if self.regex.search(submission.title) or\
self.regex.search(submission.selftext) or\
self.regex.search(submission.url):
self.log_text = "Found Amazon referral link in submission"
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
def filterComment(self, comment):
if self.regex.search(comment.body):
self.log_text = "Found Amazon referral link in comment"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id)
return True
class ShortUrl(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(
r'''(?:bit\.ly|goo\.gl|adf\.ly|is\.gd|(?<!reddi)(?:t\.co\/)(?!m|\.uk)|tinyurl\.com|'''
r'''j\.mp|linkbitty\.com|tiny\.cc|soc\.li|ultrafiles\.net|linkbucks\.com|lnk\.co'''
r'''|qvvo\.com|ht\.ly|pulse\.me|lmgtfy\.com|\.tk|skroc\.pl|ufa\.lt|alturl\.com|'''
r'''awe\.sm|q\.gs|lat\.li)''',
re.I)
def filterSubmission(self, submission):
if self.regex.search(submission.title) or\
self.regex.search(submission.selftext) or\
self.regex.search(submission.url):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
self.log_text = "Found short url in submission"
reason = "short urls are not allowed"
self.comment = self.comment_template.format(
sub=submission.subreddit, reason=reason, link=link)
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
def filterComment(self, comment):
if self.regex.search(comment.body):
self.comment = ''
self.log_text = "Found short url in comment"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id)
return True
class Failed(Filter):
def __init__(self):
Filter.__init__(self)
def filterSubmission(self, submission):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
if submission.domain.startswith('['):
self.log_text = "Found submission with formatting in the url"
self.comment = (
"You've seemed to try to use markdown or other markup in the url field"
" when you made this submission. Markdown formatting is only for self text and comm"
"enting; other formatting code is invalid on reddit. When you make a link submissio"
"n, please only enter the bare link in the url field.\n\nFeel free to try submitti"
"ng again.")
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
elif '.' not in submission.domain:
self.log_text = "Found submission with invalid url"
self.comment = (
"The submission you've made does not have a valid url in it. Please t"
"ry resubmitting and pay special attention to what you're typing/pasting in the ur"
"l field.")
p(self.log_text + ":")
p(link, color_seed=submission.name)
return True
class Minebook(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(r'''minebook\.me''', re.I)
self.action = 'spammed'
def filterSubmission(self, submission):
if self.regex.search(submission.title) or\
self.regex.search(submission.selftext) or\
submission.domain == 'minebook.me':
self.log_text = "Found minebook in submission"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id), color_seed=submission.name)
return True
def filterComment(self, comment):
if self.regex.search(comment.body):
self.log_text = "Found minebook in comment"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.name)
class SelfLinks(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.regex = re.compile(r'''^(?:https?://|www\.)\S*$''')
def filterSubmission(self, submission):
if submission.selftext:
for i in submission.selftext.split():
if not self.regex.match(i):
break
else:
self.comment = (
"This submission has been removed automatically. You appear to ha"
"ve only included links in your self-post with no explanatory text. Please res"
"ubmit or edit your post accordingly.")
self.log_text = "Found self-post that only contained links"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id), color_seed=submission.name)
return True
class BadWords(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.action = 'report'
self.badwords = [
'gay', 'fag', 'fgt', 'fggot', 'cunt', 'slut', 'nigger', 'nigga', 'retard', 'autis',
'unedditreddit', 'subredditdrama', 'srd']
def filterSubmission(self, submission):
if not submission.num_reports:
for word in self.badwords:
if word in submission.selftext.lower() or word in submission.title.lower():
self.log_text = "Found submission for mod review"
p(self.log_text + ":", end="")
p('http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id), color_seed=submission.name,
end="")
return True
def filterComment(self, comment):
if not comment.num_reports:
for word in self.badwords:
if word in comment.body.lower():
self.log_text = "Found comment for mod review"
p(self.log_text + ":", end="")
p('http://reddit.com/r/{}/comments/{}/a/{}'.format(
comment.subreddit.display_name, comment.link_id[3:], comment.id),
color_seed=comment.link_id, end="")
return True
class YoutubeSpam(Filter):
def __init__(self, reddit, youtube):
Filter.__init__(self)
self.tag = "[Youtube Spam]"
self.reddit = reddit
self.y = youtube
def _isVideo(self, submission):
'''Returns video author name if this is a video'''
if submission.domain in ('m.youtube.com', 'youtube.com', 'youtu.be'):
return self.y.get_author(submission.url)
def _checkProfile(self, submission):
'''Returns the percentage of things that the user only contributed to themselves.
ie: submitting and only commenting on their content. Currently, the criteria is:
* linking to videos of the same author (which implies it is their account)
* commenting on your own submissions (not just videos)
these all will count against the user and an overall score will be returned. Also, we only
check against the last 100 items on the user's profile.'''
try:
start_time = time.time() - (60 * 60 * 24 * 30 * 6) # ~six months
redditor = self.reddit.get_redditor(submission.author.name)
comments = [i for i in redditor.get_comments(limit=100) if i.created_utc > start_time]
submitted = [i for i in redditor.get_submitted(limit=100) if i.created_utc > start_time]
except urllib.error.HTTPError:
# This is a hack to get around shadowbanned or deleted users
p("Could not parse /u/{}, probably shadowbanned or deleted".format(user))
return False
video_count = defaultdict(lambda: 0)
video_submissions = set()
comments_on_self = 0
initial_author = self._isVideo(submission)
for item in submitted:
video_author = self._isVideo(item)
if video_author:
video_count[video_author] += 1
video_submissions.add(item.name)
if video_count:
most_submitted_author = max(video_count.items(), key=operator.itemgetter(1))[0]
else:
return False
for item in comments:
if item.link_id in video_submissions:
comments_on_self += 1
try:
video_percent = max(
[video_count[i] / sum(video_count.values()) for i in video_count])
except ValueError:
video_percent = 0
if video_percent > .85 and sum(video_count.values()) >= 3:
spammer_value = (sum(video_count.values()) + comments_on_self) / (len(
comments) + len(submitted))
if spammer_value > .85 and initial_author == most_submitted_author:
return True
def filterSubmission(self, submission):
self.report_subreddit = None
DAY = 24 * 60 * 60
if submission.domain in ('m.youtube.com', 'youtube.com', 'youtu.be'):
link = 'http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id)
# check if we've already parsed this submission
try:
with bz2.open(DATABASEFILE, 'rt') as db:
db = json.loads(db.read())
except IOError:
db = dict()
db['users'] = dict()
db['submissions'] = list()
if submission.id in db['submissions']:
return False
if submission.author.name in db['users']:
user = db['users'][submission.author.name]
else:
user = {'checked_last': 0, 'warned': False, 'banned': False}
if time.time() - user['checked_last'] > DAY:
p("Checking profile of /u/{}".format(submission.author.name), end='')
user['checked_last'] = time.time()
if self._checkProfile(submission):
if user['warned']:
self.log_text = "Confirmed video spammer"
p(self.log_text + ":")
self.comment = ''
self.report_subreddit = 'spam'
self.ban = True
self.nuke = True
user['banned'] = True
else:
self.comment = (
"""Hello, /u/{user}, it looks like you're on the verge with submittin"""
"""g videos, so consider this a friendly warning/guideline:\n\nReddit"""
""" has [guidelines as to what constitutes spam](http://www.reddit.co"""
"""m/wiki/faq#wiki_what_constitutes_spam.3F). To summarize:\n\n* It's"""
""" not strictly forbidden to submit links to videos of yours, but pl"""
"""ease only do so in a moderate amount.\n\n* If you spend more time """
"""submitting to reddit than reading it, you're almost certainly a sp"""
"""ammer. As a rule of thumb, for every post promoting your own video"""
"""(s), you should have made 10 other submissions or comments on othe"""
"""r posts. (Bear in mind that pointless comments like "nice" and "lo"""
"""l" do not count as actual contribution.)\n\n* If your contribution"""
""" to reddit consists mostly of your own videos, and additionally if"""
""" you do not participate in this community in other ways, for examp"""
"""le by submitting other content or joining the discussion on other """
"""posts, you are a spammer.\n\n* If people historically downvote you"""
"""r links or ones similar to yours, and you feel the need to keep su"""
"""bmitting them anyway, they're probably spam.\n\nFor right now, thi"""
"""s is just a friendly message, but here in /r/{sub}, we take action"""
""" against anyone that fits the above definition.\n\nIf you feel thi"""
"""s was in error, feel free to [message the moderators](/message/com"""
"""pose/?to=/r/{sub}&subject=Video%20Spam&message={link}).""".format(
user=submission.author.name, sub=SUBREDDIT, link=link))
self.ban = False
self.nuke = False
self.log_text = "Found potential video spammer"
p(self.log_text + ":")
p("http://reddit.com/u/{}".format(submission.author.name),
color_seed=submission.author.name)
user['warned'] = True
output = True
else:
output = False
db['users'][submission.author.name] = user
db['submissions'].append(submission.id)
with bz2.open(DATABASEFILE, 'wt') as f:
f.write(json.dumps(db))
return output
class AllCaps(Filter):
def __init__(self):
Filter.__init__(self)
self.comment_template = (
"""Hey there, you seem to be yelling! You don't need to be so l"""
"""oud with your title, your submission should be the one doing the talking for you. """
"""[Here's a link to resubmit with a more appropriate title]({link} 'click here to su"""
"""bmit').""")
def filterSubmission(self, submission):
title = re.findall(r'''[a-zA-Z]''', submission.title)
title_caps = re.findall(r'''[A-Z]''', submission.title)
if len(title) > 10:
if len(title_caps) / len(title) > .7:
self.log_text = "Found submission with all-caps title"
p(self.log_text + ":")
p('http://reddit.com/r/{}/comments/{}/'.format(
submission.subreddit, submission.id), color_seed=submission.name)
params = {'title': submission.title.title(), 'resubmit': True}
if submission.selftext:
params['text'] = submission.selftext
else:
params['url'] = submission.url
self.comment = self.comment_template.format(
link='/r/{}/submit?{}'.format(submission.subreddit, urlencode(params)))
return True
class Meme(Filter):
## TODO: DEPRECIATED
def __init__(self):
Filter.__init__(self)
self.comment_template = self.comment_template + (
"\n\nYou are free to [resubmit to a more appropriate subreddit]({resubmit} 'click here "
"to resubmit').")
self.meme_sites = (
'memecreator.org', 'memegenerator.net', 'quickmeme.com', 'qkme.me', 'mememaker.net',
'knowyourmeme.com', 'weknowmemes.com', 'elol.com', 'memecdn.com', 'livememe.com',