在Python中动态构造InlineKeyboardButton

时间:2018-03-14 17:30:57

标签: python telegram-bot python-telegram-bot

我想在python中为Telegram创建一个 InlineKeyboardButton ,如下面的函数,但我想动态地做。此功能将两个按钮分组在一行中,并将一个按钮添加到第二行。我想每行做两个按钮。

def options(bot, update):
    keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
                 InlineKeyboardButton("Option 2", callback_data='2')],
                [InlineKeyboardButton("Option 3", callback_data='3')]]

    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Please choose:', reply_markup = reply_markup)

但是,无论我尝试什么,我都会收到像

这样的错误消息
data['inline_keyboard'].append([x.to_dict() for x in inline_keyboard])
AttributeError: 'list' object has no attribute 'to_dict'

我的代码如下:

def create_options(self, gid, Events):
    opts = []
    o = []
    keyboard = []

    for i, events in enumerate(Events):
        if (events.gid == gid):
            o.append([[InlineKeyboardButton(events.etkinlik + u" ", callback_data=i),InlineKeyboardButton(events.etkinlik + u" ", callback_data=i)]])
            opts.append(o)
    keyboard.append(opts)
    return InlineKeyboardMarkup(keyboard)
你可以建议我做错了吗?

非常感谢你的帮助

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,如果我以这种方式编码,它就像我想要的那样工作。

keyboard = []
for i, events in enumerate(Events):
     if (events.gid == gid):
        keyboard = keyboard + 
        [[InlineKeyboardButton(events.etkinlik + u" ", callback_data=i),
          InlineKeyboardButton(events.etkinlik + u" ", callback_data=i + 100)]]
return InlineKeyboardMarkup(keyboard)