Home > python > Send a post to reddit from Python

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.

The official Reddit API is here. There is a wrapper for it called reddit_api, which greatly simplifies its usage.

Install reddit_api:

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 ;)
    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)
  1. March 7, 2012 at 20:05

    With the latest version of PRAW, there is no longer a `get_submission_by_id` function, however the process is simplified via:


  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: