Files
amazon-telegram/bot/dbhelper.py

58 lines
2.2 KiB
Python

import sqlite3
import requests
import constants
import helpers
import logging
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
def setup_db():
con = sqlite3.connect(constants.DB)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS amazon(id INTEGER PRIMARY KEY AUTOINCREMENT, \
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, tg_user TEXT, tg_group TEXT, \
tg_user_id INTEGER, tg_group_id INTEGER, url TEXT, referurl TEXT, price TEXT, \
title TEXT, image TEXT)")
con.close()
def add_product(tg_user, tg_group, tg_user_id, tg_group_id, url, referurl, title, price, image):
logging.info(f"Inserting into database: tg_user: '{tg_user}', tg_group: '{tg_group}', tg_user_id: {tg_user_id}, tg_group_id: {tg_group_id}, url: '{url}', referurl: '{referurl}', price: '{price}', title: '{title}', image: '{image}'")
con = sqlite3.connect(constants.DB)
cur = con.cursor()
params = (tg_user, tg_group, tg_user_id, tg_group_id, url, referurl, title, price, image)
cur.execute(f"INSERT INTO amazon (tg_user, tg_group, tg_user_id, tg_group_id, url, referurl, price, title, image) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", params)
product_id = cur.lastrowid
con.commit()
con.close()
try:
response = requests.get(image, headers=constants.HEADERS)
file = open(f"/app/data/images/products/{product_id}.jpg", "wb")
file.write(response.content)
file.close()
except:
pass
return product_id
def check_product(referurl, price):
con = sqlite3.connect(constants.DB)
cur = con.cursor()
cur.execute(f"SELECT * FROM amazon WHERE referurl='{referurl}' ORDER BY id DESC")
result = cur.fetchone()
if result is None:
helpers.logging.info("New entry, creating in DB")
return False
else:
helpers.logging.info("Already exists, checking price")
if price == result[8]:
helpers.logging.info("Price is the same, retrieving link")
return result[0]
else:
helpers.logging.info("Price is different, creating new entry in DB")
return False