1

我是一个初学者,我有一个问题:我将使用 botogram 创建一个电报机器人,我想通过 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()
4

2 回答 2

1

您不是循环list创建三个按钮,而是循环list发送三个消息。创建您的按钮定义列表,然后在循环中添加到它,然后在循环之外发送消息。

于 2020-04-14T19:27:25.443 回答
0

我从未使用过 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)

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

于 2020-04-14T19:35:48.970 回答