Building a reddit bot

I build this following this tutorial.

Learning | Making my own

Learning

  1. Fetch reddit post
  2. Reply to reddit post
  3. Automate reply

Fetch post from reddit

Creating reddit app

Reddit bot rules

  • You can’t make more than 1 request every 2 seconds (or 30 a minute)
  • You must not lie about your user agent

Go to this page and click on the create your own app button:

and create a reddit app. From there you will get a client_id(red square) and a secret(blue square).

And then you should to the praw.ini in the package folder of the praw and added a new section for your bot, and put the client_id and secret, along with a user_agent field specifiying the version.

Note

the user_agent is there becuase reddit only allows to prevent someone from abusing your bot. Update the version number if somebody is abusing your bot.

featch code

import praw  
  
reddit = praw.Reddit('bot1')  
subreddit = reddit.subreddit("learnpython")  
for submission in subreddit.hot(limit=5):  
    print("Title: ", submission.title)  
    print("Text: ", submission.selftext)  
    print("Score: ", submission.score)  
    print("---------------------------------\n")

Reply

import praw  
import pdb  
import re  
import os  
  
# Create the Reddit instance  
  
reddit = praw.Reddit(  
    client_id="id",  
    client_secret="sercret",  
    password="password",  
    username="username",  
    user_agent="Py_gloomy_repli_bot 0.2"  
)  
  
  
if not os.path.isfile("posts_replied_to.txt"):  
    posts_replied_to = []  
else:  
    with open("posts_replied_to.txt", "r") as f:  
        # Read the file into a list and remove any empty values  
        posts_replied_to = f.read()  
        posts_replied_to = posts_replied_to.split("\n")  
        posts_replied_to = list(filter(None, posts_replied_to))  
  
        # Get the top 5 values from the subreddit pythonforengineers  
        subreddit = reddit.subreddit('pythonforengineers')  
        for submission in subreddit.hot(limit=20):  
            if submission.id not in posts_replied_to:  
                if re.search("i love python", submission.title, re.IGNORECASE):  
                    submission.reply("me bot says: I love Python too! I especially love praw")  
                    print("Bot replying to : ", submission.title)  
                    posts_replied_to.append(submission.id)  
                elif re.search('python', submission.selftext, re.IGNORECASE):  
                    submission.reply("you mentioned python, python very good!")  
                    print("Bot replying to : ", submission.title)  
                    posts_replied_to.append(submission.id)  
                else:  
                    print("Nothing found")  
  
        # Write our updated list back to the file  
        with open("posts_replied_to.txt", "w") as f:  
            for post_id in posts_replied_to:  
                f.write(post_id + "\n")

Automate

To automate this script, we have to use linux chrontab

we first start a new cron job by typing:

crontab -e

and then we select which editor to use, I chose vim.

Then we put this line in the bottom of the cron job script:

* * * * * cd /path/to/project/; python3 bot_script.py

The 5 * represent the time the job gets executed:

* * * * * command to be executed 
– – – – – 
| | | | |
| | | | +—– day of week (0 – 6) (Sunday=0) 
| | | +——- month (1 – 12) 
| | +——— day of month (1 – 31) 
| +———– hour (0 – 23) +————- min (0 – 59)

Then save the script, and enter the command:

sudo service cron start

Note

if you want to stop the cron job: sudo service cron stop

if you want to restart the cron job: sudo service cron restart

Comment reply

import praw  
import pdb  
import re  
import os  
import random  
  
# Create the Reddit instance  
  
reddit = praw.Reddit(  
    client_id="id",  
    client_secret="secret",  
    password="password",  
    username="username",  
    user_agent="useragent"  
)  
  
lucas_quotes = \  
[  
" I've calculated your chance of survival, but I don't think you'll like it. ",  
" Do you want me to sit in a corner and rust or just fall apart where I'm standing?",  
"Here I am, brain the size of a planet, and they tell me to take you up to the bridge. Call that job satisfaction? Cause I don't. ",  
"Here I am, brain the size of a planet, and they ask me to pick up a piece of paper. ",  
" It gives me a headache just trying to think down to your level. ",  
" You think you've got problems. What are you supposed to do if you are a manically depressed robot? No, don't even bother answering. I'm 50,000 times more intelligent than you and even I don't know the answer.",  
"Zaphod Beeblebrox: There's a whole new life stretching out in front of you. Marvin: Oh, not another one.",  
"The first ten million years were the worst. And the second ten million... they were the worst too. The third ten million I didn't enjoy at all. After that, I went into a bit of a decline. ",  
"Sorry, did I say something wrong? Pardon me for breathing which I never do anyway so I don't know why I bother to say it oh God I'm so depressed. ",  
" I have a million ideas, but, they all point to certain death. ",  
]  
  
subreddit = reddit.subreddit('pythonforengineers')  
  
with open("comment_replied.txt", "r") as f:  
        # Read the file into a list and remove any empty values  
        comment_replied = f.read()  
        comment_replied = comment_replied.split("\n")  
        comment_replied = list(filter(None, comment_replied))  
  
for comment in subreddit.comments(limit=100):  
    if comment.id not in comment_replied:  
        if re.search("Lucas Help", comment.body, re.IGNORECASE):  
            lucas_reply = "Lucas the robot says: " + random.choice(lucas_quotes)  
            comment.reply(lucas_reply)  
            comment_replied.append(comment.id)  
        else:  
            print("Nothing found")  
  
# Write our updated list back to the file  
with open("comment_replied.txt", "w") as f:  
    for post_id in  comment_replied:  
        f.write(post_id + "\n")

Making my own

This is my attempt to make a helpful info bot for r/udub

import praw  
import pdb  
import re  
import os  
import random  
  
# Create the Reddit instance  
  
reddit = praw.Reddit(  
    client_id="client_id",  
    client_secret="secret",  
    password="password",  
    username="username",  
    user_agent="Py_gloomy_repli_bot 0.2"  
)  
  
helplink = '''  
General student service:\n  
- https://www.washington.edu/students/servicesforstudents/  
  
Courses/Professor info:\n  
- https://uwgrades.com/  
  
- https://www.washington.edu/cec/toc.html  
  
- https://www.google.com/search?q=rate+my+professor+uw+%5Binsert+professor+name%5D&sxsrf=AJOqlzVwUt9A0OY5_KgZb7bdeYc_lw_RKg%3A1675667778386&ei=QqngY5GbF_aE0PEP8t2piAo&ved=0ahUKEwiRxMT1rID9AhV2AjQIHfJuCqEQ4dUDCBA&uact=5&oq=rate+my+professor+uw+%5Binsert+professor+name%5D&gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCCEQoAEyBQghEKABMgUIIRCrAjoICAAQogQQsAM6BAgjECc6BQgAEIAESgQIQRgBSgQIRhgAUNgGWJYaYLgkaAFwAHgAgAFQiAHVCpIBAjIymAEAoAEByAEFwAEB&sclient=gws-wiz-serp  
  
UW student housing info:\n  
- https://www.housingforhuskies.com/  
  
UW on-campus food info:\n  
- https://www.campusreel.org/colleges/university-of-washington-seattle-campus/dining_food/  
  
UW on-campus job info:\n  
- https://www.washington.edu/workstudy/find-a-job/  
'''  
  
if not os.path.isfile("posts_replied_to.txt"):  
    posts_replied_to = []  
else:  
    with open("posts_replied_to.txt", "r") as f:  
        # Read the file into a list and remove any empty values  
        posts_replied_to = f.read()  
        posts_replied_to = posts_replied_to.split("\n")  
        posts_replied_to = list(filter(None, posts_replied_to))  
  
        # Get the top 5 values from the subreddit pythonforengineers  
        subreddit = reddit.subreddit('udub')  
        for submission in subreddit.new(limit=50):  
            if submission.id not in posts_replied_to:  
                if re.search("\?", submission.title, re.IGNORECASE):  
                    submission.reply("Hi! I am a bot! Your post is asking a question, so here are some usefuly links if you haven't found them yet!\n" + helplink)  
                    print("Bot replying to : ", submission.title)  
                    posts_replied_to.append(submission.id)  
                else:  
                    print("Nothing found")  
  
        # Write our updated list back to the file  
        with open("posts_replied_to.txt", "w") as f:  
            for post_id in posts_replied_to:  
                f.write(post_id + "\n")