Abdul Gandal
Abdul Gandal

Reputation: 97

Json in python loop

I'm a total beginner, I have a question: I'm going to create a telegram bot using botogram, I would like to insert my list's element in a JSON code by python loop. In this case I would like to create buttons with New York, LA, and Washington, {'text': i}, but on telegram appears just one button with the last item (Washington). I want to create 3 buttons.

import botogram
import json

bot = botogram.create("token")

list = ['New York',"LA", "Washington DC"]

@bot.command("start")
def start_command(chat, message):
    for i in list:
        bot.api.call('sendMessage', {
            'chat_id': chat.id,
            'text': 'Where are you?',
            'reply_markup': json.dumps({
            'keyboard': [
                [
                    {'text': i},
                    {'text': 'Action B'},
                ],
                [
                    {
                        'text': 'Use geolocation',
                        'request_location': True,
                    },
                ],
            ],
            'resize_keyboard': True,
            'one_time_keyboard': True,
            'selective': True,
        }),
    })

if __name__ == "__main__":
     bot.run()

Upvotes: 1

Views: 191

Answers (2)

georgekrax
georgekrax

Reputation: 1189

I have never used botogram, but as I see it, I suggest you create a variable in the for loop (a dictionary - dict) and then call bot.api.call

@bot.command("start")
def start_command(chat, message):
    for i in list:
        dict = {
            'chat_id': chat.id,
            'text': 'Where are you?',
            'reply_markup': {
            'keyboard': [[
                {'text': i},
                {'text': 'Action B'},
            ],
            [
                {
                    'text': 'Use geolocation',
                    'request_location': True,
                },
            ],
        ],
        'resize_keyboard': True,
        'one_time_keyboard': True,
        'selective': True, 
        }
    }
    bot.api.call('sendMessage', dict)

I hope that helps you, at least a little bit!

Upvotes: 0

Jim
Jim

Reputation: 73936

You aren't looping over list to create three buttons, you're looping over list to send three messages. Create your button definition list and then add to it within your loop, then send the message outside of the loop.

Upvotes: 1

Related Questions