Vlad_Lucky
Vlad_Lucky

Reputation: 21

Python, Aiogram: error with "await state.finish()"

Im making a telegram bot with aiogram API. Im starter in it so i have a problem with "await state.finish()" line. When i start my python file i get this error:

future: <Task finished name='Task-23' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=KeyError(1055580872)> Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates return await asyncio.gather(*tasks) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify response = await handler_obj.handler(*args, **partial_data) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update return await self.message_handlers.notify(update.message) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify response = await handler_obj.handler(*args, **partial_data) File "x-wingide-python-shell://115832752/2", line 37, in get_random_user File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\storage.py", line 322, in finish await self.storage.finish(chat=self.chat, user=self.user) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\dispatcher\storage.py", line 202, in finish await self.reset_state(chat=chat, user=user, with_data=True) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\contrib\fsm_storage\memory.py", line 78, in reset_state self._cleanup(chat, user) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\contrib\fsm_storage\memory.py", line 108, in _cleanup if self.data[chat][user] == {'state': None, 'data': {}, 'bucket': {}}: KeyError: 1055580872

My code is below:

import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext
import random

TOKEN = 'HERE IS TOKEN'

#
logging.basicConfig(level=logging.INFO)

storage = MemoryStorage()
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=storage)

class UsersClass(StatesGroup):
    users = State()

@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    await message.reply("Hi!\nI'm Bot!!!!")

@dp.message_handler(commands=['random'])
async def random_cmd(message: types.Message):
    # old style:
    # await bot.send_message(message.chat.id, message.text)
    # await message.answer(random.choice())
    await UsersClass.users.set()
    await message.reply("Write the names of all participants separated by a space")

@dp.message_handler(state=UsersClass.users)
async def get_random_user(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['users'] = message.text.split(' ')
        await bot.send_message(message.chat.id, f"Chosed: {random.choice(data['users'])}")
        await state.finish()

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

Please help if you can

Upvotes: 0

Views: 2159

Answers (1)

Vlad_Lucky
Vlad_Lucky

Reputation: 21

Okay, i found an answer. The proplem was in the File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\aiogram\contrib\fsm_storage\memory.py", line 108, in _cleanup. There is self.data doesnt have any keys. I solved this problem with additing some new lines to _cleanup function which looks like this:

def _cleanup(self, chat, user):
        if chat not in self.data.keys() or user not in self.data[chat].keys():
            return
        if self.data[chat][user] == {'state': None, 'data': {}, 'bucket': {}}:
            del self.data[chat][user]
        if not self.data[chat]:
            del self.data[chat]

Now i dont have any errors!

Upvotes: 2

Related Questions