-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcyborg.py
More file actions
398 lines (282 loc) · 11.7 KB
/
cyborg.py
File metadata and controls
398 lines (282 loc) · 11.7 KB
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
import praw
import yaml
import os
import re
from collections import deque
import time
import irclib
import prawcore
import threading
#Globals
r=praw.Reddit('cyborg')
SUBREDDIT = r.subreddit('cyborg_noeatnosleep')
ME = r.user.me()
DISCLAIMER = "\n\n*^(I am a cyborg, and this action was performed automatically. Please message the moderators with any concerns.)"
def xor(bool1, bool2):
b1 = bool(bool1)
b2 = bool(bool2)
if (b1 or b2) and not (b1 and b2):
return True
else:
return False
class Rule():
#Rule object which stores rule data
def __init__(self, data={}):
self.data=data
_valid_fields = [
'type',
'subreddit',
'author_name',
'body',
'body_regex',
'domain',
'action',
'reason',
'comment',
'ban_message',
'ban_duration',
'invert',
'message_subject',
'message',
'title',
'rule_name'
]
for entry in data:
if entry not in _valid_fields:
raise KeyError("unknown field `%s` in rule" % entry)
#set values with defaults
self.subreddit = data.get('subreddit', [])
self.type = data.get('type', "both")
self.author_name = data.get('author_name', [])
self.body = data.get('body', [])
self.body_regex = data.get('body_regex', [])
self.domain = data.get('domain', [])
self.title = data.get('title',[])
self.action = data.get('action', [])
self.reason = data.get('reason', "")
self.comment = data.get('comment', "")
self.ban_message = data.get('ban_message', "")
self.ban_duration = data.get('ban_duration', None)
self.message_subject= data.get('message_subject',"Automatic Notification")
self.message = data.get('message',"")
self.name = data.get('rule_name','None')
self.invert = data.get('invert', [])
def __str__(self):
return yaml.dump(self.data)
def match_thing(self, thing):
#returns False if it's not a match,
#True if successful match
#begin checking
if self.type=="both":
pass
elif isinstance(thing, praw.models.Comment):
if "submission" in self.type:
print('type mismatch - thing is not submission')
return False
elif isinstance(thing, praw.models.Submission):
if self.type == "comment":
print('type mismatch - thing is not comment')
return False
elif self.type == "link submission" and thing.permalink in thing.url:
print('type mismatch - thing is not link submission')
return False
elif self.type == "text submission" and thing.permalink not in thing.url:
print('type mismatch - thing is not text submission')
return False
if self.subreddit:
if xor(not any(x.lower()==thing.subreddit.display_name.lower() for x in self.subreddit), "subreddit" in self.invert):
print('subreddit mismatch')
return False
if self.author_name:
if getattr(thing, 'author', None):
if xor(not any(x.lower()==thing.author.name.lower() for x in self.author_name), "author_name" in self.invert):
print('author mismatch')
return False
if self.title:
title = getattr(thing, 'title', None)
if not title:
print('thing does not have title')
return False
if xor(not any(x in title for x in self.title), "title" in self.invert):
print('title mismatch')
return False
if self.domain:
if not getattr(thing, 'domain', None):
print('domain failed')
return False
if xor(not any(thing.domain.endswith(x) for x in self.domain), "domain" in self.invert):
print('domain mismatch')
return False
if self.body:
#get body text from comment or selftext
body = getattr(thing, 'body', getattr(thing, 'selftext', None))
if not body:
print('thing does not have body')
return False
if xor(not any(x in body for x in self.body), "body" in self.invert):
print('body mismatch')
return False
if self.body_regex:
body = getattr(thing, 'body', getattr(thing, 'selftext', None))
if not body:
print('thing does not have body for body_regex')
return False
if xor(not any(re.search(x.lower(), body.lower()) for x in self.body_regex), "body_regex" in self.invert):
print('body regex mismatch')
return False
#at this point all criteria are satisfied. Act.
print("rule triggered at "+thing.permalink)
return True
def act_on(self, thing):
#see if we need to fetch the parent thing
#if we do but it's not a comment then return
if any("parent" in x for x in self.action):
if isinstance(thing, praw.models.Comment):
parent=next(r.info([thing.parent_id]))
else:
return False
#do all actions
if "remove" in self.action:
thing.mod.remove()
if "remove_parent" in self.action:
parent.mod.remove()
if "spam" in self.action:
thing.mod.remove(spam=True)
if "spam_parent" in self.action:
parent.mod.remove(spam=True)
if "ban" in self.action:
thing.subreddit.banned.add(thing.author, ban_reason=self.reason, ban_message=self.ban_message, duration = self.ban_duration)
if "ban_parent" in self.action:
thing.subreddit.banned.add(parent.author, ban_reason=self.reason, ban_message=self.ban_message, duration = self.ban_duration)
if "report" in self.action:
thing.report(reason=self.reason)
if "report_parent" in self.action:
parent.report(reason=self.reason)
if "approve" in self.action:
thing.mod.approve()
if "approve_parent" in self.action:
parent.mod.approve()
if self.comment:
thing.reply(self.comment).mod.distinguish()
if self.message:
thing.author.message(self.message_subject, self.message)
return True
s
class Bot():
def __init__(self):
self.start_time = time.time()
self.rules=[]
self.already_done = deque([],maxlen=400)
#initiate IRC connection
self.i=irclib.IRC()
self.load_irc_config()
def load_irc_config(self):
#fetch and interpret wiki page
self.irc_config=next(yaml.safe_load_all(r.subreddit('cyborg_noeatnosleep').wiki['irc'].content_md))
for entry in self.irc_config:
self.i.add_server(entry,
self.irc_config[entry]['port'],
self.irc_config[entry]['nick'],
self.irc_config[entry]['username'],
self.irc_config[entry]['password'],
self.irc_config[entry]['realname'],
channels=self.irc_config[entry].get('channels',[]),
raw=self.irc_config[entry].get('raw',False)
)
def pingpong(self):
for message in self.i.listen():
pass
def run(self):
self.load_rules()
#spin off pingpong thread
pingpong = threading.Thread(target=self.pingpong, name='pingpong')
pingpong.start()
while True:
try:
self.mainloop()
except KeyboardInterrupt:
break
except prawcore.exceptions.RequestException:
continue
def load_rules(self):
#get wiki page
print('loading rules...')
wiki_page = SUBREDDIT.wiki["users/"+ME.name].content_md
try:
i=1
for entry in yaml.safe_load_all(wiki_page):
self.rules.append(Rule(data=entry))
i+=1
except KeyError as e:
r.send_message(ME, 'Error in Rule #'+str(i),e).mark_as_unread()
except:
r.send_message(ME, "Unable to parse rules", "Unable to parse rules")
print('...done')
def reload_rules(self):
print('Rules reload ordered')
self.rules=[]
self.load_rules()
def full_stream(self):
#unending generator which returns content from /new, /comments, and /edited of /r/mod
subreddit=r.subreddit('mod')
while True:
single_round_stream = []
#fetch /new
for submission in subreddit.new(limit=100):
#avoid old work (important for bot startup)
if submission.created_utc < self.start_time:
continue
#avoid duplicate work
if submission.fullname in self.already_done:
continue
self.already_done.append(submission.fullname)
single_round_stream.append(submission)
#fetch /comments
for comment in subreddit.comments(limit=100):
#avoid old work
if comment.created_utc < self.start_time:
continue
#avoid duplicate work
if comment.fullname in self.already_done:
continue
self.already_done.append(comment.fullname)
single_round_stream.append(comment)
#fetch /edited
for thing in subreddit.mod.edited(limit=100):
#ignore removed things
if thing.banned_by:
continue
if thing.edited < self.start_time:
continue
#uses duples so that new edits are detected but old edits are passed by
#.edited is the edit timestamp (False on unedited things)
if (thing.fullname, thing.edited) in self.already_done:
continue
self.already_done.append((thing.fullname, thing.edited))
single_round_stream.append(thing)
for thing in single_round_stream:
yield thing
def log(self, rule, thing):
name=rule.name
permalink=thing.permalink
redditor=getattr(thing.author,"name","[deleted]")
output="{}: Triggered by /u/{} at http://reddit.com{}".format(name,redditor,permalink)
channel=self.i.servers[0].channels[0]
channel.talk(output)
def mainloop(self):
for thing in self.full_stream():
name=getattr(thing.author,'name','[deleted]')
print('checking thing '+thing.fullname+' by /u/'+name+' in /r/'+thing.subreddit.display_name)
#hard code rule reload
if isinstance(thing, praw.models.Comment):
if thing.author==ME and thing.body=="!reload":
thing.delete()
self.reload_rules()
continue
for rule in self.rules:
if rule.match_thing(thing):
rule.act_on(thing)
self.log(rule, thing)
if __name__=="__main__":
b=Bot()
b.run()