Skip to content

Instantly share code, notes, and snippets.

@ak4zh
Created July 12, 2018 22:48
Show Gist options
  • Save ak4zh/d32e1ca0b96630299bf4239093a77e4c to your computer and use it in GitHub Desktop.
Save ak4zh/d32e1ca0b96630299bf4239093a77e4c to your computer and use it in GitHub Desktop.
custom build_keyboard helper function, modified version of build_menu in code snippets page
def build_keyboard(buttons, n_cols=2, resize=True, auto_cols=False, auto_arrange=False, header_buttons=None, footer_buttons=None):
text_cols = {1: 8, 2: 7, 3: 6, 4: 5} # dict text size as key and possible columns as value
longest_text, longest_button = 1, buttons[0]
lengths_list = [] # to find second largest text
for button in buttons:
length = len(button.text if isinstance(button, InlineKeyboardButton) else button)
lengths_list.append(length)
longest_button = button if length >= longest_text else longest_button
longest_text = length if length >= longest_text else longest_text
lengths_list.sort()
second_longest = lengths_list[-2]
if auto_arrange and second_longest != longest_text:
longest_text = second_longest
# I don't know why buttons.remove(longest_button) does not work here
# remove longest button to append at end
buttons = [x for x in buttons if x is not longest_button]
else:
auto_arrange = False
if auto_cols:
if longest_text in text_cols:
n_cols = text_cols[longest_text]
else:
n_cols = 2 if longest_text >= 15 else 3 if longest_text >= 10 else 4
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if auto_arrange:
menu.append([longest_button])
if footer_buttons:
menu.append(footer_buttons)
if isinstance(buttons[0], InlineKeyboardButton):
keyboard = InlineKeyboardMarkup(menu)
else:
keyboard = ReplyKeyboardMarkup(menu, resize_keyboard=resize)
return keyboard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment