skip to Main Content

i’m working to create a keyboard on a telegram bot. I would like to create some buttons. I have a problem, i would to create create a sliding keyboard that goes down. There is a problem, with json you can create it by the code n1, but in python i cant find a solution. So how can i convert ‘lista = [“New York”,”Los Angeles”,”Miami”,”Toronto”,”Berlin”,”Rome”]’in json (code n1)?

#code n1 (JSON)
{"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
                         [{"text": "Miami"}, {"text": "Toronto"}],
                         [{"text": "Berlin"}, {"text": "Rome"}]]}


#code2
import json
import time
from pprint import pprint
import telepot
from telepot.loop import MessageLoop
bot = telepot.Bot("token")
lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]
kdict = []
for i in lista:
    kdict.append({"text": i})
    print(kdict)
keyboard = {"keyboard": [kdict]}



def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == "text":
        bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)


MessageLoop(bot, handle).run_as_thread()
while 1:
    time.sleep(10)

2

Answers


  1. To pair items in a list you can create an iterator from the list, zip the iterator with itself, and use a list comprehension to iterator through the zipped pairs:

    seq = iter(lista)
    [[{'text': i} for i in pair] for pair in zip(seq, seq)]
    

    This returns:

    [[{'text': 'New York'}, {'text': 'Los Angeles'}],
     [{'text': 'Miami'}, {'text': 'Toronto'}],
     [{'text': 'Berlin'}, {'text': 'Rome'}]]
    

    You can then convert it into JSON using json.dumps.

    Login or Signup to reply.
  2. Using blhsing answer

    #code n1 (JSON)
    {"keyboard": [[{"text": "New York"}, {"text": "Los Angeles"}],
                             [{"text": "Miami"}, {"text": "Toronto"}],
                             [{"text": "Berlin"}, {"text": "Rome"}]]}
    
    
    #code2
    import json
    import time
    from pprint import pprint
    import telepot
    from telepot.loop import MessageLoop
    bot = telepot.Bot("token")
    lista = ["New York","Los Angeles","Miami","Toronto","Berlin","Rome"]
    
    seq = iter(lista)
    
    keyboard = {"keyboard": [[{'text': i} for i in pair] for pair in zip(seq, seq)]}
    
    
    
    def handle(msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print(content_type, chat_type, chat_id)
    
        if content_type == "text":
            bot.sendMessage(chat_id, msg["text"], reply_markup=keyboard)
    
    
    MessageLoop(bot, handle).run_as_thread()
    while 1:
        time.sleep(10)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search