I’m creating a Telegram bot with Aiogram 3.7. The bot will naturally be used by multiple users and must support persistent data storage. I implement storage via Aiogram’s inbuilt FSM mechanism using a Redis storage:
from aiogram.fsm.storage.memory import SimpleEventIsolation
from aiogram.fsm.storage.redis import RedisStorage, DefaultKeyBuilder
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
# Redis URL
REDIS_URL = 'redis://redis:6379/2' # running in Docker, hence the "redis" endpoint
# FSM Redis storage with a default key builder to honor separate user / chat IDs
TG_STORAGE = RedisStorage.from_url(REDIS_URL,
key_builder=DefaultKeyBuilder(with_bot_id=True,
with_destiny=True))
# bot and dispatcher
mybot = Bot(token=TOKEN, parse_mode=ParseMode.HTML)
dp = Dispatcher(storage=TG_STORAGE, events_isolation=SimpleEventIsolation())
I also have a couple of states in a state group:
from aiogram.fsm.state import StatesGroup, State
class States(StatesGroup):
mem = State() # default state
register_state = State()
I update data inside message & callback handlers as follows:
async def handle_commands(message: Message, state: FSMContext, bot: Bot):
data = await state.get_data()
# do smth with data ...
await state.update_data(user={'user_id': message.from_user.id,
'chat_id': message.chat_id})
However, it seems that this approach doesn’t separate users, and the same context / data is used across multiple users. Where am I wrong?
PS. This SO reply suggests creating multiple contexts for users “on the fly”. But in that case, I don’t quite understand, where must I store the FSMContext
objects – create them dynamically in every message handler to handle potentially different users?