Skip to content

Instantly share code, notes, and snippets.

@Birdi7
Last active March 21, 2024 17:48
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Birdi7/d5249ae88015a1384b7200dcb51e85ce to your computer and use it in GitHub Desktop.
Save Birdi7/d5249ae88015a1384b7200dcb51e85ce to your computer and use it in GitHub Desktop.
A simple example of usage of callback data factory from aiogram
"""
This is a simple example of usage of CallbackData factory
For more comprehensive example see callback_data_factory.py
"""
import asyncio
import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.utils.callback_data import CallbackData
from aiogram.utils.exceptions import MessageNotModified
logging.basicConfig(level=logging.INFO)
API_TOKEN = 'BOT_TOKEN_HERE'
loop = asyncio.get_event_loop()
bot = Bot(token=API_TOKEN, loop=loop, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
dp.middleware.setup(LoggingMiddleware())
vote_cb = CallbackData('vote', 'action', 'amount') # post:<action>:<amount>
def get_keyboard(amount):
return types.InlineKeyboardMarkup().row(
types.InlineKeyboardButton('👍', callback_data=vote_cb.new(action='up', amount=amount)),
types.InlineKeyboardButton('👎', callback_data=vote_cb.new(action='down', amount=amount)))
@dp.message_handler(commands='start')
async def cmd_start(message: types.Message):
await message.reply('Vote! Now you have 0 votes.', reply_markup=get_keyboard(0))
@dp.callback_query_handler(vote_cb.filter(action='up'))
async def vote_up_cb_handler(query: types.CallbackQuery, callback_data: dict):
logging.info(callback_data)
amount = int(callback_data['amount'])
amount += 1
await bot.edit_message_text(f'You voted up! Now you have {amount} votes.',
query.from_user.id,
query.message.message_id,
reply_markup=get_keyboard(amount))
@dp.callback_query_handler(vote_cb.filter(action='down'))
async def vote_down_cb_handler(query: types.CallbackQuery, callback_data: dict):
amount = int(callback_data['amount'])
amount -= 1
await bot.edit_message_text(f'You voted down! Now you have {amount} votes.',
query.from_user.id,
query.message.message_id,
reply_markup=get_keyboard(amount))
@dp.errors_handler(exception=MessageNotModified) # for skipping this exception
async def message_not_modified_handler(update, error):
return True
if __name__ == '__main__':
executor.start_polling(dp, loop=loop, skip_updates=True)
@Fsoky
Copy link

Fsoky commented Sep 12, 2023

thx, i made simple pagination with this example

@Munchen777
Copy link

thx, i made simple pagination with this example

Hello! Where I can see an example of pagination using Callback Data?

@Fsoky
Copy link

Fsoky commented Mar 21, 2024

thx, i made simple pagination with this example

Hello! Where I can see an example of pagination using Callback Data?

class Pagination(CallbackData, prefix="pag"):
    action: str
    page: int


def paginator(page: int=0):
    builder = InlineKeyboardBuilder()
    builder.row(
        InlineKeyboardButton(text="⬅", callback_data=Pagination(action="prev", page=page).pack()),
        InlineKeyboardButton(text="➡", callback_data=Pagination(action="next", page=page).pack()),
        width=2
    )
    return builder.as_markup()
    
@dp.callback_query(keyboards.Pagination.filter(F.action.in_(["prev", "next"])))
async def pagination_handler(call: CallbackQuery, callback_data: keyboards.Pagination):
    page_num = int(callback_data.page)
    page = page_num - 1 if page_num > 0 else 0

    if callback_data.action == "next":
        page = page_num + 1 if page_num < (len(smiles) - 1) else page_num

    with suppress(TelegramBadRequest):
        await call.message.edit_text(
            f"{smiles[page][0]} <b>{smiles[page][1]}</b>",
            reply_markup=keyboards.paginator(page)
        )
    await call.answer()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment