Не работает aiogram 3.0,0b7(aiogram.exceptions.UnsupportedKeywordArgument)

Рейтинг: -2Ответов: 3Опубликовано: 24.02.2023

Переписывал код с aiogram второй версии на третью, но получил такую ошибку:

Traceback (most recent call last):
  File "C:\Users\fortu\Desktop\Программирование\TelegramBot\TelegramBot\Bot\b.py", line 14, in <module>
    async def cmd_start(message: types.Message):
  File "C:\Users\fortu\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\event\telegram.py", line 140, in wrapper
    self.register(callback, *filters, flags=flags, **kwargs)
  File "C:\Users\fortu\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\event\telegram.py", line 68, in register
    raise UnsupportedKeywordArgument(
aiogram.exceptions.UnsupportedKeywordArgument: Passing any additional keyword arguments to the registrar method is not supported.
This error may be caused when you are trying to register filters like in 2.x version of this framework, if it's true just look at correspoding documentation pages.
Please remove the {'commands'} arguments from this call.

(background on this error at: https://docs.aiogram.dev/en/dev-3.x/migration_2_to_3.html#filtering-events)

Затем взял простой код из обучающей статьи по aiogram 3, но на выходе была та же ошибка, вот этот код:

import asyncio
import logging
from aiogram import Bot, Dispatcher, types

# Включаем логирование, чтобы не пропустить важные сообщения
logging.basicConfig(level=logging.INFO)
# Объект бота
bot = Bot(token="<token>")
# Диспетчер
dp = Dispatcher()

# Хэндлер на команду /start
@dp.message(commands=["start"])
async def cmd_start(message: types.Message):
    await message.answer("Hello!")

# Запуск процесса поллинга новых апдейтов
async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

Ответы

▲ 1

В aiogram 3.0.0 теперь что бы определить хендлер события, в дисп или роутер нужно отправлять фильтр с привычными параметрами, а не сами эти параметры:

@dp.message(Command(commands=["start"]))
async def open_home(message: Message, state: FSMContext) -> None:
  print('open home')

В вашем случае надо использовать фильтр Command(commands=['']). Также можно использовать например фильтр Text(text='',startswith=''...)

▲ 0
@dp.message_handler(commands=["start"])
async def cmd_start(message: types.Message):
    await message.answer("Hello!")
▲ 0

Ответ был дан не мной, но поделиться, думаю стоит:

Note that this version has incompatibility with Python 3.8-3.9 in case when you create an instance of Dispatcher outside of the any coroutine. Sorry for the inconvenience, it will be fixed in the next version. This code will not work:

dp = Dispatcher()

def main(): ... dp.run_polling(...)

main() Copy to clipboard But if you change it like this it should works as well: router = Router()

async def main(): dp = Dispatcher() dp.include_router(router) ... dp.start_polling(...)

asyncio.run(main())

Обновиться до Python 3.11