Python and the Reddit API

Here it finally is, the tutorial most of you have been waiting for: Python and the Reddit API!

In this tutorial we are going to create a simple program that tells us our Reddit karma using the PRAW module.

First you need a reddit account ofcourse, we want to get an api key. to do this go to:

https://www.reddit.com/prefs/apps

Scroll to the bottom and click on create an app. Give it a name and tick the Script option. Write a description for your app. The first URL doesn´t matter, I chose http://www.maxandpi.wordpress.com but it does not matter. you can leave the next URL blank.

Now you will see two different strings of random letters and numbers, save those somewhere (notepad will do) make sure to note which one is the Secret.

Now switch over to your terminal and type:

sudo pip install praw

This will install the PRAW module so we can use it in our Python code.

Now on to the actual code, make a new python file and paste the next part in, make sure to read all of the comments (the parts starting with a #) to learn about what the code does.

import praw #Makes sure we can use the module
#The next part will tell reddit that we are who we are, so that we can
#grab info from our accounts.
reddit = praw.Reddit(client_id='my client id', #Change this to the first string
                     client_secret='my client secret', #Change this to the secret string
                     user_agent='my user agent') #This can be anything, just give a title!

me = reddit.redditor('MYUSERNAME') #Defines the variable me as our account
linkkarma = me.link_karma #Defines the variable linkkarma as our link karma
commentkarma = me.comment_karma #Defines the variable commentkarma as our comment karma
totalkarma = linkkarma + commentkarma #This will make a variable called totalkarma that will add both of the karma variables together.

#now we can use those three variables in any program! for example lets make a program that tells us our karma every second!
import time #now we can use the sleep command to wait a second
while True: #Starts a loop that will never stop.
  time.sleep(1)
  print totalkarma #Tells us our total karma.

Great! Now you can use a bunch of different API´s, I recommend checking out the OpenWeatherMap API for checking the weather status.

 

Thanks for reading this post and I hope you learnt something from the comments in the code. Send me emails to maxvasten@gmail.com with what you created! If you wan´t to support me, just click on this link and I will get $0.0014 for every click!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s