Modified categories. Remove buttons when used. Added timeout to conversation. Check if user is expired. Added telegram name. Fixed bug with lowercase.
This commit is contained in:
@@ -31,28 +31,11 @@ logging.basicConfig(
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def parse_json_file():
|
||||
f = open("/app/data/products.json")
|
||||
return json.load(f)
|
||||
|
||||
def save_json_file(products):
|
||||
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:
|
||||
if walladb.is_user_valid(helpers.get_telegram_user_id(update)):
|
||||
message = """Añade un producto con `/add producto;precio_mínimo;precio_máximo,categoría,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
|
||||
Ejemplo 3: `/add tiny;0;100;informática`\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`\n
|
||||
`/status` muestra tu tipo de membresía y fecha de caducidad\n
|
||||
`/categories` muestra las categorías disponibles"""
|
||||
message = "Utiliza el menú de la conversación para añadir un producto y sigue los pasos indicados"
|
||||
else:
|
||||
message = """Activa tu periodo de prueba de 7 días con `/test` o contacta con @jocarduck para más información."""
|
||||
message = "Activa tu periodo de prueba de 7 días con `/test` o contacta con @jocarduck para más información."
|
||||
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
|
||||
|
||||
async def main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
@@ -68,6 +51,7 @@ async def main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
return ACTION
|
||||
|
||||
async def menu_click_handler(update: Update, context: CallbackContext):
|
||||
await update.callback_query.edit_message_reply_markup(None)
|
||||
telegram_user_id = helpers.get_telegram_user_id(update)
|
||||
if walladb.is_user_valid(telegram_user_id):
|
||||
context.user_data['telegram_user_id'] = telegram_user_id
|
||||
@@ -99,11 +83,10 @@ async def menu_click_handler(update: Update, context: CallbackContext):
|
||||
return REMOVE_PRODUCT
|
||||
if query.data == 'list':
|
||||
await send_list(update, context)
|
||||
#await context.bot.send_message(chat_id=update.effective_chat.id, text='Send your name', reply_markup=ForceReply())
|
||||
return ConversationHandler.END
|
||||
else:
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id,
|
||||
text='Activa tu periodo de prueba de 7 días con `/test` o contacta con @jocarduck para más información.', parse_mode=ParseMode.MARKDOWN_V2)
|
||||
text=helpers.telegram_escape_characters('Activa tu periodo de prueba de 7 días con `/test` o contacta con @jocarduck para más información.'), parse_mode=ParseMode.MARKDOWN_V2)
|
||||
return ConversationHandler.END
|
||||
|
||||
async def add_product_name(update: Update, context: CallbackContext):
|
||||
@@ -162,6 +145,7 @@ async def add_product_max_price(update: Update, context: CallbackContext):
|
||||
return ADD_PRODUCT_CATEGORY
|
||||
|
||||
async def add_product_category(update: Update, context: CallbackContext):
|
||||
await update.callback_query.edit_message_reply_markup(None)
|
||||
query = update.callback_query
|
||||
if query.data == 'category':
|
||||
markup = InlineKeyboardMarkup(helpers.create_category_keyboard())
|
||||
@@ -177,6 +161,8 @@ async def add_product_category(update: Update, context: CallbackContext):
|
||||
return ConversationHandler.END
|
||||
|
||||
async def continue_or_finish(update: Update, context: CallbackContext):
|
||||
if update.callback_query != None:
|
||||
await update.callback_query.edit_message_reply_markup(None)
|
||||
markup = InlineKeyboardMarkup(helpers.create_continue_keyboard())
|
||||
last_step = context.user_data.get('last_step', '')
|
||||
query = update.callback_query
|
||||
@@ -195,6 +181,8 @@ async def continue_or_finish(update: Update, context: CallbackContext):
|
||||
|
||||
if last_step == 'category':
|
||||
category = int(query.data)
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id,
|
||||
text=f"Categoría escogida: {helpers.get_category_name(category)}")
|
||||
context.user_data['category'] = category
|
||||
context.user_data['last_step'] = ''
|
||||
|
||||
@@ -207,13 +195,13 @@ async def continue_or_finish(update: Update, context: CallbackContext):
|
||||
context.user_data['title_exclude'] = update.message.text
|
||||
context.user_data['last_step'] = ''
|
||||
|
||||
if qd == 'description_exclude':
|
||||
if qd == 'title_description_exclude':
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id,
|
||||
text='Exclusión de descripción', reply_markup=ForceReply())
|
||||
context.user_data['last_step'] = 'description_exclude'
|
||||
context.user_data['last_step'] = 'title_description_exclude'
|
||||
return CONTINUE_OR_FINISH
|
||||
if last_step == 'description_exclude':
|
||||
context.user_data['description_exclude'] = update.message.text
|
||||
if last_step == 'title_description_exclude':
|
||||
context.user_data['title_description_exclude'] = update.message.text
|
||||
context.user_data['last_step'] = ''
|
||||
|
||||
if qd == 'coords':
|
||||
@@ -255,6 +243,7 @@ async def continue_or_finish(update: Update, context: CallbackContext):
|
||||
return CONTINUE_OR_FINISH
|
||||
|
||||
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
logging.info('Conversation cancelled')
|
||||
context.user_data.clear()
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Cancelado.")
|
||||
return ConversationHandler.END
|
||||
@@ -306,7 +295,7 @@ async def add_premium_user_command(update: Update, context: ContextTypes.DEFAULT
|
||||
telegram_user_id = update.message.text.split('/add_premium_user ')[1].split(' ')[0]
|
||||
days = update.message.text.split('/add_premium_user ')[1].split(' ')[1]
|
||||
until = helpers.get_date_ahead(int(days))
|
||||
if not walladb.add_premium_user(telegram_user_id, until):
|
||||
if not walladb.add_premium_user(telegram_user_id, '', until):
|
||||
products = walladb.get_products_from_user(telegram_user_id)
|
||||
|
||||
for product in products:
|
||||
@@ -333,9 +322,10 @@ async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
|
||||
|
||||
async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
telegram_user_id = helpers.get_telegram_user_id(update)
|
||||
telegram_user_name = helpers.get_telegram_user_name(update)
|
||||
if not walladb.is_user_valid(telegram_user_id):
|
||||
until = helpers.get_date_ahead(7)
|
||||
walladb.add_test_user(telegram_user_id, until)
|
||||
walladb.add_test_user(telegram_user_id, telegram_user_name, until)
|
||||
message = f"Periodo de prueba activado hasta el {until}."
|
||||
else:
|
||||
message = "Ya has utilizado el periodo de prueba."
|
||||
@@ -345,7 +335,7 @@ async def test_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
||||
message = "Ya eres premium. No puedes volver al periodo de prueba."
|
||||
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
|
||||
|
||||
async def add_to_db_and_send(update, context):
|
||||
async def add_to_db_and_send(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
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), ))
|
||||
@@ -355,6 +345,12 @@ async def add_to_db_and_send(update, context):
|
||||
def error(update, context):
|
||||
logging.error(f'Update ---{update}--- caused error ---{context.error}---')
|
||||
|
||||
async def conv_timeout(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Se ha superado el tiempo de espera, vuelve a usar el menú si quieres añadir otro producto.")
|
||||
|
||||
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.")
|
||||
|
||||
def main()->None:
|
||||
walladb.setup_db()
|
||||
products = walladb.get_all_products()
|
||||
@@ -366,7 +362,7 @@ def main()->None:
|
||||
|
||||
"""Start the bot."""
|
||||
# Create the Application and pass it your bot's token.
|
||||
application = Application.builder().token(constants.TELEGRAM_TOKEN).build()
|
||||
application = Application.builder().get_updates_http_version('1.1').http_version('1.1').token(constants.TELEGRAM_TOKEN).build()
|
||||
|
||||
# on different commands - answer in Telegram
|
||||
application.add_handler(CommandHandler("help", help_command))
|
||||
@@ -377,6 +373,7 @@ def main()->None:
|
||||
application.add_handler(CommandHandler("test", test_command))
|
||||
|
||||
conv_handler = ConversationHandler(
|
||||
conversation_timeout=60,
|
||||
entry_points=[CommandHandler("menu", main_menu)],
|
||||
states={
|
||||
ACTION: [CallbackQueryHandler(menu_click_handler)],
|
||||
@@ -388,20 +385,16 @@ def main()->None:
|
||||
CONTINUE_OR_FINISH: [CallbackQueryHandler(continue_or_finish),
|
||||
MessageHandler(filters.TEXT, continue_or_finish)],
|
||||
REMOVE_PRODUCT: [MessageHandler(filters.TEXT, remove_product)],
|
||||
ConversationHandler.TIMEOUT: [CallbackQueryHandler(conv_timeout),
|
||||
MessageHandler(filters.TEXT, conv_timeout)],
|
||||
ConversationHandler.END: [MessageHandler(filters.TEXT, conv_finish)],
|
||||
},
|
||||
fallbacks=[CommandHandler("cancel", cancel)],
|
||||
)
|
||||
|
||||
# Add ConversationHandler to application that will be used for handling updates
|
||||
application.add_handler(conv_handler)
|
||||
|
||||
#application.bot.set_chat_menu_button('Menú')
|
||||
|
||||
application.add_error_handler(error)
|
||||
# on non command i.e message - echo the message on Telegram
|
||||
#application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
|
||||
|
||||
# Run the bot until the user presses Ctrl-C
|
||||
application.run_polling()
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user