Python Telegram Pagination Bot

Recently, I faced the task of paginating a list of elements in a telegram bot. And she was surprised to find that for such a seemingly typical task, PyPi does not have a single library. Therefore, it was decided to correct this annoying omission and publish its implementation.


You can install the package from PyPi by executing in the console:


pip install python-telegram-bot-pagination

The InlineKeyboardPaginator class from the telegram_bot_pagination package makes it easy to get a set of inline buttons for navigating through the list pages. It is necessary to transfer to the constructor the number of pages into which the list of elements is divided, as well as the current page and pattern for generating data returned by pressing the bot button. After that, the paginator himself will form the necessary keyboard, which will be available through the markup property.


from telegram_bot_pagination import InlineKeyboardPaginator

paginator = InlineKeyboardPaginator(
        10,
        current_page=1,
        data_pattern='elements#{page}'
    )

Now paginator.markup will return a json object for the reply_markup field of the sendMessage Telegram Bot API method. In this case, five buttons will be formed. If the number of pages is five or less, then the buttons will be correspondingly. If there is only one page, then markup will be blank. If there are more than five pages, then the keyboard will contain 5 buttons for:


  • first page;
  • previous page;
  • current page;
  • next page;
  • last page.

For example, if there is an array of character_pages containing descriptions of Harry Potter characters to create a bot that displays a list of characters, we need a function that sends the current list page:


def send_character_page(message, page=1):
    paginator = InlineKeyboardPaginator(
        len(character_pages),
        current_page=page,
        data_pattern='character#{page}'
    )

    bot.send_message(
        message.chat.id,
        character_pages[page-1],
        reply_markup=paginator.markup,
        parse_mode='Markdown'
    )

And the button handler in the bot:



@bot.callback_query_handler(func=lambda call: call.data.split('#')[0]=='character')
def characters_page_callback(call):
    page = int(call.data.split('#')[1])
    bot.delete_message(
        call.message.chat.id,
        call.message.message_id
    )
    send_character_page(call.message, page)

* The example uses pyTelegramBotAPI to work with the bot.


The full code for the example can be found here .


The result, depending on the number of entries in the list, will look like this:





Thank you for the attention. I will be glad to any constructive criticism.


All Articles