Advertisement
Fsoky

Aiogram Bot With MongoDB | nobody

Apr 15th, 2021
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. from aiogram import Bot, Dispatcher, types, executor
  2. from aiogram.contrib.fsm_storage.memory import MemoryStorage
  3. from aiogram.dispatcher import FSMContext
  4. from aiogram.dispatcher.filters.state import State, StatesGroup
  5. from pymongo import MongoClient
  6.  
  7. bot = Bot(token="token")
  8. dp = Dispatcher(bot, storage=MemoryStorage())
  9. cluster = MongoClient("link to connect")
  10. collection = cluster.testdb.testcoll
  11.  
  12.  
  13. class Form(StatesGroup):
  14.     name = State()
  15.     passwd = State()
  16.  
  17.  
  18. @dp.message_handler(commands="reg")
  19. async def registration(message: types.Message):
  20.     await Form.name.set()
  21.     await message.answer("Please, enter your name")
  22.  
  23.  
  24. @dp.message_handler(state=Form.name)
  25. async def process_registration(message: types.Message, state: FSMContext):
  26.     async with state.proxy() as data:
  27.         data["name"] = message.text
  28.  
  29.     await Form.next()
  30.     await message.answer("Now, enter your password")
  31.  
  32.  
  33. @dp.message_handler(state=Form.passwd)
  34. async def process_password(message: types.Message, state: FSMContext):
  35.     async with state.proxy() as data:
  36.         data["passwd"] = message.text
  37.  
  38.         if collection.count_documents({"_id": message.from_user.id, "chat_id": message.chat.id}) == 0:
  39.             collection.insert_one(
  40.                 {
  41.                     "_id": message.from_user.id,
  42.                     "chat_id": message.chat.id,
  43.                     "name": data["name"],
  44.                     "password": data["passwd"]
  45.                 }
  46.             )
  47.  
  48.             await message.reply("You successfully registered to the system")
  49.         else:
  50.             await message.reply("You already registered in the system!")
  51.  
  52.  
  53.     await state.finish()
  54.  
  55.  
  56. @dp.message_handler(commands="data")
  57. async def get_data_of_db(message: types.Message):
  58.     data = collection.find_one({"_id": message.from_user.id, "chat_id": message.chat.id})
  59.     await message.reply(data)
  60.  
  61.  
  62. if __name__ == "__main__":
  63.     executor.start_polling(dp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement