Send a post to reddit from Python
How to send a post to reddit.com from a Python script? Motivation: when you send a post, you have to wait 8 minutes before you could send the next one. Imagine you have 10 posts to submit. It’d be nice to launch a script at night which would send everything till next morning.
Submit a post
Now I only show how to send one post. Batch processing is left as a future project.
sudo pip install reddit
Submit a post:
#!/usr/bin/env python import reddit subreddit = '...' # name of the subreddit where to send the post url = '...' # what you want to send title = '...' # title of your post # change user_agent if you want: r = reddit.Reddit(user_agent="my_cool_application") # your username and password on reddit: r.login(user="...", password="...") # the output is a JSON text that contains the link to your post: print r.submit(subreddit, url, title)
Submit a comment (update, 20111107)
Let’s see how to add a comment to a post. First, we need the URL of a post.
Example: http://www.reddit.com/r/thewalkingdead/comments/lkycy/that_look_on_the_kids_face/. Here, the last part of the URL is just garbage, the following URL is equivalent with it: http://www.reddit.com/r/thewalkingdead/comments/lkycy. The unique ID of the post is the last part: “lkycy”. Thus, this image can be accessed via this URL too: http://www.reddit.com/lkycy.
Now, let’s log in to reddit, fetch the post by its ID and add a comment.
def get_reddit_id(url): result = re.search('/comments/(.*?)/', url) return result.group(1) def add_comment(r, reddit_url): reddit_id = get_reddit_id(reddit_url) post = r.get_submission_by_id(reddit_id) comment = "first" # just to make reddit happy ;) post.add_comment(comment) print '# comment added:', comment def main(): r = reddit.Reddit(user_agent="my_cool_application") r.login(user="...", password="...") reddit_url = ... add_comment(r, reddit_url)