Build Marvin the Depressed Reddit Bot in Python

Build a Reddit Bot Series

Part 1: Read posts from reddit

Part 2: Reply to posts

Part 3: Automate our Bot

Part 4: Marvin the Depressed Bot

There are many bots on Reddit (and Twitter etc), most of whom are very helpful.

There is one bot that reminds of you something; another transcribes xkcd comic strips.

Our bot is not going to be like that. Our bot will be a depressed loner who will reply to your plea for help with more insults.

Introducing Marvin the Depressed Robot:

The theory behind bots: Most bots on reddit follow the same formula: They scan for a keyword in the comments, and reply based on a formula. We will follow this formula. To be insulted by  get inspirational quotes from our bot, just add the words: Marvin help to your post.

Our script will continually monitor all new posts, and when it sees Marvin help, it will jump into action.

Prerequisites: Make sure you have done Parts 1 & 2 of the tutorial. Part 3 isn’t necessary, as this blog will try a new approach.

As before:  I created a special sub-Reddit for this series. Please please please stick to that. I don’t want you spamming other Reddits. The moderators may ban you, and Reddit may ban my user agent (please read part one if you don’t know what that means). So please stick to practising here:

http://www.reddit.com/r/pythonforengineers

This is my own sub-Reddit, and you have full permission to play in that region.

Before we start, all the source code is here.

Build Our Bot

The first thing to do is to get some sarcastic Marvin quotes. Imdb is a good source.

Let’s create our Reddit bot and point it to our sub-reddit:

Now we come to the  crux of the code.

Praw added this feature fairly recently, the ability to iterate over all new  posts in a subreddit. In their official example, they show you how to track new posts. This method is called monitoring the submission stream, and it does so indefinitely.

We are going to do something slightly different and monitor all new replies to posts.

This line will continually monitor all new comments on every single post in the sub-reddit. It will run forever until you press Ctrl+C to kill the program.

We search for our keyword Marvin help in every single comment’s body. If we find it:

We choose a random quote from Marvin, and use the comment.reply() to reply to the message.

Let’s test our bot.

We create an empty post with a call to help to Marvin:

As you can see, I’m feeling depressed as Justin Bieber hasn’t released an album for months, and I asked Marvin for help.

Let’s run our bot now.

Go to the subreddit page:

And there you go. We are one step closer to the future. Now we just to write a towel bot, and a bot that replies DON’T PANIC to every single post.