Mejoradas funciones y añadido README
This commit is contained in:
@@ -5,8 +5,8 @@ import logging
|
||||
import prettytable
|
||||
|
||||
from worker import Worker
|
||||
from telegram import ForceReply, Update
|
||||
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
|
||||
from telegram import Update
|
||||
from telegram.ext import Application, CommandHandler, ContextTypes
|
||||
|
||||
TELEGRAM_CHANNEL_ID = os.getenv("TELEGRAM_CHANNEL_ID")
|
||||
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
||||
@@ -22,61 +22,107 @@ logging.basicConfig(
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def parse_json_file():
|
||||
f = open("products.json")
|
||||
f = open("/app/data/products.json")
|
||||
return json.load(f)
|
||||
|
||||
def save_json_file(products):
|
||||
with open('products.json', 'w') as outfile:
|
||||
with open('/app/data/products.json', 'w') as outfile:
|
||||
json.dump(products, outfile, indent=2)
|
||||
|
||||
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Send a message when the command /help is issued."""
|
||||
message = "Add with /add product;min_price;max_price"
|
||||
await update.message.reply_text(message)
|
||||
message = """Añade un producto con `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
||||
Ejemplo: `/add placa base itx;0;150`\n
|
||||
Ejemplo 2: `/add cpu;10;30;;intel,core 2 duo,celeron;;;100`\n
|
||||
Los campos opcionales que se dejen vacíos tomarán el valor configurado en el archivo `\.env`\n
|
||||
Lista los productos con `/list` o obtén la información de uno en concreto con `/list nombre del producto`\n
|
||||
Borra un producto con `/remove nombre del producto`"""
|
||||
await update.message.reply_markdown_v2(message)
|
||||
|
||||
async def add_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
parsed = update.message.text.split(";")
|
||||
logging.info(parsed)
|
||||
if len(parsed) < 3:
|
||||
#message = "You must pass the correct number of arguments: /add product;min_price;max_price;latitude(optional);longitude(optional);distance(optional);title_exclude(optional);title_description_exclude(optional)"
|
||||
message = "You must pass the correct number of arguments: /add product;min_price;max_price"
|
||||
else:
|
||||
product = {"product_name": f"{parsed[0][len('/add '):]}", #removes "/add "
|
||||
"distance": "0",
|
||||
"latitude": f"{LATITUDE}",
|
||||
"longitude": f"{LONGITUDE}",
|
||||
message = """Tienes que pasar el número correcto de parámetros: `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
||||
Ejemplo: `/add placa base itx;0;150`\n
|
||||
Ejemplo 2: `/add cpu;10;30;;intel,core 2 duo,celeron;;;100`\n
|
||||
Los campos opcionales que se dejen vacíos tomarán el valor configurado en el archivo `\.env`"""
|
||||
|
||||
args = update.message.text.split("/add ")
|
||||
if len(args) == 1:
|
||||
pass
|
||||
elif len(args[1].split(";")) > 2:
|
||||
args = args[1].split(";")
|
||||
logging.info(f'Adding: {args}')
|
||||
title_exclude, title_description_exclude, latitude, longitude, distance = [], [], LATITUDE, LONGITUDE, "0"
|
||||
product_name, min_price, max_price = args[0:3]
|
||||
if len(args) > 3 and args[3]:
|
||||
title_exclude = args[3].split(",")
|
||||
if len(args) > 4 and args[4]:
|
||||
title_description_exclude = args[4].split(",")
|
||||
if len(args) > 5 and args[5]:
|
||||
latitude = args[5]
|
||||
if len(args) > 6 and args[6]:
|
||||
longitude = args[6]
|
||||
if len(args) > 7 and args[7]:
|
||||
distance = args[7]
|
||||
|
||||
product = {"product_name": product_name,
|
||||
"distance": distance,
|
||||
"latitude": latitude,
|
||||
"longitude": longitude,
|
||||
"condition": "all",
|
||||
"min_price": f"{parsed[1]}",
|
||||
"max_price": f"{parsed[2]}",
|
||||
"title_keyword_exclude" : [],
|
||||
"exclude": []
|
||||
"min_price": min_price,
|
||||
"max_price": max_price,
|
||||
"title_keyword_exclude" : title_description_exclude,
|
||||
"exclude": title_exclude
|
||||
}
|
||||
|
||||
products = parse_json_file()
|
||||
products.append(product)
|
||||
save_json_file(products)
|
||||
p = threading.Thread(target=Worker.run, args=(product, ))
|
||||
p.start()
|
||||
message = f"Added {parsed[0][5:]}"
|
||||
await update.message.reply_text(message)
|
||||
found = False
|
||||
for fproduct in products:
|
||||
if fproduct['product_name'] == product_name:
|
||||
found = True
|
||||
if not found:
|
||||
products.append(product)
|
||||
save_json_file(products)
|
||||
p = threading.Thread(target=Worker.run, args=(product, ))
|
||||
p.start()
|
||||
message = f"Añadido {product_name} a seguimiento"
|
||||
else:
|
||||
message = f"{product_name} ya está en seguimiento\!"
|
||||
await update.message.reply_markdown_v2(message)
|
||||
|
||||
async def remove_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
products = parse_json_file()
|
||||
product_to_remove = update.message.text[len('/remove '):]
|
||||
message = f"{product_to_remove} no está en seguimiento!"
|
||||
products = parse_json_file()
|
||||
for product in products:
|
||||
if product['product_name'] == product_to_remove:
|
||||
products.remove(product)
|
||||
message = f"{product_to_remove} borrado!"
|
||||
save_json_file(products)
|
||||
await update.message.reply_text(f"{product_to_remove} removed!")
|
||||
await update.message.reply_text(message)
|
||||
|
||||
async def list_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
products = parse_json_file()
|
||||
|
||||
table = prettytable.PrettyTable(['Product', 'Min', 'Max'])
|
||||
table.align['Product'] = 'l'
|
||||
table.align['Min Price'] = 'r'
|
||||
table.align['Max Price'] = 'r'
|
||||
for product in products:
|
||||
table.add_row([product['product_name'], f"{product['min_price']}€", f"{product['max_price']}€"])
|
||||
args = update.message.text.split("/list ")
|
||||
found = False
|
||||
if len(args) > 1:
|
||||
table = prettytable.PrettyTable(['Campo', 'Valor'])
|
||||
table.align['Campo'] = 'l'
|
||||
table.align['Valor'] = 'r'
|
||||
for product in products:
|
||||
if product['product_name'] == args[1]:
|
||||
for key in product:
|
||||
table.add_row([key, product[key]])
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
table = prettytable.PrettyTable(['Producto', 'Mín', 'Máx'])
|
||||
table.align['Producto'] = 'l'
|
||||
table.align['Mín'] = 'r'
|
||||
table.align['Máx'] = 'r'
|
||||
for product in products:
|
||||
table.add_row([product['product_name'], f"{product['min_price']}€", f"{product['max_price']}€"])
|
||||
await update.message.reply_markdown_v2(f'```{table}```')
|
||||
|
||||
def main()->None:
|
||||
|
||||
Reference in New Issue
Block a user