DEV Community

qing
qing

Posted on

Build a Price Monitoring Bot with Python and Telegram

Build a Price Monitoring Bot with Python and Telegram

Imagine getting instant notifications on your phone whenever your favorite product goes on sale or its price drops. Sounds like a dream come true for any online shopper, right? Well, what if I told you that you can build your own price monitoring bot using Python and Telegram? That's right; with just a few lines of code, you can create a bot that tracks prices and sends you updates in real-time.

Getting Started

To build our price monitoring bot, we'll need to use a few libraries and tools. First, you'll need to have Python installed on your computer. If you don't have it, you can download it from the official Python website. Next, you'll need to install the requests and beautifulsoup4 libraries, which we'll use to scrape product prices from websites. You can install them using pip:

pip install requests beautifulsoup4
Enter fullscreen mode Exit fullscreen mode

We'll also need to create a Telegram bot and get its API token. If you don't know how to do this, don't worry; I'll walk you through the process.

Creating a Telegram Bot

To create a Telegram bot, you'll need to talk to the BotFather bot in Telegram. Here's how you can do it:

  1. Open Telegram and search for "BotFather".
  2. Start a conversation with BotFather and send it the /newbot command.
  3. Follow the instructions to create a new bot and get its API token.
  4. Save the API token; we'll need it later.

Scraping Product Prices

Now that we have our Telegram bot set up, let's move on to scraping product prices. We'll use the requests and beautifulsoup4 libraries to scrape prices from websites. Here's an example of how you can do it:

import requests
from bs4 import BeautifulSoup

# Send a GET request to the product page
url = "https://example.com/product"
response = requests.get(url)

# If the GET request is successful, the status code will be 200
if response.status_code == 200:
    # Get the content of the response
    page_content = response.content

    # Create a BeautifulSoup object and specify the parser
    soup = BeautifulSoup(page_content, 'html.parser')

    # Find the price element on the page
    price_element = soup.find("span", class_="price")

    # Get the price text
    price = price_element.text.strip()

    print("The current price is:", price)
else:
    print("Failed to retrieve the product page")
Enter fullscreen mode Exit fullscreen mode

This code sends a GET request to the product page, parses the HTML content, and extracts the price.

Building the Price Monitoring Bot

Now that we can scrape product prices, let's build our price monitoring bot. We'll use the python-telegram-bot library to interact with our Telegram bot. Here's an example of how you can use it:

import requests
from bs4 import BeautifulSoup
from telegram.ext import Updater, CommandHandler, MessageHandler

# Replace with your Telegram bot API token
API_TOKEN = "YOUR_API_TOKEN"

# Define a function to scrape the product price
def scrape_price():
    url = "https://example.com/product"
    response = requests.get(url)

    if response.status_code == 200:
        page_content = response.content
        soup = BeautifulSoup(page_content, 'html.parser')
        price_element = soup.find("span", class_="price")
        price = price_element.text.strip()
        return price
    else:
        return None

# Define a function to send a price update to the user
def send_price_update(update, context):
    price = scrape_price()
    if price:
        context.bot.send_message(chat_id=update.effective_chat.id, text=f"The current price is: {price}")
    else:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to retrieve the product price")

# Define a function to start the bot
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Welcome to the price monitoring bot!")
    context.bot.send_message(chat_id=update.effective_chat.id, text="Use the /price command to get the current price")

# Create the Updater and dispatcher
updater = Updater(API_TOKEN, use_context=True)
dispatcher = updater.dispatcher

# Add handlers for the /start and /price commands
start_handler = CommandHandler("start", start)
price_handler = CommandHandler("price", send_price_update)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(price_handler)

# Start the bot
updater.start_polling()
Enter fullscreen mode Exit fullscreen mode

This code defines a bot that responds to the /start and /price commands. When the user sends the /price command, the bot scrapes the product price and sends it back to the user.

Scheduling Price Updates

To send price updates to the user at regular intervals, we can use the schedule library. Here's an example of how you can use it:

import schedule
import time

# Define a function to send a price update to the user
def send_price_update():
    price = scrape_price()
    if price:
        # Send the price update to the user
        context.bot.send_message(chat_id=update.effective_chat.id, text=f"The current price is: {price}")
    else:
        # Send an error message to the user
        context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to retrieve the product price")

# Schedule the price update to be sent every hour
schedule.every(1).hours.do(send_price_update)

while True:
    schedule.run_pending()
    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

This code schedules the send_price_update function to be executed every hour.

Conclusion

Building a price monitoring bot with Python and Telegram is a fun and rewarding project that can help you stay on top of price changes for your favorite products. With the code examples and instructions provided in this post, you can create your own bot and start receiving price updates in no time. So why wait? Start building your bot today and take your online shopping experience to the next level! If you have any questions or need further assistance, feel free to ask in the comments below. Happy coding!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Top comments (0)