Vageesh KV
2 min readMay 29, 2018

How to build a reddit bot?

As a frequent user of reddit, I’ve come across many bots that makes the experience better like for instance, the Colorizebot which can be summoned to colorize black and white images. Praw is a reddit API wrapper for python which makes reddit app creation, an easy excercise.

Adaenggappa!

This is my first attempt at creating a bot that uses tamil movie dialogues as insults and when invoked the bot replies with a random phrase. Named KundakkaMandakkaBot, the script uses popular phrases of Vadivelu & Goundamani.

  1. Use Praw to login, this requires the credentials retrieved from the id’s preferences https://www.reddit.com/prefs/apps/
  2. Store it in a *.py file which can be then accessed.
import praw
import config
import os
import random

def bot_login():
rlogin = praw.Reddit(username = config.username, password = config.password,
client_id = config.client_id, client_secret=config.client_secret,
user_agent = "Kundakka Mandakka Bot v1.2")
return rlogin

3. The function returns rlogin which can then be used to comment, post, message as the reddit id using praw funtions

4. Function run_bot: picks up the last 25 mentions of the username if the mention/comment has not been replied to we reply with a funny dialogue from a file. Also store the comment id of the mention in the file comments_replied_to.txt

5. Function getrandom_comment: Picks a random dialogue from the file dialogues.txt

def run_bot(rlogin, comments_replied_to):
for comment in rlogin.inbox.mentions(limit=25):
if comment.id not in comments_replied_to:
comment.reply(getrandom_comment()+"\n"+"This is an automated comment from a bot!")
comments_replied_to.append(comment.id)
else:
print("Comment Replied")

with open("comments_replied_to.txt", "a") as f:
f.write(comment.id + "\n")

def getrandom_comment():
with open("dialogues", "r") as f:
insults = f.read()
insults = insults.split("\n")
return random.choice(insults)

def get_saved_comments():
if not os.path.isfile("comments_replied_to.txt"):
comments_replied_to = []
else:
with open("comments_replied_to.txt", "r") as f:
comments_replied_to = f.read()
comments_replied_to = comments_replied_to.split("\n")
comments_replied_to = filter(None, comments_replied_to)

return comments_replied_to

6. Function get_saved_comments: Retrieve comments that have been replied to which is store in the file comments_replied_to.txt

rlogin = bot_login()


comments_replied_to = get_saved_comments()
print(comments_replied_to)

while True:
run_bot(rlogin, comments_replied_to)
sleep(7200)

7. run_bot is being run every 2 hours, checking for mentions and replying if required.

Find the code here on github!

And here is the code in action: