0

I'm trying to build menu in telegram using python-telegram-bot module and in it's sample there is:

button_list = [
    InlineKeyboardButton("col 1", ...),
    InlineKeyboardButton("col 2", ...),
    InlineKeyboardButton("row 2", ...)
]
reply_markup = InlineKeyboardMarkup(util.build_menu(button_list, n_cols=2))
bot.send_message(..., "A two-column menu", reply_markup=reply_markup)

I get this error:

NameError: global name 'util' is not defined

I couldn't fine the import for that in the samples and it's not recognized there.

what should I exactly import?

Masoud Motallebipour
  • 414
  • 3
  • 16
  • 33

1 Answers1

2

That example is from our Code Snippets page. Therefore to get the code to work, you need to actually include the snippet, since it's not actually a part of the library per se.

def build_menu(buttons,
               n_cols,
               header_buttons,
               footer_buttons):
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
    if header_buttons:
        menu.insert(0, header_buttons)
    if footer_buttons:
        menu.append(footer_buttons)
    return menu

And then change util.build_menu(button_list, n_cols=2) to build_menu(button_list, n_cols=2).

Note that you don't even have to use build_menu to use buttons. It fact it's often simpler to just define your buttons as a two dimensional list instead, so your code would turn into:

button_list = [
    [
        InlineKeyboardButton("col 1", ...),
        InlineKeyboardButton("col 2", ...)
    ],
    [
        InlineKeyboardButton("row 2", ...)
    ]
]
reply_markup = InlineKeyboardMarkup(button_list)
bot.send_message(..., "A two-column menu", reply_markup=reply_markup)
jsmnbom
  • 138
  • 8
  • Tnx, is there any working sample of this? because now I get bad request – Masoud Motallebipour Jun 17 '17 at 14:57
  • Could you please join us in the [python-telegram-bot support group](https://t.me/pythontelegrambotgroup)? We will at least need to see a copy of your code, to figure out why it's not working :) – jsmnbom Jun 18 '17 at 09:52
  • Thanks, However I didn't understand how to add the callback to every button. I mean the part you wrote '...' in the example below the words you wrote in the answer 'It fact it's often simpler to just define your buttons as a two dimensional list instead, so your code would turn into:' – Jacquelyn.Marquardt Aug 25 '17 at 12:41