Home>

I use a telegram bot to access the database with goods. But in response, the user receives a list of products in turn. I wanted to send the whole list in one message.

Code excerpt:

bot.register_next_step_handler(c, show_category)
def show_category(message):
    chat_id= message.chat.id
    user_data=message.text
    cursor.execute(f'''
        select product_id, title, price from products
        join categories using(category_id) where category_name=%s
    ''', (user_data,))
    category_products=cursor.fetchall()
    for products in category_products:
        product_id=products[0]
        title=products[1]
        price=products[2]
        message_to_user= f'''{title}\nPrice: {price}\nDetails: /product_{product_id}'''
        bot.send_message(chat_id, message_to_user)
  • Answer # 1

    I mean how? Before iteration (for) definemessage_to_user= "", in the iterator itself, change to

    message_to_user += f'{title}\nPrice: {price}\nDetails: /product_{product_id}\n'
    

    And after and most importantly OUTSIDE of the iterator, you make a send message. In the end something like this.

    message_to_user= ""
    for products in category_products:
        product_id=products[0]
        title=products[1]
        price=products[2]
        message_to_user += f'{title}\nPrice: {price}\nDetails: /product_{product_id}\n'
    bot.send_message(chat_id, message_to_user)
    

    Thanks a lot! Working :-)

    Handsome_7772022-01-30 10:23:17