This commit is contained in:
Joan
2023-11-09 19:03:20 +01:00
parent 83bc0038b1
commit 0c4c075fef

View File

@@ -284,91 +284,94 @@ async def update_conjunta(update: Update, context: CallbackContext, conjunta_id)
# Función para unirse a una conjunta # Función para unirse a una conjunta
async def handle_conjunta(update: Update, context: CallbackContext): async def handle_conjunta(update: Update, context: CallbackContext):
user_id = update.effective_user.id try:
user_name = update.effective_user.username user_id = update.effective_user.id
reply_message_id = update.message.reply_to_message.message_id user_name = update.effective_user.username
message = update.message.text message = update.message.text
reply_message_id = update.message.reply_to_message.message_id
cursor.execute("SELECT * FROM conjuntas WHERE message_id=?", (reply_message_id,)) cursor.execute("SELECT * FROM conjuntas WHERE message_id=?", (reply_message_id,))
conjunta = cursor.fetchone() conjunta = cursor.fetchone()
if conjunta: if conjunta:
conjunta_id, message_id, product_name, product_description, limit, limit_per_user, price, price_member, closed, photo_id = conjunta conjunta_id, message_id, product_name, product_description, limit, limit_per_user, price, price_member, closed, photo_id = conjunta
regex_borrar = r'\b(?!apunto)(desapunto|borro|desapuntar|borrar)\b' regex_borrar = r'\b(?!apunto)(desapunto|borro|desapuntar|borrar)\b'
regex_apuntar = r'\b(apunto|me uno)\b' regex_apuntar = r'\b(apunto|me uno)\b'
# Si el usuario se borra... # Si el usuario se borra...
if re.findall(regex_borrar, message, re.IGNORECASE): if re.findall(regex_borrar, message, re.IGNORECASE):
if closed == 0: if closed == 0:
cursor.execute("SELECT * FROM conjunta_users WHERE conjunta_id=? AND user_id=?", (conjunta_id, user_id)) cursor.execute("SELECT * FROM conjunta_users WHERE conjunta_id=? AND user_id=?", (conjunta_id, user_id))
user_conjunta = cursor.fetchone() user_conjunta = cursor.fetchone()
if user_conjunta: if user_conjunta:
cursor.execute("DELETE FROM conjunta_users WHERE id = ?", (user_conjunta[0],)) cursor.execute("DELETE FROM conjunta_users WHERE id = ?", (user_conjunta[0],))
conn.commit() conn.commit()
worksheet = spreadsheet.worksheet(f"{product_name} - {conjunta_id}") worksheet = spreadsheet.worksheet(f"{product_name} - {conjunta_id}")
found_cell = worksheet.find(user_name) found_cell = worksheet.find(user_name)
if found_cell: if found_cell:
worksheet.delete_rows(found_cell.row) worksheet.delete_rows(found_cell.row)
await update.message.reply_text("¡Desapuntado de la conjunta!") await update.message.reply_text("¡Desapuntado de la conjunta!")
await send_message_to_admins(update, context, f"@{user_name} se ha desapuntado de la conjunta {product_name} - {conjunta_id}") await send_message_to_admins(update, context, f"@{user_name} se ha desapuntado de la conjunta {product_name} - {conjunta_id}")
try: try:
await update_conjunta(update, context, conjunta_id) await update_conjunta(update, context, conjunta_id)
except Exception: except Exception:
pass pass
else:
await update.message.reply_text("La conjunta ya está cerrada y no puedes borrarte.")
# Si el usuario se apunta...
if re.findall(regex_apuntar, message, re.IGNORECASE):
if closed == 0:
cursor.execute("SELECT * FROM conjunta_users WHERE conjunta_id=? AND user_id=?", (conjunta_id, user_id))
user_conjunta = cursor.fetchone()
if user_conjunta:
await update.message.reply_text("Ya te has unido a esta conjunta.")
else: else:
regex_numeros = r'\d+' await update.message.reply_text("La conjunta ya está cerrada y no puedes borrarte.")
search_quantity = re.search(regex_numeros, message)
if search_quantity: # Si el usuario se apunta...
quantity = search_quantity.group() if re.findall(regex_apuntar, message, re.IGNORECASE):
if closed == 0:
cursor.execute("SELECT * FROM conjunta_users WHERE conjunta_id=? AND user_id=?", (conjunta_id, user_id))
user_conjunta = cursor.fetchone()
if user_conjunta:
await update.message.reply_text("Ya te has unido a esta conjunta.")
else: else:
quantity = 1 regex_numeros = r'\d+'
search_quantity = re.search(regex_numeros, message)
try: if search_quantity:
quantity = int(quantity) quantity = search_quantity.group()
if quantity <= 0:
raise ValueError
if limit is not None and quantity > limit_per_user or limit is not None and quantity > quantity_left(conjunta_id):
await update.message.reply_text("La cantidad deseada excede el límite por usuario de la conjunta o no quedan suficientes.")
else: else:
if user_name: quantity = 1
cursor.execute("INSERT INTO conjunta_users (conjunta_id, user_id, user_name, quantity) VALUES (?, ?, ?, ?)",
(conjunta_id, user_id, user_name, quantity))
conn.commit()
socios_worksheet = spreadsheet.worksheet("Socios") try:
socio = socios_worksheet.find(user_name) quantity = int(quantity)
if quantity <= 0:
worksheet = spreadsheet.worksheet(f"{product_name} - {conjunta_id}") raise ValueError
worksheet.append_row([user_name, quantity, "" if socio else "NO"]) if limit is not None and quantity > limit_per_user or limit is not None and quantity > quantity_left(conjunta_id):
await update.message.reply_text("La cantidad deseada excede el límite por usuario de la conjunta o no quedan suficientes.")
await update.message.reply_text(f"Te has unido a la conjunta para '{product_name}' con {quantity} unidades.")
await send_message_to_admins(update, context, f"@{user_name} se ha apunta a la conjunta {product_name} - {conjunta_id} con {quantity} unidades")
try:
await update_conjunta(update, context, conjunta_id)
except Exception:
pass
else: else:
await update.message.reply_text("Por favor, tienes que ponerte un nick en Telegram para poder participar.") if user_name:
except ValueError: cursor.execute("INSERT INTO conjunta_users (conjunta_id, user_id, user_name, quantity) VALUES (?, ?, ?, ?)",
await update.message.reply_text("Por favor, introduce una cantidad válida.") (conjunta_id, user_id, user_name, quantity))
else: conn.commit()
await update.message.reply_text("La conjunta ya está cerrada y no puedes unirte.")
socios_worksheet = spreadsheet.worksheet("Socios")
socio = socios_worksheet.find(user_name)
worksheet = spreadsheet.worksheet(f"{product_name} - {conjunta_id}")
worksheet.append_row([user_name, quantity, "" if socio else "NO"])
await update.message.reply_text(f"Te has unido a la conjunta para '{product_name}' con {quantity} unidades.")
await send_message_to_admins(update, context, f"@{user_name} se ha apunta a la conjunta {product_name} - {conjunta_id} con {quantity} unidades")
try:
await update_conjunta(update, context, conjunta_id)
except Exception:
pass
else:
await update.message.reply_text("Por favor, tienes que ponerte un nick en Telegram para poder participar.")
except ValueError:
await update.message.reply_text("Por favor, introduce una cantidad válida.")
else:
await update.message.reply_text("La conjunta ya está cerrada y no puedes unirte.")
except Exception as e:
logging.error(f"Error handling message: {e}")
async def close_conjunta(update: Update, context: CallbackContext): async def close_conjunta(update: Update, context: CallbackContext):
user_id = update.effective_user.id user_id = update.effective_user.id
@@ -527,13 +530,6 @@ def main()->None:
application.add_handler(CallbackQueryHandler(close_conjunta, pattern="close \d")) application.add_handler(CallbackQueryHandler(close_conjunta, pattern="close \d"))
application.add_handler(MessageHandler(filters.REPLY, handle_conjunta)) application.add_handler(MessageHandler(filters.REPLY, handle_conjunta))
# Avisamos de que el bot está en funcionamiento
for admin_id in admin_ids:
try:
await application.bot.send_message(chat_id=admin_id, text="El bot acaba de arrancar y está en funcionamiento.")
except Exception as e:
logging.error(f"Error sending message: {e}")
application.run_polling() application.run_polling()
conn.close() conn.close()