WhatsApp Flight Alerts A Python Script For Cheap Flights

by StackCamp Team 57 views

Introduction

Hey guys! Are you tired of constantly checking flight prices, hoping to snag a great deal? What if I told you there's a way to automate this process and get notified directly via WhatsApp when prices drop? In this article, I'm going to walk you through creating a Python script that does just that. We'll dive into the tools and libraries you'll need, the step-by-step process of building the script, and how to set it up to run automatically. Imagine receiving a message on your phone the moment a flight to your dream destination becomes affordable – sounds amazing, right? So, let's get started and turn that dream into reality!

Why Automate Flight Price Tracking?

In today's fast-paced world, time is precious. Spending hours manually checking flight prices across various websites can be tedious and time-consuming. Automating this process not only saves you valuable time but also increases your chances of securing the best deals. Flight prices are dynamic and can fluctuate rapidly based on demand, seasonality, and other factors. By automating the tracking, you can instantly receive notifications when prices drop, allowing you to book flights at the most opportune moments. This proactive approach ensures you never miss out on a potential bargain, making your travel dreams more attainable without the constant effort of manual monitoring. Plus, let's be honest, who doesn't love the idea of a little tech magic working in their favor?

Benefits of Using WhatsApp Notifications

Why WhatsApp, you ask? Well, it's simple. WhatsApp is one of the most widely used messaging platforms globally, meaning you likely already have it installed on your phone and use it daily. This familiarity makes it incredibly convenient to receive flight price alerts directly through the app. Notifications are instant, ensuring you're among the first to know about price drops. Unlike email, which can sometimes get lost in the inbox clutter, WhatsApp messages are more immediate and attention-grabbing. This immediacy is crucial when it comes to booking flights, as the best deals often disappear quickly. Additionally, WhatsApp allows for quick and easy interaction – you can check the alert and book your flight with just a few taps on your phone, making the entire process seamless and user-friendly. It's like having a personal travel assistant right in your pocket!

Prerequisites and Setup

Before we dive into the code, let's make sure you have everything you need to get started. This section will cover the necessary software installations and API keys you'll require. Don't worry, it's all pretty straightforward, and we'll take it step by step.

Installing Python and Required Libraries

First things first, you'll need Python installed on your machine. If you don't already have it, head over to the official Python website (python.org) and download the latest version. Make sure to select the option to add Python to your system's PATH during installation – this will make it easier to run Python scripts from the command line. Once Python is installed, you'll need to install a few libraries that our script will use. These libraries will help us with web scraping, sending WhatsApp messages, and scheduling tasks. Open your command prompt or terminal and use pip, Python's package installer, to install the following libraries:

  • requests: This library allows us to make HTTP requests to fetch data from websites.
  • beautifulsoup4: Beautiful Soup is a Python library for pulling data out of HTML and XML files. We'll use it to parse the flight price information from the website.
  • twilio: Twilio is a cloud communications platform that allows us to send SMS and WhatsApp messages.
  • schedule: This library will help us schedule our script to run automatically at specific intervals.

You can install these libraries by running the following commands in your terminal:

pip install requests beautifulsoup4 twilio schedule

Make sure you have a stable internet connection during the installation process. Once the installations are complete, you're one step closer to automating your flight price tracking!

Setting Up a Twilio Account and WhatsApp Integration

To send WhatsApp messages programmatically, we'll use Twilio, a powerful cloud communication platform. Don't worry; setting up a Twilio account is quick and easy. Head over to the Twilio website (twilio.com) and sign up for a free account. You'll need to verify your email address and phone number during the signup process.

Once you're logged in, you'll see your Account SID and Auth Token on the Twilio dashboard. These are crucial credentials that our script will use to authenticate with Twilio, so keep them handy. Next, you'll need to enable the Twilio Sandbox for WhatsApp. This sandbox environment allows you to test your WhatsApp integration without incurring any charges. To activate the sandbox, navigate to the Programmable SMS section in your Twilio console and then click on WhatsApp. Follow the instructions to connect to the sandbox by sending a specific message from your WhatsApp number to Twilio's sandbox number. This step is essential for our script to send messages to your WhatsApp.

With your Twilio account set up and the WhatsApp sandbox configured, you're ready to move on to the next step: writing the Python script. Make sure you have your Account SID, Auth Token, and sandbox phone number ready – we'll need them in the code!

Writing the Python Script

Now comes the exciting part – writing the Python script that will do all the magic. We'll break down the script into manageable chunks, explaining each part along the way. By the end of this section, you'll have a fully functional script that can track flight prices and send you WhatsApp notifications.

Step-by-Step Code Explanation

First, let's start by importing the necessary libraries. These libraries provide the functions and tools we'll need to make HTTP requests, parse HTML, send WhatsApp messages, and schedule tasks. Here's the code snippet:

import requests
from bs4 import BeautifulSoup
from twilio.rest import Client
import schedule
import time

Next, we'll define a function to fetch the flight price from a specific website. This function will take the URL of the flight search results page as input and return the price. We'll use the requests library to fetch the HTML content of the page and Beautiful Soup to parse it. Here’s the code:

def get_flight_price(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        soup = BeautifulSoup(response.content, 'html.parser')
        # The following lines are examples. Modify them to suit your target website's structure.
        price_element = soup.find('div', class_='YOUR_PRICE_CLASS') # Replace YOUR_PRICE_CLASS with your target class
        if price_element:
            price = price_element.text.strip()
            return price
        else:
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error fetching the URL: {e}")
        return None
    except Exception as e:
        print(f"Error parsing the HTML: {e}")
        return None

In this function, we first make an HTTP request to the given URL and check for any errors. Then, we use Beautiful Soup to parse the HTML content. The key part here is finding the element that contains the flight price. This will vary depending on the website you're scraping, so you'll need to inspect the HTML source of the page and identify the appropriate CSS class or tag. The example code shows a placeholder for the class name (YOUR_PRICE_CLASS), which you'll need to replace with the actual class name from the website.

Next, we'll create a function to send a WhatsApp message using Twilio. This function will take the message text, your Twilio account credentials, and your WhatsApp number as input. Here’s the code:

def send_whatsapp_message(message, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number):
    client = Client(account_sid, auth_token)
    try:
        message = client.messages.create(
            body=message,
            from_=from_whatsapp_number,
            to=to_whatsapp_number
        )
        print(f"Message sent! SID: {message.sid}")
    except Exception as e:
        print(f"Error sending message: {e}")

This function initializes a Twilio client with your Account SID and Auth Token. Then, it uses the client.messages.create() method to send a WhatsApp message. You'll need to provide the message body, your Twilio WhatsApp sandbox number (the from_whatsapp_number), and your personal WhatsApp number (the to_whatsapp_number).

Now, let's combine these functions to create the main logic of our script. We'll define a function that fetches the flight price, compares it to a threshold, and sends a WhatsApp message if the price is below the threshold. Here’s the code:

def check_flight_price_and_notify(url, threshold_price, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number):
    price = get_flight_price(url)
    if price:
        try:
            price_numeric = float(price.replace('{{content}}#39;, '').replace(',', '')) # Remove currency symbols and commas
            if price_numeric <= threshold_price:
                message = f"Flight price dropped! Current price: {price}. Book now!"
                send_whatsapp_message(message, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number)
            else:
                print(f"Flight price is still above threshold. Current price: {price}")
        except ValueError:
            print(f"Could not convert price to a number: {price}")
    else:
        print("Could not fetch flight price.")

In this function, we first fetch the flight price using the get_flight_price() function. If we get a valid price, we convert it to a number and compare it to the threshold price. If the price is below the threshold, we construct a message and send it using the send_whatsapp_message() function. We also include some error handling to catch cases where the price cannot be converted to a number.

Finally, we'll set up the scheduling to run this function automatically at regular intervals. We'll use the schedule library for this. Here’s the code:

if __name__ == "__main__":
    # Replace with your actual values
    url = "YOUR_FLIGHT_URL" # Replace with your target URL
    threshold_price = 200  # Set your threshold price
    account_sid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Replace with your Account SID
    auth_token = "your_auth_token"  # Replace with your Auth Token
    from_whatsapp_number = "whatsapp:+14155238886"  # Your Twilio WhatsApp number
    to_whatsapp_number = "whatsapp:+1234567890"  # Your WhatsApp number

    # Schedule the task to run every day at a specific time
    schedule.every().day.at("08:00").do(check_flight_price_and_notify, url, threshold_price, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number)

    while True:
        schedule.run_pending()
        time.sleep(60)  # Check every minute

This code block first sets the URL, threshold price, and Twilio credentials. Make sure to replace the placeholder values with your actual values. Then, it uses the schedule library to schedule the check_flight_price_and_notify() function to run every day at 8:00 AM. The while True loop keeps the script running and checks for pending scheduled tasks every minute.

Full Script and Usage Instructions

Here’s the complete script:

import requests
from bs4 import BeautifulSoup
from twilio.rest import Client
import schedule
import time


def get_flight_price(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        soup = BeautifulSoup(response.content, 'html.parser')
        # The following lines are examples. Modify them to suit your target website's structure.
        price_element = soup.find('div', class_='YOUR_PRICE_CLASS') # Replace YOUR_PRICE_CLASS with your target class
        if price_element:
            price = price_element.text.strip()
            return price
        else:
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error fetching the URL: {e}")
        return None
    except Exception as e:
        print(f"Error parsing the HTML: {e}")
        return None


def send_whatsapp_message(message, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number):
    client = Client(account_sid, auth_token)
    try:
        message = client.messages.create(
            body=message,
            from_=from_whatsapp_number,
            to=to_whatsapp_number
        )
        print(f"Message sent! SID: {message.sid}")
    except Exception as e:
        print(f"Error sending message: {e}")


def check_flight_price_and_notify(url, threshold_price, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number):
    price = get_flight_price(url)
    if price:
        try:
            price_numeric = float(price.replace('{{content}}#39;, '').replace(',', '')) # Remove currency symbols and commas
            if price_numeric <= threshold_price:
                message = f"Flight price dropped! Current price: {price}. Book now!"
                send_whatsapp_message(message, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number)
            else:
                print(f"Flight price is still above threshold. Current price: {price}")
        except ValueError:
            print(f"Could not convert price to a number: {price}")
    else:
        print("Could not fetch flight price.")


if __name__ == "__main__":
    # Replace with your actual values
    url = "YOUR_FLIGHT_URL"  # Replace with your target URL
    threshold_price = 200  # Set your threshold price
    account_sid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Replace with your Account SID
    auth_token = "your_auth_token"  # Replace with your Auth Token
    from_whatsapp_number = "whatsapp:+14155238886"  # Your Twilio WhatsApp number
    to_whatsapp_number = "whatsapp:+1234567890"  # Your WhatsApp number

    # Schedule the task to run every day at a specific time
    schedule.every().day.at("08:00").do(check_flight_price_and_notify, url, threshold_price, account_sid, auth_token, from_whatsapp_number, to_whatsapp_number)

    while True:
        schedule.run_pending()
        time.sleep(60)  # Check every minute

To use the script, follow these steps:

  1. Replace YOUR_FLIGHT_URL with the URL of the flight search results page you want to track. You'll need to inspect the HTML of the page and identify the CSS class that contains the flight price.
  2. Set the threshold_price to the maximum price you're willing to pay for the flight.
  3. Replace ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your Twilio Account SID and your_auth_token with your Twilio Auth Token.
  4. Replace whatsapp:+14155238886 with your Twilio WhatsApp sandbox number and whatsapp:+1234567890 with your personal WhatsApp number.
  5. Save the script as a .py file (e.g., flight_tracker.py).
  6. Run the script from your terminal using the command python flight_tracker.py.

With the script running, you'll receive WhatsApp notifications whenever the flight price drops below your specified threshold. How cool is that?

Setting Up Automatic Execution

Now that you have a working script, the next step is to set it up to run automatically. You don't want to have to manually start the script every day, right? This section will guide you through setting up automatic execution using system scheduling tools.

Using Task Scheduler (Windows)

If you're using Windows, you can use the Task Scheduler to run your script automatically. Task Scheduler is a built-in Windows tool that allows you to schedule tasks to run at specific times or intervals. Here’s how to set it up:

  1. Open Task Scheduler by searching for "Task Scheduler" in the Start menu.
  2. In the Task Scheduler window, click on "Create Basic Task" in the right-hand pane.
  3. Give your task a name (e.g., "Flight Tracker") and click "Next."
  4. Choose the trigger for your task. You can select "Daily," "Weekly," or "Monthly" depending on how often you want to run the script. For example, if you want to run the script every day, select "Daily" and click "Next."
  5. Set the time and date for the task to start and click "Next."
  6. Choose the action "Start a program" and click "Next."
  7. In the "Program/script" field, enter python. In the "Add arguments" field, enter the full path to your Python script (e.g., C:\path\to\flight_tracker.py). In the "Start in" field, enter the directory where your script is located. Click "Next."
  8. Review the task details and click "Finish."

With these steps, your script will now run automatically according to the schedule you've set. You can always modify the task in Task Scheduler if you need to change the schedule or other settings.

Using Cron (macOS and Linux)

If you're using macOS or Linux, you can use cron to schedule your script. Cron is a time-based job scheduler in Unix-like operating systems. Here’s how to set it up:

  1. Open your terminal.

  2. Type crontab -e and press Enter. This will open the crontab file in a text editor. If this is the first time you're using cron, you may be prompted to choose an editor. Select your preferred editor.

  3. Add a new line to the crontab file with the schedule and command for your script. The cron syntax is as follows:

    minute hour day_of_month month day_of_week command
    

    For example, to run your script every day at 8:00 AM, you would add the following line:

    0 8 * * * /usr/bin/python3 /path/to/flight_tracker.py
    

    Replace /usr/bin/python3 with the full path to your Python executable and /path/to/flight_tracker.py with the full path to your script. If you're not sure where your Python executable is located, you can find it by running which python3 in your terminal.

  4. Save the crontab file and exit the editor. Cron will automatically load the new schedule.

With cron set up, your script will now run automatically according to the schedule you've defined. You can edit the crontab file at any time to change the schedule or other settings.

Customization and Further Improvements

Now that you have a working flight price tracker, let's explore some ways you can customize and improve it. This section will cover adding more features, handling multiple flights, and integrating with other services.

Adding More Features (e.g., Price History, Multiple Destinations)

One way to enhance your script is to add the ability to track price history. This would involve storing the flight prices over time and displaying them in a graph or chart. You could use a database or a simple text file to store the price data. Another useful feature is the ability to track multiple destinations. Instead of just tracking one flight, you could configure the script to track several flights to different destinations. This would require modifying the script to accept a list of URLs and threshold prices, and then iterating over the list to check each flight.

Handling Multiple Flights and Destinations

To handle multiple flights and destinations, you could modify the script to read the flight details from a configuration file. This file could contain a list of URLs, threshold prices, and other settings. The script would then loop through this list, checking the price for each flight and sending notifications as needed. This approach makes the script more flexible and easier to configure.

Integrating with Other Services (e.g., IFTTT, Google Sheets)

To make your flight price tracker even more powerful, you could integrate it with other services. For example, you could use IFTTT (If This Then That) to trigger actions based on the flight price notifications. IFTTT allows you to connect different services and create automated workflows. You could set up an IFTTT applet to automatically add the flight details to a Google Sheets spreadsheet whenever a price drop notification is received. This would allow you to keep a record of the price changes and make it easier to analyze the data. Another integration option is to use Google Sheets directly to store the price data. You could use the Google Sheets API to write the flight prices to a spreadsheet, allowing you to track the prices over time and create charts and graphs.

Conclusion

Alright, guys, we've reached the end of our journey on building a Python script to track flight prices and send WhatsApp notifications. You've learned how to set up your environment, write the code, schedule automatic execution, and even customize the script with additional features. This project is not just a practical tool for finding cheap flights; it's also a fantastic way to level up your Python skills and explore the world of web scraping and automation. Remember, the possibilities are endless when you combine programming with real-world problems. So go ahead, tweak the script, add your own personal touch, and start saving money on your next adventure! Happy travels, and happy coding!

Recap of Key Steps and Benefits

Let's quickly recap the key steps we covered in this article. First, we set up our environment by installing Python and the necessary libraries. Then, we wrote the Python script, which involved fetching flight prices from a website, sending WhatsApp messages using Twilio, and scheduling the script to run automatically. We also explored how to customize the script with additional features and integrate it with other services. The benefits of this project are numerous. You'll save time by automating flight price tracking, increase your chances of finding the best deals, and receive instant notifications via WhatsApp. Plus, you'll gain valuable experience in Python programming, web scraping, and automation.

Encouragement to Customize and Experiment

Now that you have a solid foundation, I encourage you to take this script and make it your own. Experiment with different websites, add more features, and integrate it with other services. The beauty of programming is that there's always something new to learn and explore. Don't be afraid to try new things and see what you can create. Whether you're a seasoned programmer or just starting out, this project is a great way to expand your skills and build something useful. So go ahead, dive in, and let your creativity soar! Remember, every great programmer started somewhere, and this could be the project that sparks your passion for coding.