Задать вопрос
@fartunin6

Почему при срабатывание callback query handler вылазит ошибка?

Вылазит ошибка при срабатывание callback query handler (нажатие на inline button). Не могу понять почему. Прикрепляю код хендлерров и бд
from aiogram import types, Dispatcher
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.dispatcher.filters import Text

from create_bot import bot
from base import sqlite_db
from keyboards import kb_admin

ID = None


class Admin(StatesGroup):
    photo = State()
    name = State()
    desc = State()
    price = State()


async def cm_verify(message: types.Message):
    global ID
    ID = message.from_user.id
    await bot.send_message(message.from_user.id, "Success verify", reply_markup=kb_admin)


async def cm_start(message: types.Message):
    if message.from_user.id == ID:
        await Admin.photo.set()
        await message.reply('upload photo')


async def cm_delete(message: types.Message):
    if message.from_user.id == ID:
        print('delete handler')
        data = await sqlite_db.sql_scan()
        for ret in data:
            b_name = InlineKeyboardButton(f'Delete {ret[1]}', callback_data=f'del {ret[1]}')
            kb_delete = InlineKeyboardMarkup().add(b_name)

            await bot.send_photo(message.from_user.id, ret[0], f'{ret[1]}\nDescription: {ret[2]}\nPrice: {ret[-1]}')
            await bot.send_message(message.from_user.id, text='delete', reply_markup=kb_delete)


async def del_callback(query: types.CallbackQuery):
    print('delete callback')
    await sqlite_db.sql_delete(query.data.replace('del ', ''))
    await query.answer(text=f'{query.data.replace("del ", "")} is deleted', show_alert=True)


async def cm_cancel(message: types.Message, state: FSMContext):
    if message.from_user.id == ID:
        current_state = await state.get_state()
        if current_state is None:
            return
        await state.finish()
        await message.reply('canceled')


async def load_photo(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['photo'] = message.photo[0].file_id
    await Admin.next()
    await message.reply("type name of pizza")


async def load_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['name'] = message.text
    await Admin.next()
    await message.reply('type description')


async def load_desc(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['desc'] = message.text
    await Admin.next()
    await message.reply('enter price')


async def load_price(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['price'] = float(message.text)

    await sqlite_db.sql_add(state)
    await state.finish()


def handlers_admin(dp: Dispatcher):
    dp.register_message_handler(cm_verify, commands=['verify'], is_chat_admin=True)
    dp.register_message_handler(cm_start, commands=['upload'], state=None)
    dp.register_message_handler(cm_cancel, commands=['cancel'], state='*')  # * = any state

    dp.register_message_handler(cm_delete, commands=['delete'])
    dp.register_callback_query_handler(lambda x: x.data and x.data.startswith('del '))
    dp.register_message_handler(load_photo, content_types=['photo'], state=Admin.photo)
    dp.register_message_handler(load_name, state=Admin.name)
    dp.register_message_handler(load_desc, state=Admin.desc)
    dp.register_message_handler(load_price, state=Admin.price)


бд -
from create_bot import bot
import sqlite3 as sq


def sql_start():
    global base, cur
    base = sq.connect('pizza.db')
    cur = base.cursor()

    if base:
        print('Db is connected')

    base.execute('CREATE TABLE IF NOT EXISTS menu(img TEXT, name TEXT PRIMARY KEY, descr TEXT, price TEXT)')
    base.commit()


async def sql_add(state):
    async with state.proxy() as data:
        cur.execute('INSERT INTO menu VALUES (?, ?, ?, ?)', tuple(data.values()))
        base.commit()


async def sql_read(message):
     for ret in cur.execute('SELECT * FROM menu').fetchall():
         await bot.send_photo(message.from_user.id, ret[0], f'{ret[1]}\nDescription: {ret[2]}\nPrice: {ret[-1]}')


async def sql_scan():
    return cur.execute('SELECT * FROM menu').fetchall()


async def sql_delete(data):
    print('done')
    cur.execute('DELETE FROM menu WHERE name == ?', (data,))
    base.commit()


сама ошибка -
Task exception was never retrieved
future: exception=TypeError("object bool can't be used in 'await' expression")>
Traceback (most recent call last):
File "C:\Users\fartu\Desktop\PizzaBot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\fartu\Desktop\PizzaBot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\fartu\Desktop\PizzaBot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\fartu\Desktop\PizzaBot\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 283, in process_update
return await self.callback_query_handlers.notify(update.callback_query)
File "C:\Users\fartu\Desktop\PizzaBot\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
TypeError: object bool can't be used in 'await' expression
  • Вопрос задан
  • 904 просмотра
Подписаться 1 Простой 3 комментария
Решения вопроса 1
SoreMix
@SoreMix
yellow
В dp.register_callback_query_handler первым аргументом должна передаваться функция, на которую этот callback вешается, и затем уже остальные параметры. У вас нет функции
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы