Package: keyboa
KeyboaThis is a simple but flexible inline keyboard generator that works as an add-on to PyTelegramBotAPI package. Withkeyboayou can:quickly create buttons with complex callback,create keyboards directly from lists,easily combine multiple keyboards into one,many other cool things...📖 This guide applies to Keyboa version 3 and above.
If you are using Keyboa version 2 and below, please useThe guide for version 2.📌IMPORTANT NOTICE:Version 3 isn't compatible with version 2.
If decide to update from 2 to 3 version, be aware that you will need to adjust your code.InstallationKeyboa is compatible with Python 3.7 and higher. You can install this package with pip as usual:$pipinstallkeyboaAfter that, just import:fromkeyboaimportKeyboaQuick StartA minimal keyboardThe simplest telegram keyboard can be created like this:menu=["spam","eggs","ham"]keyboard=Keyboa(items=menu)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())A simple structured keyboardIf you need to create a keyboard with a predefined structure, do the following:menu=[["spam","eggs"],["ham","bread"],"spam"]keyboard=Keyboa(items=menu)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())That's a good start, but let's take a closer look at how it works and what additional features we can use.How it worksTheKeyboaclass provides two options for creating pyTelegramBotAPI compatible keyboards withInlineKeyboardMarkuptype: methodslice()and propertykeyboard.
Use theKeyboa classdescription below as a reference to understand the nuances and limitations of the module or see the following examples.Create keyboardsThe easiest way to create a keyboard is to init Keyboa object with a list of items and getkeyboardproperty.menu=["spam","eggs","ham"]keyboard=Keyboa(items=menu)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())By default, each item in the list becomes a separate row, but it's easy to change by combining the items into groups.menu=[["spam","eggs"],["ham","bread"],"spam"]keyboard=Keyboa(items=menu)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())Now you see that the keyboard buttons are arranged according to how we grouped them in the list.Note that the last "spam" has become a separate row, although we have not put it on a separate list.And of course you can create more complex structures, for example:menu=[["spam","eggs","ham"],["ham","eggs"],["spam",]["sausages","spam"],["eggs","spam","spam"]]keyboard=Keyboa(items=menu)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())Due to Telegram API limitation you can addup to 8 buttons per rowandup to 100 for the entire keyboard.Let's go deeper. Suppose you have a list of 24 items, and you would like to divide it into rows of 6 buttons each. Here is what you need to do:numbers=list(range(1,25))keyboard=Keyboa(items=numbers,items_in_row=6)bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard())💡 You can easily make 3, 4 or even 8 buttons in a row, changing theitems_in_rowparameter only.Now we will try to use more attributes to see how they will affect the result:keyboa=Keyboa(items=list(range(0,48)),alignment=True)keyboard=keyboa(slice(5,37))bot.send_message(chat_id=chat_id,text=text,reply_markup=keyboard)As you can see, this keyboard consists of a[5:37]slice. In addition, although we did not specify theitems_in_rowattribute, the function divided list into equal rows, because of enabledalignmentattribute.Create Buttons💡 There is usually no need to create separate buttons as they will be created automatically from their source data when the keyboard is created.
But if there is such a need, it can be done as follows.
ImportButtonclass (detailed description), create button object from various data types, such asstr,int,tuple,dictand callbuttonproperty to getInlineKeyboardButton:fromkeyboaimportButtonspam=Button(button_data="spam").buttonbutton fromstrorintspam=Button(button_data="spam").button{'text':'spam','callback_data':'spam'}button fromtuplespam=Button(button_data=("spam","eggs"),front_marker="ham_",back_marker="_spam").button{'text':'spam','callback_data':'ham_eggs_spam'}💡 Notice that in this example we also usedfront_markerandback_markerto add some data to button's callback_data.button fromdictwithout "text" keyspam=Button(button_data={"spam":"ham_eggs_spam"}).button{'text':'spam','callback_data':'ham_eggs_spam'}button fromdictwith "text" keyspam=Button(button_data={"text":"spam","url":"https://ya.ru/","callback_data":"eggs"}).button{"text":"spam","url":"https://ya.ru/","callback_data":"eggs"}Combine KeyboardsSometimes it is necessary to combine several keyboard blocks into the big one. The Keyboa class methodcombine()does just that!This method has only one input parameter -keyboards. It should be a sequence ofInlineKeyboardMarkupobjects. Also could be presented as a standaloneInlineKeyboardMarkup.Here is how it works:controls=[["⏹️","⏪️","⏏️","⏩️","▶️"],]tracks=list(range(1,13))keyboard_controls=Keyboa(items=controls).keyboardkeyboard_tracks=Keyboa(items=tracks,items_in_row=4).keyboardkeyboard=Keyboa.combine(keyboards=(keyboard_tracks,keyboard_controls))bot.send_message(chat_id=user_id,text=text_tracks,reply_markup=keyboard)As you see, we merged two keyboards into one.Complex callbacksA few words about how to create complex callbacks for buttons.Often it is necessary to read and pass through the callback options that the user has sequentially selected. For example, determining the address: city, street, house, apartment number.Suppose we offer the user several cities to choose from. Create a simple keyboard:kb_cities=Keyboa(items=["Moscow","London","Tokyo",],front_marker="&city=",back_marker="$")bot.send_message(chat_id=user_id,text="Select your city:",reply_markup=kb_cities())By doing so, we get the following inside the keyboard:{'inline_keyboard':[[{'text':'Moscow','callback_data':'&city=Moscow$'}],[{'text':'London','callback_data':'&city=London$'}],[{'text':'Tokyo','callback_data':'&city=Tokyo$'}]]}Suppose a user selectsLondon. We would like to remember this, and let him choose from several streets:received_callback=call.data# "&city=London$"streets=["Baker Street","Oxford Street","Abbey Road",]kb_streets=Keyboa(items=streets,front_marker="&street=",back_marker=received_callback# we added existing data to the end)bot.send_message(chat_id=user_id,text="Select your street:",reply_markup=kb_streets()){'inline_keyboard':[[{'text':'Baker Street','callback_data':'&street=Baker Street&city=London$'}],[{'text':'Oxford Street','callback_data':'&street=Oxford Street&city=London$'}],[{'text':'Abbey Road','callback_data':'&street=Abbey Road&city=London$'}]]}💡 Notice that we used afront_markerto specify the type of current items, and aback_markerto attach existing information.As you can see, the variant selected by the user in the previous step was also saved.
If the user selects a street, for example,Baker Street, we will receive thecall.dataas'&street=Baker Street&city=London$'. Of course we are able to parse it easily.Finally, let him to choose an apartment:received_callback=call.data# '&street=Baker Street&city=London$'apartments=["221a","221b","221c",]kb_apartments=Keyboa(items=apartments,front_marker="&apartments=",back_marker=received_callback# we added existing data to the end)bot.send_message(chat_id=user_id,text="Select your apartments:",reply_markup=kb_apartments()){'inline_keyboard':[[{'text':'221a','callback_data':'&apartments=221a&street=Baker Street&city=London$'},{'text':'221b','callback_data':'&apartments=221b&street=Baker Street&city=London$'},{'text':'221c','callback_data':'&apartments=221c&street=Baker Street&city=London$'}]]}And if the user selects button221b, we will assume that 🕵🏻‍♂️ Mr. Sherlock Holmes uses our bot too!DetailsKeyboa classAttributeTypeDescriptionitemsBlockItemsMandatory. List of items for the keyboard. The total number should not be more than 100 due to the Telegram Bot API limitation.items_in_rowIntegerOptional. The number of buttons in one keyboard row. Must befrom 1 to 8due to the Telegram Bot API limitation.The default value isNone, which means that by default the keyboard structure depends on the grouping ofitemselements.copy_text_to_callbackBooleanIfTrue, andbutton_datais astror anint, function will copy button text to callback data (and add other markers if they exist).The default value isTrue.front_markerCallbackDataMarkerOptional. Front part of callback data, which is common for all buttons.back_markerCallbackDataMarkerOptional. Back part of callback data, which is common for all buttons.alignmentBoolean or IterableIfTrue, will try to split all items intoequal rows in a range of 3 to 5.IfIterable(with anyintin the range from 1 to 8), will try to find a suitable divisor among them.Enabled attribute replaces the action ofitems_in_rowattribute, but if a suitable divisor cannot be found, function will use theitems_in_rowvalue if provided.The default value isNone.alignment_reverseBooleanIfTrue, will try to find the divisor starting from the end of theauto_alignmentvariable (if defined) or from the default range.Enabled attribute works only ifauto_alignmentis enabled.The default value isNone.# structureless sequence of InlineButtonData objectsFlatSequence=List[InlineButtonData]# structured sequence of InlineButtonData objectsStructuredSequence=List[Union[FlatSequence,InlineButtonData]]# unified type that allows you to use any available data types for the keyboardBlockItems=Union[StructuredSequence,InlineButtonData]Button classAttributeTypeDescriptionbutton_dataInlineButtonDataAn object from which the button will be created.See detailed explanation below.front_markerCallbackDataMarkerOptional. An object to be added to theleftside of callback.back_markerCallbackDataMarkerOptional. An object to be added to therightside of callback.copy_text_to_callbackBooleanIfTrue, andbutton_datais astror anint, function will copy button text to callback data (and add other markers if they exist).The default value isFalse.All acceptable types combined intoInlineButtonDatatype:InlineButtonData=Union[str,int,tuple,dict,InlineKeyboardButton]Also there is aCallbackDataMarkertype for callback data:CallbackDataMarker=Optional[Union[str,int]]Forbutton_dataobject --If it is astror anint, it will be used for text (and callback, ifcopy_text_to_callbackis not disabled).If it is atuple, the zero element [0] will be the text, and the first [1] will be the callback.If it is adict, there are two options:if there isno "text" keyin dictionary and only one key exists, the key will be the text, and the value will be the callback.In this case no verification of the dictionary's contents is performed!if the"text" key exists, function passes the whole dictionary toInlineKeyboardButton, where dictionary's keys represent object's parameters and dictionary's values represent parameters' values accordingly.
In all other cases theValueErrorwill be raised.