-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddititalybot.py
348 lines (318 loc) · 16.2 KB
/
reddititalybot.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
# coding=utf8
import html
import logging
import re
import sys
import time
import datetime
from praw import Reddit
from praw.models.reddit.comment import Comment
from praw.models.reddit.submission import Submission
import yaml
class Bot(object):
def __init__(self, r):
self.r = r
logging.info('Success.')
self.subreddits = {}
for subreddit in SUBREDDITS:
logging.info('Checking subreddit: %s', subreddit)
self.subreddits[subreddit] = {}
sub = self.subreddits[subreddit]
logging.info('Loading mods')
sub['mods'] = list(mod.name for mod in
self.r.subreddit(subreddit).moderator())
logging.info('Mods loaded: %s.', sub['mods'])
logging.info('Loading reasons')
sub['reasons'] = yaml.load(html.unescape(
self.r.subreddit(subreddit).wiki['ribconf'].content_md))
logging.info('Reasons loaded.')
def refresh_sub(self, subreddit):
logging.info('Refreshing subreddit: %s', subreddit)
sub = self.subreddits[subreddit]
logging.info('Loading mods')
sub['mods'] = list(mod.name for mod in
self.r.subreddit(subreddit).moderator())
logging.info('Mods loaded: %s.', sub['mods'])
logging.info('Loading reasons')
sub['reasons'] = yaml.load(html.unescape(
self.r.subreddit(subreddit).wiki['ribconf'].content_md))
logging.info('Reasons loaded.')
def check_comments(self, subreddit):
logging.info('Checking subreddit: %s', subreddit)
sub = self.subreddits[subreddit]
for comment in self.r.subreddit(subreddit).comments(limit=100):
if (comment.banned_by or not comment.author or
comment.author.name not in sub['mods']):
continue
report = {'source': comment, 'reason': comment.body,
'author': comment.author.name}
self.handle_report(subreddit, report, comment.parent())
def check_reports(self, subreddit):
logging.info('Checking subreddit reports: %s', subreddit)
for reported_submission in self.r.subreddit(subreddit).mod.reports():
if not reported_submission.mod_reports:
continue
report = {'reason': reported_submission.mod_reports[0][0],
'author': reported_submission.mod_reports[0][1]}
self.handle_report(subreddit, report, reported_submission)
def handle_report(self, subreddit, report, target):
sub = self.subreddits[subreddit]
# Check for @m command.
match = re.search(r'@m (\w*) *(.*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
rule = match.group(1)
note = match.group(2)
logging.info('Rule %s matched.', rule)
if rule not in sub['reasons']:
rule = 'Generic'
msg = sub['reasons'][rule]['Message']
if note:
msg = '{}\n\n{}'.format(msg, note)
if 'source' in report:
report['source'].mod.remove()
target.mod.remove()
if isinstance(target, Submission):
logging.info('Removed submission.')
header = sub['reasons']['Header'].format(
author=target.author.name, permalink2=target.permalink)
footer = sub['reasons']['Footer'].format(
author=target.author.name, permalink2=target.permalink)
msg = '{header}\n\n{msg}\n\n{footer}'.format(
header=header, msg=msg, footer=footer)
target.reply(msg).mod.distinguish(sticky=True)
target.mod.flair(sub['reasons'][rule]['Flair'])
permalink = target.permalink
elif isinstance(target, Comment):
logging.info('Removed comment.')
header = sub['reasons']['Headerc'].format(
author=target.author.name, permalink2=target.permalink)
footer = sub['reasons']['Footer'].format(
author=target.author.name, permalink2=target.permalink)
msg = '{header}\n\n{msg}\n\n{footer}'.format(
header=header, msg=msg, footer=footer)
target.reply(msg).mod.distinguish(sticky=True)
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "removed", rule, target.author.name, permalink, report, ))
# Check for @s command.
match = re.search(r'@s (\w*) *(.*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
rule = match.group(1)
note = match.group(2)
logging.info('Rule Special %s matched.', rule)
if rule not in sub['reasons']:
rule = 'Generic'
msg = sub['reasons'][rule]['Message']
if note:
msg = '{}\n\n{}'.format(msg, note)
if 'source' in report:
report['source'].mod.approve()
target.mod.approve()
if isinstance(target, Submission):
logging.info('Stickied message to submission.')
headerl = sub['reasons']['Headerl'].format(
author=target.author.name, permalink2=target.permalink)
footerl = sub['reasons']['Footerl'].format(
author=target.author.name, permalink2=target.permalink)
msg = '{headerl}\n\n{msg}\n\n{footerl}'.format(
headerl=headerl, msg=msg, footerl=footerl)
target.reply(msg).mod.distinguish(sticky=True)
target.mod.flair(sub['reasons'][rule]['Flair'])
permalink = target.permalink
elif isinstance(target, Comment):
logging.info('Stickied message to comment.')
headerl = sub['reasons']['Headerl'].format(
author=target.author.name, permalink2=target.permalink)
footerl = sub['reasons']['Footerl'].format(
author=target.author.name, permalink2=target.permalink)
msg = '{headerl}\n\n{msg}\n\n{footerl}'.format(
headerl=headerl, msg=msg, footerl=footerl)
target.reply(msg).mod.distinguish(sticky=True)
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "stickied", rule, target.author.name, permalink, report, ))
# Check for @spam command.
if report['reason'].lower().startswith('@spam'):
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
if 'source' in report:
report['source'].mod.remove()
target.mod.remove(spam=True)
if isinstance(target, Submission):
logging.info('Removed submission (spam).')
permalink = target.permalink
elif isinstance(target, Comment):
logging.info('Removed comment (spam).')
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "removed spam", rule, target.author.name, permalink, report, ))
# Check for @ban command.
match = re.search(r'@ban (\d*) "([^"]*)" "([^"]*)"', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
duration = match.group(1)
reason = match.group(2)
msg = match.group(3)
logging.info('Ban (%s: %s -- %s) matched.', duration, reason,
msg)
if 'source' in report:
report['source'].mod.remove()
target.mod.remove()
self.r.subreddit(subreddit).banned.add(
target.author.name, duration=duration, note=reason,
ban_message=msg)
logging.info('User banned.')
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | | {} \n".format(timestamp, report['author'], "ban", 'ban', target.author.name, report))
# Check for @ban2 command.
match = re.search(r'@ban2', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
reason = "{} banned by {}".format(target.author.name, report['author'])
logging.info('Ban2 matched. Reason: %s', reason)
if 'source' in report:
report['source'].mod.remove()
target.mod.remove()
self.r.subreddit(subreddit).banned.add(
target.author.name, note=reason,
ban_message='http://reddit.com/r/italy/wiki/ban_informations')
logging.info('User banned.')
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | | {} \n".format(timestamp, report['author'], "ban2", 'ban', target.author.name, report))
# Check for @bant command.
match = re.search(r'@bant (\d*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
duration = match.group(1)
reason = "{} temporarly banned by {}".format(target.author.name, report['author'])
logging.info('Bant matched. Reason: %s', reason)
if 'source' in report:
report['source'].mod.remove()
target.mod.remove()
self.r.subreddit(subreddit).banned.add(
target.author.name, duration=duration, note=reason,
ban_message="""Il ban temporaneo è il nostro modo per comunicarti che hai violato il regolamento o inserito un commento davvero inadeguato al clima del sub. Confidiamo che tu possa capire come mai guardando i tuoi ultimi messaggi. A presto.
You have been banned TEMPORARILY from /r/italy.""")
logging.info('User banned.')
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | | {} \n".format(timestamp, report['author'], "bant", 'ban temp', target.author.name, report))
# Check for @sayst command.
match = re.search(r'@sayst *(.*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
msg = match.group(1)
logging.info('Say matched.')
if 'source' in report:
report['source'].mod.approve()
target.mod.approve()
if isinstance(target, Submission):
logging.info('Say stickied message to submission.')
msg = '{msg}'.format(msg=msg)
target.reply(msg).mod.distinguish(sticky=True)
permalink = target.permalink
elif isinstance(target, Comment):
logging.info('Say stickied message to comment.')
msg = '{msg}'.format(
msg=msg)
target.reply(msg).mod.distinguish(sticky=True)
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "stickied", "sayst", target.author.name, permalink, report, ))
# Check for @saynost command.
match = re.search(r'@saynost *(.*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
msg = match.group(1)
logging.info('Say nost matched.')
if 'source' in report:
report['source'].mod.approve()
target.mod.approve()
if isinstance(target, Submission):
logging.info('Say stickied message to submission.')
msg = '{msg}'.format(msg=msg)
target.reply(msg).mod.distinguish(sticky=False)
permalink = target.permalink
elif isinstance(target, Comment):
logging.info('Say stickied message to comment.')
msg = '{msg}'.format(
msg=msg)
target.reply(msg).mod.distinguish(sticky=False)
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "stickied", "saynost", target.author.name, permalink, report, ))
# Check for @saynost command.
match = re.search(r'@saynod *(.*)', report['reason'],
re.IGNORECASE)
if match:
timestamp = str(datetime.datetime.now().strftime("%Y:%m:%d %H:%M:%S"))
msg = match.group(1)
logging.info('Say nod matched.')
if 'source' in report:
report['source'].mod.approve()
target.mod.approve()
if isinstance(target, Submission):
msg = '{msg}'.format(msg=msg)
permalink = target.permalink
elif isinstance(target, Comment):
msg = '{msg}'.format(
msg=msg)
permalink = target.permalink
self.log(subreddit, "{} | /u/{} | {} | {} | /u/{} | [link]({}) | {} \n".format(timestamp, report['author'], "stickied", "saynod", target.author.name, permalink, report, ))
def log(self, subreddit, msg):
headerbar = "Date | Moderator | Action | Rule | User | Object| Report |\n|---|---|----|----|----|----|----|"
logs_page = self.r.subreddit(subreddit).wiki['rib_logs']
try:
logs_content = logs_page.content_md
logs_content = '\n'.join(logs_content.split('\n')[2:])
except TypeError:
logs_content = ""
logs_content = '\n'.join(logs_content.split('\n')[2:])
logs_page.edit("{}\n{}{}".format(headerbar, msg, logs_content))
def check_mail(self):
logging.info('Checking mail')
for mail in self.r.inbox.unread():
mail.mark_read()
logging.info('New mail: "%s".', mail.body)
match = re.search(r'@refresh (.*)', mail.body, re.IGNORECASE)
if not match:
continue
subreddit = match.group(1)
if subreddit in self.subreddits:
sub = self.subreddits[subreddit]
if mail.author in sub['mods']:
self.refresh_sub(subreddit)
mail.reply(
"Refreshed mods and reasons for {}!".format(subreddit))
else:
mail.reply(
("Unauthorized: not an r/{} mod").format(subreddit))
else:
mail.reply("Unrecognized sub: {}.".format(subreddit))
def run(self):
while True:
logging.info('Running cycle')
for subreddit in SUBREDDITS:
try:
self.check_comments(subreddit)
self.check_reports(subreddit)
self.check_mail()
except Exception as exception:
logging.exception(exception)
logging.info('Sleeping')
time.sleep(32) # PRAW caches responses for 30s.
if __name__ == '__main__':
with open('config.yaml') as config_file:
CONFIG = yaml.load(config_file)
CLIENT_ID = CONFIG['Client ID']
CLIENT_SECRET = CONFIG['Client Secret']
USERNAME = CONFIG['Username']
PASSWORD = CONFIG['Password']
SUBREDDITS = CONFIG['Subreddits']
USER_AGENT = CONFIG['User Agent']
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format='%(asctime)s %(levelname)s: %(message)s')
logging.info('Logging in')
MODBOT = Bot(Reddit(client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
user_agent=USER_AGENT, username=USERNAME,
password=PASSWORD))
MODBOT.run()