Migrated from sqlite to MySQL

This commit is contained in:
Joan Cano
2023-07-04 00:14:14 +02:00
parent 3c1fb2474b
commit 69b2034bbe
7 changed files with 266 additions and 110 deletions

View File

@@ -1,7 +1,5 @@
import json
import threading
import logging
import prettytable
import helpers
import walladb
import constants
@@ -20,6 +18,8 @@ from telegram.ext import (
filters
)
SEARCH_THREADS_LIST = []
ACTION, ADD_PRODUCT_NAME, ADD_PRODUCT_MIN_PRICE, ADD_PRODUCT_MAX_PRICE, \
ADD_PRODUCT_CATEGORY, ADD_PRODUCT_TITLE_EXCLUDE, ADD_PRODUCT_DESCRIPTION_EXCLUDE, \
ADD_PRODUCT_COORDS, ADD_PRODUCT_DISTANCE, REMOVE_PRODUCT, LIST, FINISH, CONTINUE_OR_FINISH = range(13)
@@ -304,6 +304,7 @@ async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
return ConversationHandler.END
async def remove_product(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
global SEARCH_THREADS_LIST
await update.callback_query.edit_message_reply_markup(None)
query = update.callback_query
product_name = query.data
@@ -312,6 +313,9 @@ async def remove_product(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
if walladb.remove_product({'product_name' : product_name, \
'telegram_user_id' : telegram_user_id}):
message = f"¡{product_name} borrado de la lista de seguimiento!"
product_thread = helpers.get_thread(product_name)
if product_thread != None:
product_thread.stop()
await context.bot.send_message(chat_id=update.effective_chat.id, text=message)
return ConversationHandler.END
@@ -324,8 +328,8 @@ async def product_details(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
if product:
categories = helpers.generate_categories_string(product['category'], product['subcategory'])
text = f"*Nombre del producto:* {helpers.telegram_escape_characters(product['product_name'])}\n\
*Precio desde *{product['min_price']}€ *hasta *{product['max_price']}\n\
*En las coordenadas *{helpers.telegram_escape_characters(product['latitude'])}, {helpers.telegram_escape_characters(product['longitude'])} *y a *{product['distance']}km *de estas*\n\
*Precio desde *{helpers.telegram_escape_characters(str(product['min_price']))}€ *hasta *{helpers.telegram_escape_characters(str(product['max_price']))}\n\
*En las coordenadas *{helpers.telegram_escape_characters(str(product['latitude']))}, {helpers.telegram_escape_characters(str(product['longitude']))} *y a *{product['distance']}km *de estas*\n\
*En las categorías: *{helpers.telegram_escape_characters(categories)}\n\
*Palabras excluídas del título: *`{helpers.telegram_escape_characters(product['title_exclude'])}`\n\
*Palabras excluídas del título y la descripción: *`{helpers.telegram_escape_characters(product['title_description_exclude'])}`"
@@ -376,7 +380,7 @@ async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
if walladb.is_user_valid(telegram_user_id):
type = walladb.get_user_type(telegram_user_id)
until = walladb.get_user_until(telegram_user_id)
message = f"Tu cuenta es tipo: {type} y caduca el {until}."
message = f"Tu cuenta es tipo: {type} y caduca el {helpers.get_spanish_date(until)}."
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -385,7 +389,7 @@ async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
if not walladb.is_user_valid(telegram_user_id):
until = helpers.get_date_ahead(7)
walladb.add_test_user(telegram_user_id, telegram_user_name, until)
message = f"Periodo de prueba activado hasta el {until}."
message = f"Periodo de prueba activado hasta el {helpers.get_spanish_date(until)}."
else:
message = "Ya has utilizado el periodo de prueba."
if walladb.is_user_testing(telegram_user_id):
@@ -395,10 +399,12 @@ async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
async def add_to_db_and_send(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
global SEARCH_THREADS_LIST
logging.info(f"Adding product with context: {context.user_data}")
walladb.add_product(context.user_data)
p = threading.Thread(target=Worker.run, args=(walladb.get_product(context.user_data), ))
p.start()
SEARCH_THREADS_LIST.append((context.user_data, p))
await context.bot.send_message(chat_id=update.effective_chat.id, text=f"¡*{helpers.telegram_escape_characters(context.user_data['product_name'])}* añadido correctamente\!", parse_mode=ParseMode.MARKDOWN_V2)
def error(update, context):
@@ -410,7 +416,25 @@ async def conv_timeout(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
async def conv_finish(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await context.bot.send_message(chat_id=update.effective_chat.id, text="Vuelve a usar el menú si quieres añadir otro producto.")
async def list_threads(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if helpers.is_user_admin(update.message.chat_id):
global SEARCH_THREADS_LIST
tmp_search_threads_list = []
threads_string = ""
for thread in SEARCH_THREADS_LIST:
if thread[1].is_alive():
tmp_search_threads_list.append((thread[0], thread[1]))
threads_string = threads_string + f"{thread[0]['product_name']} - {thread[0]['telegram_user_id']}\n"
SEARCH_THREADS_LIST = tmp_search_threads_list
if len(threads_string) > 2000:
my_strings = [(threads_string[i:i+2000]) for i in range(0, len(threads_string), 2000)]
for my_string in my_strings:
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(f"{my_string}"))
else:
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(f"{threads_string}"))
def main()->None:
global SEARCH_THREADS_LIST
walladb.setup_db()
products = walladb.get_all_products()
@@ -418,6 +442,7 @@ def main()->None:
logging.info(product)
p = threading.Thread(target=Worker.run, args=(product, ))
p.start()
SEARCH_THREADS_LIST.append((product, p))
"""Start the bot."""
# Create the Application and pass it your bot's token.
@@ -430,6 +455,7 @@ def main()->None:
application.add_handler(CommandHandler("remove_user", remove_user_command))
application.add_handler(CommandHandler("status", status_command))
application.add_handler(CommandHandler("test", test_command))
application.add_handler(CommandHandler("list_threads", list_threads))
#application.add_handler(CallbackQueryHandler("list", send_list()))
#application.add_handler(CallbackQueryHandler(pattern="list", callback=send_list()))