Posts Tagged ‘add comment’

Send a post to reddit from Python

October 30, 2011 1 comment

How to send a post to 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: Here, the last part of the URL is just garbage, the following URL is equivalent with it: The unique ID of the post is the last part: “lkycy”. Thus, this image can be accessed via this URL too:

Now, let’s log in to reddit, fetch the post by its ID and add a comment.

def get_reddit_id(url):
    result ='/comments/(.*?)/', url)

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)