-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActions.py
302 lines (271 loc) · 9.16 KB
/
Actions.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
#!/usr/bin/env python2.7
import logging
import praw.exceptions
import requests
import urlparse
import httplib
def make_post_text(sub, title, message, distinguish=False):
try:
# create a post
post = sub.submit(title=title, text=message)
return post
except Exception, e:
logging.error("Post with title: " + title + "\tmessage: " + message + " not created.")
if __debug__:
logging.exception(e)
return None
def make_post_url(sub, title, url):
try:
# create a post
post = sub.submit(title=title, url=url)
return post
except Exception, e:
logging.error("Post with title: " + title + "\turl: " + url + " not created.")
if __debug__:
logging.exception(e)
return None
def approve_post(self, post):
try:
post.approve()
return True
except Exception, e:
logging.error("Post " + str(post.id) + " was not approved")
if __debug__:
logging.exception(e)
return False
def remove_post(self, post, mark_spam=True, delete=False):
try:
if delete:
post.mod.delete()
else:
post.mod.remove(spam=mark_spam)
return True
except Exception, e:
logging.error("Post " + str(post.id) + " was not removed")
if __debug__:
logging.exception(e)
return False
def ban_user(sub, reason, user):
try:
sub.add_ban(user)
logging.info("User " + str(user) + " was banned for " + str(reason))
return True
except Exception, e:
logging.error("User " + str(user) + " was not successfully banned for " + str(reason))
if __debug__:
logging.exception(e)
return False
def unban_user(sub, user):
try:
sub.remove_ban(user)
logging.info("User " + str(user) + " unbanned successfully.")
return True
except Exception, e:
logging.error("User " + str(user) + " not unbanned successfully.")
if __debug__:
logging.exception(e)
return False
def get_posts(sub, limit=20):
try:
posts = sub.new(limit=limit)
return posts
except Exception, e:
logging.error("Posts retrieved correctly")
if __debug__:
logging.exception(e)
return None
def make_comment(post, text, dist=False):
try:
comment = post.reply(text)
if dist:
comment.mod.distinguish()
return comment
except praw.exceptions.APIException, a:
if a.error_type == 'DELETED_LINK':
logging.info('Comment not made on post {}, post already deleted'.format(post.name))
pass
else:
logging.error("Comment " + text + " was not made successfully!")
if __debug__:
logging.exception(a)
except Exception, e:
logging.error("Comment " + text + " was not made successfully!")
if __debug__:
logging.exception(e)
return None
def get_comments(post):
try:
post.comments.replace_more().list()
except Exception, e:
logging.error("Comments not retrieved successfully")
if __debug__:
logging.exception(e)
return None
def remove_comment(comment, mark_spam=False):
try:
comment.remove(spam=mark_spam)
return True
except Exception, e:
logging.error("Comment not removed successfully")
if __debug__:
logging.exception(e)
return False
def write_wiki_page(wiki, content, reason=''):
"""Writes to a wiki page, returns true if written successfully"""
try:
wiki.edit(content=content, reason=reason)
return True
except Exception, e:
logging.error("Error writing wiki page.")
if __debug__:
logging.exception(e)
return False
def get_wiki_content(wiki):
"""Reads from a wiki page, returns content if read successfully"""
try:
return wiki.content_md
except Exception, e:
logging.error("Could not retrieve wiki page content")
if __debug__:
logging.exception(e)
return None
def get_or_create_wiki(reddit, sub, page):
"""Returns the specified wiki page, it will be created if not already extant"""
wiki = None
try:
wiki = reddit.get_wiki_page(sub, page)
except requests.exceptions.HTTPError, e:
logging.warning("Wiki page " + page + " not created for subreddit, creating...")
try:
reddit.edit_wiki_page(sub, page, content="", reason="initial commit")
wiki = reddit.get_wiki_page(sub, page)
except Exception, e:
logging.error("Could not create wiki page.")
if __debug__:
logging.exception(e)
except Exception, e:
logging.error("Could not get wiki page")
if __debug__:
logging.exception(e)
return wiki
def get_unread(reddit, limit=10):
"""Returns a list of messages
"""
comments = None
try:
comments = reddit.inbox.unread(limit = limit)
except requests.exceptions.HTTPError, e:
logging.error("Unread mail for user could not be retrieved")
if __debug__:
logging.exception(e)
except Exception, e:
logging.error("Unread mail for user could not be retrieved")
if __debug__:
logging.exception(e)
return comments
def get_mods(reddit, sub):
try:
mods = []
for mod in sub.moderator():
mods.append(mod)
return mods
except Exception, e:
logging.error("Could not retrieve moderators for sub: " + str(sub))
if __debug__:
logging.exception(e)
return None
def send_message(reddit, user, subject, message):
"""sends a message to user 'user' with subject and message
:type reddit AuthenticatedReddit
:return True if sent correctly, false otherwise
"""
try:
if len(message) >= 10000:
temp = " \nMessage too long, truncated to 10000 characters..."
message = message[:10000 - len(temp)] + temp
user = reddit.redditor(user).message(subject, message)
except requests.exceptions.HTTPError, e:
logging.error("Message " + subject + " could not be sent to user " + user)
if __debug__:
logging.exception(e)
return False
except Exception, e:
logging.error("Message " + subject + " could not be sent to user " + user)
if __debug__:
logging.exception(e)
return False
return True
def xpost(post, other_sub, comment):
try:
return make_post_url(other_sub, title=post.title + "//" + comment, url=u"http://redd.it/{}".format(post.id))
except Exception, e:
logging.error("Post " + str(post.id) + " could not be cross posted")
if __debug__:
logging.exception(e)
return False
def get_username(post):
try:
return post.author.name
except:
return None
def is_deleted(post):
try:
return post.author is None or (post.author is not None and post.author.name == "[deleted]")
except:
return False
def is_deleted(post):
try:
return post.author is None or (post.author is not None and post.author.name == "[deleted]")
except:
return False
def get_by_ids(reddit, id_list):
""" Gets a list of posts by submission id
:param reddit: the praw object
:param id_list: the list of post id's (should be the submission's name property)
:return: a list of loaded posts
"""
if not id_list:
return None
try:
submissions = []
for reddit_id in id_list:
submissions.append(reddit.submission(id=reddit_id))
return submissions
except TypeError, e:
logging.error("At least one non-string in id_list passed to get_by_ids")
except Exception, e:
logging.error("Posts with id's: " + ", ".join(id_list)[:30] + " were not loaded")
if __debug__:
logging.exception(e)
return None
def resolve_url(url):
"""Resolves a url for caching and storing purposes
:return: the resolved url, or None if an exception occurs
"""
#determine scheme and netloc
parsed = urlparse.urlparse(url)
if parsed.scheme == httplib.HTTP or parsed.scheme == "http":
h = httplib.HTTPConnection(parsed.netloc)
elif parsed.scheme == httplib.HTTPS or parsed.scheme == "https":
h = httplib.HTTPSConnection(parsed.netloc)
else:
logging.warning("Could not determine net scheme for url " + url)
return None
#add query
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
#ask server
try:
h.request('HEAD', resource, headers={"USER-AGENT" : "Mozilla/5.0 (X11; Linux x86_64; rv:13.0) Gecko/13.0 Firefox/13.0"})
response = h.getresponse()
except httplib.error, e:
logging.error("Error on resolving url " + url + "\n" + str(e))
if __debug__:
logging.exception(e)
return None
#check for redirection
if response.status/100 == 3 and response.getheader('Location'):
return resolve_url(response.getheader('Location')) # changed to process chains of short urls
else:
return url