How to make a Reddit bot using Python

A quick & simple reddit bot that scrapes comments!

Jun 11, 2022  • 5 mins read  •  views
Feature Image

What we're building 👷‍♂️

A great way to learn about any new technology is to start by developing a teeny-tiny POC (proof of concept) of what you're trying to build in the future.

For our Reddit bot, we'll create a simple subreddit comment scraper that notifies users whenever they mistype the word Gandhi (trust me this happens a lot, and such a bot already exists!).

What you'll need 📝

  • Python

  • PRAW (the main ingredient)

  • A Reddit account for your bot

Account Setup 💡

1) Go to reddit.com and create a brand new account for your bot

2) Once logged in, go to reddit.com/prefs/apps and create a new application.

Reddit Bot step 1

Select 'script', give it a brief description and enter any url you want in the 'redirect url' field (it doesn't really matter). Finally hit 'Create app' !

Reddit bot step 2

3) Save your client id and client secret shown on the screen (we'll need this later)

The Code 💻

Install PRAW by running the command

pip install praw

Or if your python version is 3.x, try running:

pip3 install praw

Save your bot details as environment variables for added security and access them in your python program using 'os.environ'.

🔺Note: You might need to restart your IDE for your program to pick up changes in your env variables.

import praw
import os
import sys

config = dict(os.environ)

#Make sure config keys are same as the environment variables!

reddit = praw.Reddit(
    client_id=config['bot_client_id'],
    client_secret=config['bot_client_secret'],
    user_agent=config['bot_name'],
    username=config['bot_name'],
    password=config['bot_password'])

Let's set up the subreddits to monitor as well as the function to scrape the comments!

#Go ahead and replace "your_fav_subreddit" with a subreddit name of your choice!
subreddit = reddit.subreddit("your_fav_subreddit")

for comment in subreddit.stream.comments(skip_existing=True):
    process_comment(comment)

Here's the main function that checks whether the comment contains the typo 'Ghandi'.

If it does, we reply to the comment author with a quote, and politely let them know the correct spelling. (No matter how polite you are, someone is bound to get their day ruined over a bot 😅)

response = "Be the change that you wish to see in the world. Just so you know, the correct spelling is Gandhi."

def process_comment(comment):
    try:
        commentBody = comment.body.lower()
        if('ghandi' in commentBody):
            comment.reply(response)
            print(f"Replied to {comment.author} in r/{comment.subreddit}")
    except Exception as e:
        sys.exit(f'Could not process comment! \nError Message:{e}')

Result ✨

Run your program, and if you followed all the steps correctly, you should see something like this whenever a comment contains the typo in it!

Replied to GalacticUnicorn69 in r/dankmemes

You should now be able to see your comment by heading over to Reddit and checking the comments tab under your profile!

Go ahead and have fun 🚀

This is merely the tip of the iceberg. If you're comfortable coding in Python, try reading the docs for praw and try out the various built-in APIs available. As long as you follow basic rediquette rules, use your creativity to the fullest and make awesome reddit bots for fellow redditors to enjoy!

Here's one I created over the weekend -> HarryMaguireBot

🎉 Share this article

kevzpeter.com/blog/how-to-make-a-reddit-bot-using-python