Build a Reddit Bot Part 3: Automate your bot

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

Up till now, we had to manually run our Python code every time we want to reply to Reddit posts. However, that is not the definition of a bot. A bot is a program that runs by itself.

So we will automate our bot, so it can run without our intervention.

As usual, you have both the video and text.

(Note: Vimeo changed the rules. If you want to watch the video in HD, you have to go to their website. Click on HD on the video below.)

Automating our bot

I will get a bit controversial here. I love my Windows. It’s the main OS I use at home.

However, practically speaking, if you work with servers, especially at companies that regularly use Python, you will be working with Linux. Not to say one is better than the other, it’s just that Microsoft has its own infrastructure (as does Mac).

So I will automate the bot in Linux. You could do it in Windows using Task Scheduler or something, but I want this series to be practical, so it can help you in the real world. So we will use Linux. Again, no judgement on if Linux is better than Windows or vice versa.

Linux/Python are closely tied together. In the last few years, Python has become the defacto tool for automating Linux.

If you don’t have Linux, don’t worry. I’ll be using a virtual machine. Specifically, Vagrant. Their getting started document is quite good, just follow it till you have a basic vagrant instance running. We’ll go from there.

Creating a Linux VM in Vagrant

I’m going to repeat some of the stuff you may have seen in the Vagrant tutorial, so we are all on the same page.

To start off, create a directory called bot anywhere you want and cd into it.

Run Vagrant init and vagrant up to create our VM.

Once the machine is running, ssh into it:

In case you didn’t know, the /vagrant directory is the directory you created the vagrant file in. You can access it from your normal PC. Let’s change to that:

Either run the commands below, or download the installer file from here. These commands will install pip, praw and Git, and then download the source code to our Reddit Bot that we wrote in Part 2.

A brief detour on the crontab

Cron is the way tasks are usually scheduled in Linux. To get a good overview, see here.

In short, you enter 5 values: Minute (0-59), Hour(0-23), Day of Month(1-31), Month(1-12), Day of Week (0-6)

The first two are most important, as normally you’d want to run a job every day. For example, if you want to run a task everyday at 22:15 in the night, you would enter:

* means run it on every day, week etc.

That was the theory. Coming to practice, type:

I recommend you press 2 and choose nano. Like the help says, it’s the easiest to use. This is what you will get:

cygwin1

The commands are given at the bottom of the screen.

Scroll down, and enter the following command:

cygwin2

Some explanation. We want our bot to run all the time, once a minute, which is why we have put * for everything.

The command may look scary:

The problem is cron jobs are run in their own environment. Which means you can’t assume which directories will be in the path. So I have to cd to the directory, and then run the script from there.

Linux allows you to chain commands together using the terminator ; That’s what we do in the example above.

Press Ctrl+o to save, then Ctrl+x to exit.

And your bot will be running in the background automatically. Give it a try. Post a message on the subreddit, and see your bot reply.

reddit3reddit4Hungry for more? Why not learn how to build a Twitter Analytics app?

20 thoughts on “Build a Reddit Bot Part 3: Automate your bot”

  1. Thank you for your post! It helped me build a moderation bot for my new subreddit [removed by moderator, as nsfw]. Your post seemed easier than trying to figure out the reddit automoderator rules. And I’ve barely used python. Put it on my hosted box.

  2. Crontab recognizes my reply_post.py file, but when it runs the script, it gives me “ImportError: No module named praw” I am not sure why it’s giving me this issue, since the script was running fine in part 2. Praw is definitely installed. Any ideas?

        1. do you have multiple versions of Python? If so, check which one is being called

          The other idea is that there is a typo in that file. Start python from the command line and type “import praw”. What happens?

  3. I appreciate your posts, they help a lot.

    I was wondering if you are going to do a video on creating a bot that is activated when a keyword is entered. For example, there is a RemindMe bot that gets activated when a user comments “RemindMe! 5 min” on a post. The bot will then send a message to the user in 5 min time with the link of the post.

    If you are not planning to do something like that, could you point me to a resource that could teach me? Thank you for you help.

    1. I could do something like it. You would have to monitor each subreddit every minute or so, and if so see a keyword, like “remindme”, read the username and send them a message.

      All the functionality is there, it’s just a matter of connecting it. I might give it a try, but can’t say when. If you susbcribe to my email list, I’ll send you an email once it’s done.

  4. It appears my python in the VM is running python 2.7 and I have 3.6 on my windows machine. When I try to run the script using the cronjob it does not run. Also, will i need to set up another praw.ini file on the VM?

  5. Hi there, great write up.

    I’m not having any luck automating the bot and i’m not quite sure how to debug it.

    I am running it manually and have no issues.

    this is what is in my crontab: * * * * * cd /vagrant/RayHudsonBot/; ./rh_bot.py

    1. Debugging cron scripts is a pain (I know from experience). I would try to write some output to a file, to check if the script is even running. It took me a few tries before even I got it working.

      1. I tried creating the output file and they are just empty. So that means my cron script is working but it is not executing my code. Oddly, when I run my script outside of crontab in vangrant, it works but I get the following errors:

        SNIMissingWarning

        /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

        InsecurePlatformWarning

        /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

        1. can you try it with the latest Python version (3.5 or above)?

          Also, what platform are you using (Cygwin? Debian?). You will have to search for the cron problems on that system, as the behaviour might change

  6. Hi Shantnu ! Thanks for this tutorial, it’s great and very easy to follow. I created my bot using the the Linux subsystem in Windows 10 instead of creating a VM so I don’t really know where I should start on this part of the tuto.
    Thanks for your help so far !

  7. Hi Shantnu, thanks for the great tuto !
    I am creating my bot on the linux subsystem on windows 10 instead of a VM, so I don’t really know where to pick up on the 3 part
    Very noob question indeed, I don’t usually write in python, nor do I use linux so I’m a bit lost
    Thanks again for giving us some of your time !

  8. Hey everyone. I was having some issues with crontab and think I found a universal solution for all Unix-based users (any linux distro or iOS). If you are running Ubuntu 18.04 and are struggling to get your python file to run in cron, then you’re in the exact same boat as me. If you’re running Windows, then the only advice I can offer is to install Git and use the Git Bash terminal, but I’m not positive that will work.

    After much googling, I found this answer on Stack Overflow that steered me in the right direction:

    https://stackoverflow.com/questions/26049459/python-script-not-running-in-cron/38682365#38682365

    My understanding is that cron and Python don’t always work well together for some reason. So this person came up with the idea to write a shell script (file extension is .sh) that executes the Python file and have cron call that instead.

    Instead of the line given in the tutorial written in your crontab file, use the following line instead:

    * * * * * sh /home/[yourUserName]/auto_delete.sh

    I’m not sure if it is necessary to have this script in your home directory or not, but mine is. Also, you can name your file whatever you want, but I just copied the the user’s example and I’m too lazy to change it.

    For your shell script, make sure it is in the same directory that you wrote in your cron file and has the same name (/home/[yourUserName]/auto_delete.sh). Use any text editor (I chose Vim) and have it say the following, but just know that I’m not a shell scripting expert and only know a handful of useful commands:

    #!/bin/sh
    echo $(date) >> bash_cron_log.txt
    /[your]/[directory]/[where]/[python]/[executable]/[is]/[installed] /[your]/[directory]/[where]/[bot]/[file]/[is]/[located]/someBotFile.py >> bash_cron_log.txt

    What this will do create a text file (or append to an existing text file) called bash_cron_log.txt in the same directory as your shell script. Also, this will be where all of your output from your Python file is written. For example, if you have print(“connected”) in your python file after your Reddit instantiation, it will write “connected” out to that .txt file. However, you will need to edit your Python file to access the correct directory for posts_replied_to.txt, unless you’re okay with it being in the same file as your shell script. For example, this is what my text file looked like after I had that print statement in my python script for 3 minutes:

    Wed Oct 3 22:27:01 CDT 2018
    Wed Oct 3 22:28:01 CDT 2018
    Wed Oct 3 22:29:01 CDT 2018
    connected
    Wed Oct 3 22:30:01 CDT 2018
    connected
    Wed Oct 3 22:31:01 CDT 2018
    connected
    Wed Oct 3 22:32:01 CDT 2018
    Wed Oct 3 22:33:01 CDT 2018
    Wed Oct 3 22:34:01 CDT 2018

    Notice that all the times are exactly 1 minute apart. This is because cron’s minimum time between runs is 1 minute (I think this is true). If you want it to run more frequently than 1 minute intervals, then you need to use something else.

    If you don’t know where your Python executable is installed, just type “which python” in your terminal and it will give you the exact path you need to for that first argument you’re looking for.

    Okay, I think I covered everything. Thank you Shantnu for making this tutorial and that subreddit for us to play around in. If I made a mistake anywhere in here, whether it’s a typo or I’m misunderstanding a concept, please let me know and I’ll change it.

Leave a Reply

Your email address will not be published. Required fields are marked *