python循环中的Json

2024-06-01 13:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个完全的初学者,我有一个问题:我将使用僵尸程序创建一个电报机器人,我想通过python循环在JSON代码中插入我的列表元素。在本例中,我想创建纽约、洛杉矶和华盛顿的按钮,{'text': i},但在电报上只显示最后一项(华盛顿)的一个按钮。我想创建3个按钮

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()

Tags: textimportidjsontruebotchat电报
2条回答

您不是通过list来创建三个按钮,而是通过list来发送三条消息。创建按钮定义列表,然后将其添加到循环内,然后在循环外发送消息

我从未使用过botogram,但在我看来,我建议您在for循环(字典-dict)中创建一个变量,然后调用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)

我希望这对你有帮助,至少有一点

相关问题 更多 >