Не работают обработчики второй inline клавиатуры , никаких ошибок не выдаёт ,просто при нажатии ничего не происходит

Рейтинг: 0Ответов: 1Опубликовано: 20.08.2023

Вот мой фаил keyboards.py

from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton

    
    
    
def get_kb() -> InlineKeyboardMarkup:
    kb = InlineKeyboardMarkup(resize_keyboard=True)
    kb1 = InlineKeyboardButton('IT проблема', callback_data='btn_it')
    kb2 = InlineKeyboardButton('Оборудование', callback_data='btn_oborudovaniye')
    kb.add(kb1, kb2)
    return kb
    
    
def photo_or_video_kb() -> InlineKeyboardMarkup:
    kbch = InlineKeyboardMarkup(resize_keyboard=True)
    kbch1 = InlineKeyboardButton('Фото', callback_data='but_photo')
    kbch2 = InlineKeyboardButton('Видео', callback_data='but_video')
    kbch3 = InlineKeyboardButton('Ни то ни другое', callback_data='but_nothing')
    kbch.add(kbch1, kbch2)
    kbch.add(kbch3)
    return kbch

А вот сам основной фаил main.py

from aiogram import types, executor, Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.types import callback_query

from keyboard import get_kb, photo_or_video_kb
from db import Database
from config import TOKEN_API
from messages import *
from states import ProfileStatesGroup

storage = MemoryStorage()
bot = Bot(TOKEN_API)
dp = Dispatcher(bot,
                storage=storage)

db = Database('Database.db')


@dp.message_handler(commands=['start'], state='*')
async def cmd_start(message: types.Message, state: FSMContext) -> None:
    await bot.send_message(chat_id=message.from_user.id,
                           text=start_msg,
                           reply_markup=get_kb())
    if state is None:
        return
    await state.finish()


@dp.message_handler(lambda message: not message.text, state=ProfileStatesGroup.it_problem_info)
async def check_info(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_text)


@dp.message_handler(content_types=['text'], state=ProfileStatesGroup.it_problem_info)
async def load_it_info(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        data['it_description'] = message.text
    await bot.send_message(chat_id=message.from_user.id,
                           text=what_you_want_to_send,
                           reply_markup=photo_or_video_kb())


@dp.message_handler(lambda message: not message.photo, state=ProfileStatesGroup.it_problem_photo)
async def check_photo(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_photo)


@dp.message_handler(content_types=['photo'], state=ProfileStatesGroup.it_problem_photo)
async def load_photo(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        desc = data['it_description']
        num = db.select_number()
        data['it_photo'] = message.photo[0].file_id
        await bot.send_photo(chat_id="94766813",
                             photo=data['it_photo'],
                             caption=f"Номер заявки: {num}\n\n{desc}")
        await bot.send_photo(chat_id="-941467752",
                             photo=data['it_photo'],
                             caption=f"Номер заявки: {num}\n\n{desc}")
        db.numberplusone()
    await bot.send_message(chat_id=message.from_user.id, text=success)
    await bot.send_message(chat_id=message.from_user.id, text=number)
    await state.finish()


@dp.message_handler(lambda message: not message.video, state=ProfileStatesGroup.it_problem_video)
async def check_photo(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_video)


@dp.message_handler(content_types=['video'], state=ProfileStatesGroup.it_problem_video)
async def load_photo(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        desc = data['it_description']
        num = db.select_number()
        data['it_video'] = message.video.file_id
        await bot.send_video(chat_id="94766813",
                             video=data['it_video'],
                             caption=f"Номер заявки: {num}\n\n{desc}")
        await bot.send_video(chat_id="-941467752",
                             video=data['it_video'],
                             caption=f"Номер заявки: {num}\n\n{desc}")
        db.numberplusone()
    await bot.send_message(chat_id=message.from_user.id, text=success)
    await bot.send_message(chat_id=message.from_user.id, text=number)
    await state.finish()


@dp.message_handler(content_types=['text'], state=ProfileStatesGroup.it_problem_nothing)
async def load_photo(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        desc = data['it_description']
        num = db.select_number()
        await bot.send_message(chat_id="94766813",
                               text=f"Номер заявки:{num} \n\nСуть проблемы: {desc}")
        await bot.send_message(chat_id="-941467752",
                               text=f"Номер заявки:{num} \n\nСуть проблемы: {desc}")
        db.numberplusone()
    await bot.send_message(chat_id=message.from_user.id, text=success)
    await bot.send_message(chat_id=message.from_user.id, text=number)
    await state.finish()


@dp.message_handler(lambda message: not message.text, state=ProfileStatesGroup.oborudovaniye_number)
async def check_oborudovaniye_table_number(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_text)


@dp.message_handler(content_types=['text'], state=ProfileStatesGroup.oborudovaniye_number)
async def oborudovaniye_table_number(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        data['onumber'] = message.text
    await bot.send_message(chat_id=message.from_user.id, text=oborudovaniye_problem_description)
    await ProfileStatesGroup.oborudovaniye_problem_info.set()


@dp.message_handler(lambda message: not message.text, state=ProfileStatesGroup.oborudovaniye_problem_info)
async def check_oborudovaniye_info(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_text)


@dp.message_handler(content_types=['text'], state=ProfileStatesGroup.oborudovaniye_problem_info)
async def oborudovaniye_info(message: types.Message, state: FSMContext) -> None:
    async with state.proxy() as data:
        data['oinfo'] = message.text
        num = db.select_number()
        await bot.send_message(chat_id="94766813",
                               text=f"Номер заявки:{num} \n\n1.Номер места: {data['onumber']}\n2.Суть проблемы: {data['oinfo']}")
        await bot.send_message(chat_id="-941467752",
                               text=f"Номер заявки:{num} \n\n1.Номер места: {data['onumber']}\n2.Суть проблемы: {data['oinfo']}")
        db.numberplusone()
    await bot.send_message(chat_id=message.from_user.id, text=success)
    await bot.send_message(chat_id=message.from_user.id, text=number)
    await state.finish()


@dp.callback_query_handler()
async def ikb_cb_handler(callback_query: types.CallbackQuery):
    if callback_query.data == 'btn_it':
        await ProfileStatesGroup.it_problem_info.set()
        await bot.send_message(callback_query.from_user.id, text=it_msg)
        await callback_query.message.delete()
    if callback_query.data == 'btn_oborudovaniye':
        await ProfileStatesGroup.oborudovaniye_number.set()
        await bot.send_message(callback_query.from_user.id, text=oborudovaniye_table_number_msg)
        await callback_query.message.delete()

**#####Вот эти последние callback_query_handler не срабатывают** 

@dp.callback_query_handler(lambda c: c.data == 'but_photo')
async def process_callback_button2(callback_query: types.CallbackQuery):
    await ProfileStatesGroup.it_problem_photo.set()
    await bot.send_message(callback_query.from_user.id,
                           text=photo)
    await callback_query.message.delete()


@dp.callback_query_handler(lambda c: c.data == 'but_video')
async def process_callback_button2(callback_query: types.CallbackQuery):
    await ProfileStatesGroup.it_problem_video.set()
    await bot.send_message(callback_query.from_user.id,
                           text=video)
    await callback_query.message.delete()


@dp.callback_query_handler(lambda c: c.data == 'but_nothing')
async def process_callback_button2(callback_query: types.CallbackQuery):
    await ProfileStatesGroup.it_problem_nothing.set()
    await callback_query.message.delete()

**#####Вот эти последние callback_query_handler не срабатывают**

if __name__ == '__main__':
    executor.start_polling(dp,
                           skip_updates=True)

Ответы

▲ 0

Проблема, возможно, может быть связана с тем, что вы используете InlineKeyboardMarkup вместо ReplyKeyboardMarkup для создания второй клавиатуры с кнопками "Фото", "Видео" и "Ни то ни другое".

InlineKeyboardMarkup используется для создания встроенных клавиатур, которые отображаются в виде кнопок под сообщением, и требуют взаимодействия через нажатие. Это может быть причиной, по которой кнопки не срабатывают в данном контексте.

Для создания обычной клавиатуры с кнопками для выбора "Фото", "Видео" и "Ни то ни другое" вам следует использовать ReplyKeyboardMarkup вместо InlineKeyboardMarkup.

Пример ваших функций photo_or_video_kb() и ikb_cb_handler() с использованием ReplyKeyboardMarkup:

from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

def photo_or_video_kb() -> ReplyKeyboardMarkup:
    kbch = ReplyKeyboardMarkup(resize_keyboard=True)
    kbch1 = KeyboardButton('Фото')
    kbch2 = KeyboardButton('Видео')
    kbch3 = KeyboardButton('Ни то ни другое')
    kbch.row(kbch1, kbch2)
    kbch.row(kbch3)
    return kbch
@dp.message_handler(commands=['start'], state='*')
async def cmd_start(message: types.Message, state: FSMContext) -> None:
    await bot.send_message(chat_id=message.from_user.id,
                           text=start_msg,
                           reply_markup=get_kb())
    if state is None:
        return
    await state.finish()

...

@dp.message_handler(lambda message: not message.text, state=ProfileStatesGroup.it_problem_info)
async def check_info(message: types.Message):
    await bot.send_message(chat_id=message.from_user.id,
                           text=this_is_not_text,
                           reply_markup=photo_or_video_kb())

Примечание: Важно учитывать, что использование ReplyKeyboardMarkup с опциями resize_keyboard=True и слишком много кнопок может занимать много места на экране и ухудшать пользовательский опыт. Поэтому стоит рассмотреть варианты оптимизации дизайна клавиатуры для улучшения пользовательского интерфейса.