
In this article I’ll go through what the bot does and how it was made. This is not a challenging project and can be done with little programming experience.
Requirements:
- Basic knowledge of Python
- A Reddit account
- PRAW: Python Reddit API Wrapper
You’ll first need to log into your Reddit account and go to the Reddit apps page. Create an app, give it a name, and choose “script” from the options. You have to choose a redirect uri, but since this is just a script, you can just type: “http://localhost:8080”
After creating your app, you will be given two strings:
- client_id (located under the name of your app)
- secret
These are important, so write them down but keep them secret. This is what will allow you to connect to your bot.
PRAW can be installed with pip. To install PRAW, type the following into the command line:
pip install praw
You can also refer to the PRAW website for more thorough installation instructions
After you’re done installing PRAW, we can move on to creating the config file. You can use any text editor, I’m using Atom. Create a folder to house all your work. In that folder, create a file named “config.py” and copy the following into it:
username = ""
password = ""
client_id = ""
client_secret = ""
Where username and password is your Reddit username and password. Remember the two strings you saved earlier? Copy and paste them into their respective variables. Remember, don’t make this file public, as anyone with your client_id and secret will have access to your bot.
Now that the setup is done, we can move onto the main script. In the same folder create a file named “reddit_bot.py”. We’ll need to import a few modules.
import praw # Reddit API
import config # config.py file which includes login information
import time # allows script to "wait"
import os # reading files from our computer
import file_handle
import sys
We first define a function to log in with the information provided in config.py, which returns an instance of Reddit. This gives us convenient access to the Reddit API.
def bot_login():
r = praw.Reddit(username = config.username,
password = config.password,
client_id = config.client_id,
client_secret = config.client_secret,
user_agent = "My bot v0.1")
print ("Logged in!")
return r
Let’s define our run_bot function which will essentially do the searching and replying. We can use a simple for loop which iterates through a certain number of comments in a subreddit of our choice. Let’s go through r/all.
def run_bot(r):
for comment in r.subreddit('all').comments(limit=100):
print(comment.body)
run_bot() currently takes in an instance of Reddit as a parameter, searches through the given subreddit’s comments and prints the comment body. We can check whether the a user is asking for a link by checking if “link?” is in the comment body.
def run_bot(r):
for comment in r.subreddit('all').comments(limit=100):
if ("link?" in comment.body or "Link?" in comment.body):
print(comment.body)
And then reply to the comment using comment.reply()
def run_bot(r):
for comment in r.subreddit('all').comments(limit=100):
if ("link?" in comment.body or "Link?" in comment.body):
print(comment.body)
comment.reply("[Here you go!]
(https://www.ssbwiki.com/images/thumb/2/23/HWL_Toon_Link_Artwork.png/
1200px-HWL_Toon_Link_Artwork.png)")
print ("Replied to comment")
Great! Now are bot will reply to every user that asks for a link. Now that we have our main function, we need to initialize our Reddit instance, user, and call the function. Outside of our run_bot() function, we initialize:
r = bot_login() # r is an instance of Reddit
while True:
run_bot(r)
time.sleep(20) # to prevent spamming comments
Now if you were to run this code, you might notice that the bot will reply to comments that it has already replied to before. To prevent this, we need to create a text file that contains the id’s of every comment we’ve replied to. Let’s creat a new file called “file_handle.py” and save it in the same directory as our “reddit_bot.py”. We’ll need to import:
import config
import os
Define a function that creates the file if it doesn’t exist and returns a list of comment id’s:
def get_saved_comments():
# if the file does not exist
if not os.path.isfile("comments_replied_to.txt"):
# create the file
file = open("comments_replied_to.txt", 'w')
print("comments_replied_to.txt", "was created")
file.close()
comments_replied_to = []
else:
with open("comments_replied_to.txt", "r") as f:
comments_replied_to = f.read()
# separates comment id's
comments_replied_to = comments_replied_to.split("\n")
# return array of comments
return comments_replied_to
Going back to our “reddit_bot.py” file, we have already imported “file_handle”, so we just have to retrieve the list of comment id’s. We can do that before we call run_bot(), and then pass that through as a parameter for run_bot().
r = bot_login() # r is an instance of Reddit
comments_replied_to = file_handle.get_saved_comments()
while True:
run_bot(r, comments_replied_to)
time.sleep(20) # to prevent spamming comments
This means we have to add the parameter to our run_bot() function:
def run_bot(r, comments_replied_to):
We’re almost there! Before we reply to a comment, we have to check whether we have replied to that comment before. We simply check if the id of the comment we found is in our “comments_replied_to” list. To be safe, we can also check that the comment we’re replying to isn’t one of ours:
def run_bot(r, comments_replied_to):
for comment in r.subreddit('all').comments(limit=100):
if ("link?" in comment.body or "Link?" in comment.body)\
and comment.id not in comments_replied_to\
and comment.author != r.user.me():
print(comment.body)
comment.reply("[Here you go!]
(https://www.ssbwiki.com/images/thumb/2/23/HWL_Toon_Link_Artwork.png/
1200px-HWL_Toon_Link_Artwork.png)")
print ("Replied to comment")
Since we’ve replied to another comment, we have to append that id to our list of id’s and also save it in our text file, so that when we run this script again we can still retrieve the full list of id’s.
def run_bot(r, comments_replied_to):
for comment in r.subreddit('all').comments(limit=100):
if ("link?" in comment.body or "Link?" in comment.body)\
and comment.id not in comments_replied_to\
and comment.author != r.user.me():
print(comment.body)
comment.reply("[Here you go!]
(https://www.ssbwiki.com/images/thumb/2/23/HWL_Toon_Link_Artwork.png/
1200px-HWL_Toon_Link_Artwork.png)")
print ("Replied to comment")
comments_replied_to.append(comment.id)
with open ("comments_replied_to.txt", "a") as f:
f.write(comment.id + "\n")
That’s it! You’ve created a working Reddit bot that is able to search through Reddit comments and reply to them. Feel free to check out my full code on my Github page where I’ve added some extra functionality to not reply to NSFW posts, print the parent comment (if there is one) and more. Also take a look at other projects featured on my blog, I’m always posting new projects!
Full code from “reddit_bot.py”:
import praw
import config
import time
import os
import file_handle
import sys
def bot_login():
r = praw.Reddit(username = config.username,
password = config.password,
client_id = config.client_id,
client_secret = config.client_secret,
user_agent = "My robot test v0.1")
print ("Logged in!")
return r
def run_bot(r, comments_replied_to):
for comment in r.subreddit('all').comments(limit=100):
if ("link?" in comment.body or "Link?" in comment.body)\
and comment.id not in comments_replied_to\
and comment.author != r.user.me():
print(comment.body)
comment.reply("[Here you go!]
(https://www.ssbwiki.com/images/thumb/2/23/HWL_Toon_Link_Artwork.png/
1200px-HWL_Toon_Link_Artwork.png)")
print ("Replied to comment")
comments_replied_to.append(comment.id)
with open ("comments_replied_to.txt", "a") as f:
f.write(comment.id + "\n")
r = bot_login() # r is an instance of Reddit
comments_replied_to = file_handle.get_saved_comments()
while True:
run_bot(r, comments_replied_to)
time.sleep(20) # to prevent spamming comments