• Home
  • Pyrogram
  • Мастерство работы с кнопками в Telegram: создание и обработка инлайн кнопок с Pyrogram

Мастерство работы с кнопками в Telegram: создание и обработка инлайн кнопок с Pyrogram

Image

В этом уроке по Pyrogram мы разберёмся, как создавать и отправлять пользователю инлайн-кнопки, а также научимся обрабатывать нажатия на них. Вы узнаете, какие возможности предоставляет Pyrogram для создания кнопок и как использовать их в вашем телеграм-боте. Не пропустите этот урок, если хотите научиться создавать более удобный и интуитивно понятный интерфейс для ваших пользователей.

from pyrogram import Client, idle, filters
from pyrogram.enums import ParseMode
from pyrogram.handlers import MessageHandler, CallbackQueryHandler
from pyrogram.types import Message, BotCommand, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery

api_id = 12345678
api_hash = 'abcdefghijklmnopqrstuvwxyz'

bot_token = '9876543210:abcdefghijklm'

client = Client(name='me_client_bot', api_id=api_id, api_hash=api_hash, parse_mode=ParseMode.HTML)


inline_keyboard = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(
            text='Basic button',
            callback_data='basic_button'
        ),
        InlineKeyboardButton(
            text='Link',
            url='https://nztcoder.com'
        ),
        InlineKeyboardButton(
            text='Added button',
            callback_data='add_button'
        )
    ],
    [
        InlineKeyboardButton(
            text='Profile',
            user_id=5528605206
        )
    ]
])


def command_start(client: Client, message: Message):
    message.reply('Hi! You entered start command.', reply_markup=inline_keyboard)


def command_basic(client: Client, call: CallbackQuery):
    client.answer_callback_query(call.id)
    call.message.reply(f'You press button with callback_data {call.data}')


def command_add(client: Client, call: CallbackQuery):
    client.answer_callback_query(call.id)
    call.message.reply(f'You press button (Added_button) with callback_data {call.data}')

def call_data(data):
    async def filter_data(self, __, call: CallbackQuery):
        # return self.data == call.data
        return self.data in call.data

    return filters.create(filter_data, data=data)

client.add_handler(CallbackQueryHandler(command_basic, call_data('basic_button')))
client.add_handler(CallbackQueryHandler(command_add, call_data('add_button')))
# client.add_handler(CallbackQueryHandler(command_basic))
client.add_handler(MessageHandler(command_start, filters.command(commands='start')))

bot_commands = [
    BotCommand(
        command='start',
        description='Get started'
    ),
    BotCommand(
        command='run',
        description='Launch'
    ),
    BotCommand(
        command='go',
        description='Go to'
    )
]

client.start()
client.set_bot_commands(bot_commands)
idle()
client.stop()
Image