Monitorare l'andamento del prezzo di un prodotto Amazon ricevendo degli alert da un bot telegram
Per prima cosa bisogna importare tutte le librerie necessarie al funzionamento:
import sys
import time
import telepot
from telepot.loop import MessageLoop
import requests
from bs4 import BeautifulSoup
from tinydb import TinyDB, Query
Successivamente andiamo a definire le varie funzioni che compongono il bot:
- Funzione per estrarre il prezzo dell'articolo
def getPrice(url):
header ={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}
page = requests.get(url, headers=header)
soup = BeautifulSoup(page.content, 'html.parser')
try:
price = soup.find(id="priceblock_ourprice").getText()
title = soup.find(id="productTitle").getText()
convertedPrice = price[0:-2]
return float(convertedPrice.replace(',','.')), title.strip()
except:
getPrice(url)
- Funzione per verificare se il prezzo è diminuito o aumentato: dopo la verifica aggiorna il prezzo nel database e invio un messaggio all'utente
def checkPrice(table, prod):
convertedPrice, title = getPrice(prod)
lastPrice = table.get(Query()['url'] == prod)
if convertedPrice lastPrice.get("prezzo"):
bot.sendMessage(chatId, "Prezzo aumentato!n" + title + "nNuovo prezzo= " + str(convertedPrice) + " €"+ "nVecchio prezzo= " + str(lastPrice.get("prezzo")) + " €")
table.update({'prezzo': convertedPrice}, Query().titolo == title)
print(convertedPrice)
- Funzione per creare l'oggetto e salvarlo nel file database
def createItem(item):
table = db.table(chatId)
try:
convertedPrice, title = getPrice(item)
table.insert({"titolo": title, 'prezzo': convertedPrice, 'url': item})
except:
createItem(item)
- Funzione per la gestione dei messaggi ricevuti dal bot Telegram
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'text':
table = db.table(chat_id)
chatId=chat_id
createItem(msg["text"])
productArray.append(msg['text'])
bot.sendMessage(chatId, "Prodotto aggiunto alla lista")
Passiamo alla definizione delle variabili necessarie al funzionamento del bot
TOKEN = envToken # Token univoco assegnato al bot telegram
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
chatIds = envChatIds # Array degli id Chat a cui inviare i messaggi di variazione dei prezzi
Definiamo un ciclo infinito in cui viene effettuato il check dei tutti i prodotti inseriti nel file database ogni ora
while True:
for chatId in chatIds:
table = db.table(chatId)
if table:
for product in table:
try:
checkPrice(table, product.get("url"))
except:
checkPrice(table, product.get("url"))
time.sleep(3600)