Build an Uptime Bot
00:00 In this lesson, you’re going to build an uptime bot. Eventually it’s going to look something like this, but don’t get too stuck with this code. You’re going to build it step by step starting now.
Head over to your favorite text editor. I’m here in VS Code, and I’m still on the terminal in an empty folder. I’m going to create a new file. I’m going to say
touch uptime_bot.py. Now you can see I have this empty file,
uptime_bot. Open it up, and I will also get rid of all this extra stuff. Okay. You’re inside of a file called
And that sounds about right. These are three tasks that you want the script to accomplish. Let’s get started right away. For querying a URL, you’re going to use the
urllib package, and specifically you need
This allows you to make requests, and it’s also part of the standard library, so you won’t need to install anything else. Okay, so you can query a URL by saying
urllib.request.urlopen() and then pass in a URL. Now, you could hard-code a URL in here, but I’m going to put it into a variable that, of course, you’re going to need to define as well.
01:55 So, let’s say the URL that you want to query is the Python docs, docs.python.org. And then we go to 3, of course. All right, so that’s the URL that you want to query. Now, feel free to put in your own URL here instead. Now with this, I can send a HTTP query to the URL, and then if there is no exception, then everything is fine, right?
Try doing this request, and if there’s an exception, then we want to catch this exception. Now, maybe we want to say, if this try works out, I’m going to print out that everything’s fine. Let’s say it’s a
Okay, like this, we’re catching an exception and then we have a loop that queries the URL. Okay, we’re querying the URL so far, but now you want to also add a loop. For this, you’re going to just use a
while True: loop and then move all of this functionality into the body of the loop.
So now you have a loop that queries the URL, and it tries to make this request to the URL, prints
"success" if it works out, and if it runs into an error, then it’s going to instead print
"error". Now, if you run this as is right now, then this
while True: is going to make the problem where it just keeps calling way too often and way too quickly, so this is where
time.sleep() comes in.
Now, you see my editor already tells me that I’m missing
time because I haven’t imported yet, so you can go up here and say
import time. Now everyone is happy, and Python is going to run into an infinite loop and keep trying to request the URL, print
"success" if it finds it and if there’s no error, and print
"error" if there’s an error. And we’re sleeping between calls, so I can get rid of this too.
Become a Member to join the conversation.