Build A Website Blocker App With Python
Tags: python, programming, beginners, opensource
Published: 2023-10-06 12:33:51

<p data-pm-slice="1 3 []">Distractions are everywhere online, making staying focused on important tasks difficult. Website blocker tools can help by restricting access to time-wasting sites.</p>
This comprehensive guide will build a customizable website blocker in Python that gives you control over when and where to browse.
<h4><strong>Introduction</strong></h4>
The internet provides a massive amount of information and entertainment. But it also enables endless distractions that can derail productivity.

According to RescueTime, the average person spends over 2 hours per day on social media alone. Add in other sites like news, videos, and games - and those hours can climb higher.

This issue has led to the rise of website-blocking apps and extensions. By intentionally limiting access, you reduce the temptation to stray onto procrastination-inducing sites.

Popular existing options include:
<ul>
 	<li><strong>Freedom</strong> - Blocks sites across devices for a monthly fee. Allows scheduled sessions.</li>
 	<li><strong>ColdTurkey</strong> - Blocks sites based on a countdown timer. Paid versions add more options.</li>
 	<li><strong>StayFocusd</strong> - Chrome extension to block sites for set periods of time.</li>
 	<li><strong>BlockSite</strong> - A browser extension for blocking sites on a schedule. Free and paid tiers.</li>
</ul>
While these work, they also have limitations:
<ul>
 	<li>Recurring subscriptions and fees</li>
 	<li>Restricted site customization</li>
 	<li>Limited to specific browsers</li>
 	<li>Can't easily undo blocks during sessions</li>
</ul>
By building our own website blocker in Python, we can create a free, cross-platform tool with more flexibility:
<ul>
 	<li>Block any sites we want</li>
 	<li>Set specific blocking periods</li>
 	<li>Easily unblock sites when needed</li>
 	<li>Works on all major operating systems</li>
</ul>
In the rest of this guide, we will walk through the key steps to create an effective website-blocking program with Python.
<h4><strong>Overview of How the Website Blocker Works</strong></h4>
Before jumping into the code, let's briefly summarize how the website blocker will function:
<ul>
 	<li>User inputs list of sites they want to block</li>
 	<li>The user sets start and end times for blocking periods</li>
 	<li>The program checks the current time against blocking times in a loop</li>
 	<li>If, within a blocking period, the program edits the system host file to block target sites</li>
 	<li>Host file redirects blocked sites to 127.0.0.1 (<a href="http://localhost" target="_blank" rel="noopener noreferrer nofollow">localhost</a>)</li>
 	<li>Users can exit the program to restore normal site access</li>
</ul>
Modifying the host file allows our program to block sites across all browsers and applications. And using Python gives us operating system portability.

To get started, fork the <a href="https://github.com/Scofield-Idehen/Do_not_disturb.git" target="_blank" rel="noopener noreferrer nofollow">file</a> and follow the guide.
<h4><strong>Step 1 - Import Required Modules</strong></h4>
Our website blocker will rely on 3 core modules in the Python standard library:
```python
import time
from datetime import datetime as f
```
 	<li><strong>time</strong> - Provides functions like sleep() to pause the program for the given number of seconds. This allows repeating actions.</li>
 	<li><strong>datetime</strong> - Gives useful classes for working with dates and times. We can easily get the current time, construct time objects, and format times.</li>
</ul>
These powerful built-in modules will handle most of the underlying logic for our program.
<h4><strong>Step 2 - Get User Input for Sites to Block</strong></h4>
First, we must let users specify which websites to block access to during focus sessions.

We can use Python's input() function to prompt the user and store their sites in a list:
```python
host_temp = 'hosts' # to test the program as we need adminstartive privilage to run the host_path file
host_path = "/etc/hosts" #be careful and test with the host_temp file until you are ready to use this file.
redirect = '127.0.0.1' #we can creat a redirect to this site ot create a random page online to redirect the user to read
banned_list = ['www.facebook.com', 'facebook.com', 'x.com', 'www.twitter.com'] #pages i banned to give me access to focus
```
Breaking this down:
<ul>
 	<li>Redirect the URL to  127.0.0.1, which is the local host.</li>
 	<li>Save the list to global banned_sites that other functions can access</li>
</ul>
Now, we can get a custom list of distracting sites to block from the user when the program runs.
<h4><strong>Step 3 - Get Blocking Period Times</strong></h4>
In addition to blocking certain sites, we also want to let the user specify when those sites should be blocked.

A good approach is to have the user provide a start and end time for blocking periods. We'll use the 24-hour format to simplify timing logic later on.
<h4>Start Infinite Loop</h4>
We use a while True loop to run the code continuously:

<code>while True:</code>

This loop will run forever until the program is manually stopped.
<h4>Check Time</h4>
Inside the loop, we check the current time using the datetime library:
```python
if f(f.now().year, f.now().month, f.now().day,8) &lt; f.now() &lt; f(f.now().year, f.now().month, f.now().day,13):

print('Working Hours')
```
This creates a datetime object for the current time and objects for 8 a.m. and 1 p.m. today. We compare the current time to see if it is between 8 a.m. and 13 p.m.

If it falls within this time frame, our programs print working hours and block the website from running.
```python
for web_site in banned_list:
    if web_site in content:
    pass
else:
    file.write(redirect+' '+ web_site+'\n ')
```
Next, we check for web_site  in the banned_list  and confirm line by line if any matches our content, and if it does, we pass; otherwise, we write the banned website in our list.
<h4>Working Hours</h4>
If it is between 8 am and 1 pm, we print a message and open the host file to modify it:
```python
print('Working Hours')
with open(host_path, 'r+') as file:
content = file.read()</code></pre>
The file is opened for reading and writing.
<pre><code class="language-python">with open(host_path, 'r+') as file:
    content = file.read()
#print(content)
```
We loop through the banned sites:
```python
file_contents = file.readlines()
for website in banned_list:
    if website not in file_contents:
        file.write(redirect + " " + website + "\n")
```
For each banned site, we check if it is already blocked in the host file. If not, we write a new line redirecting it to 127.0.0.1 to block it.
<h4>Fun Time</h4>
After 1 p.m., we enter the 'else' part of the code:
```python
else:
    print("Fun time! Allowing sites...")

   with open(host_path, 'r+') as file:
```
We again open the host file for reading and writing.

This time, we remove the blocked sites:
```python
file_contents = file.readlines()

file.seek(0)

for line in file_contents:

if not any(site in line for site in banned_list):

file.write(line)
```
We loop through the file lines and only write ones that don't contain the banned sites. This removes the blocked entries.

<code>file.truncate()</code>

Finally, we truncate the file to remove any leftover blank lines.
<h4>Delay and Repeat</h4>
After updating the host file, we delay for 10 seconds before repeating the loop:

<code>time.sleep(10)</code>

This continually checks the time and modifies the host file to block or allow sites accordingly.

And that covers this code in detail! It shows how Python can interact with the system and schedule tasks based on the time. The host file is modified dynamically to control website access.
<h4>Testing</h4>
<img src="https://paper-attachments.dropboxusercontent.com/s_DFF9108347D2955E612CCDDB49B0428DA42527CC02D1F222EB85F079E14081B9_1696591668711_Screenshot+2023-10-05+at+15.25.05.png" alt="" align="left" />
<h4></h4>
To get our program to run, go to your terminal and navigate to the file directory of your program.
<img class="alignnone  wp-image-2856" src="http://blog.learnhub.africa/wp-content/uploads/2023/10/Screenshot-2023-10-05-at-15.28.31-300x198.png" alt="" width="843" height="556" />
Type in the Python name of the file to run the program; it should begin like the screen.
<h4></h4>
<h4><strong>Final Thoughts</strong></h4>
And that covers the steps to build your own website blocker with Python!

Building projects like this is a great way to level up your Python skills. You get experience with timing events, terminal interaction, file I/O, system commands, and more.

If you like my work and want to help me continue dropping content like this, buy me a <a href="https://www.buymeacoffee.com/scofields1s" target="_blank" rel="noopener noreferrer nofollow">cup of coffee</a>.

If you find this post exciting, find more exciting posts on <a href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h4><strong>Resource</strong></h4>
<ul>
 	<li><a href="https://realpython.com/lessons/python-folium-get-started/" target="_blank" rel="noopener noreferrer nofollow">Getting started with Folium</a></li>
 	<li><a href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
 	<li><a href="https://blog.learnhub.africa/2023/10/04/creating-interactive-maps-with-folium-and-python/" target="_blank" rel="noopener noreferrer nofollow">Creating Interactive Maps with Folium and Python</a></li>
</ul>