from typing import Union from convopyro import listen_message from pykeyboard import ReplyButton, ReplyKeyboard from pyrogram.types import ForceReply, Message, ReplyKeyboardRemove from classes.location import Location from classes.pyroclient import PyroClient from modules.database import col_locations async def search_name(app: PyroClient, message: Message) -> Union[Location, None]: location: Union[Location, None] = None await message.reply_text( "Please, send me a location name. It should be the name used in your local authorities' garbage collection schedule. This usually is a name of the district or even the town itself.", reply_markup=ForceReply(placeholder="Location name"), ) while location is None: answer = await listen_message(app, message.chat.id, 300) if answer is None or answer.text == "/cancel": await message.reply_text("Cancelled.", reply_markup=ReplyKeyboardRemove()) return if answer.text is None: await message.reply_text( "Please, send the name of the location as a text. You can also abort this operation with /cancel command.", reply_markup=ForceReply(placeholder="Location name"), ) continue query = {"$text": {"$search": answer.text}} locations = await col_locations.find(query).limit(6).to_list() if len(locations) == 0: await message.reply_text( "Could not find any locations by this name. Try rephrasing it or make sure you use the same location language and name itself as it in written by your local authorities in garbage collection schedule.\n\nYou can also abort this operation with /cancel command.", reply_markup=ForceReply(placeholder="Location name"), ) continue keyboard = ReplyKeyboard(resize_keyboard=True, row_width=2) keyboard.add(*[ReplyButton(db_record["name"]) for db_record in locations]) await message.reply_text( "Select the location using the keyboard", reply_markup=keyboard ) while True: answer = await listen_message(app, message.chat.id, 300) if answer is None or answer.text == "/cancel": await message.reply_text( "Cancelled.", reply_markup=ReplyKeyboardRemove() ) return for db_record in locations: if answer.text == db_record["name"]: location = Location(**db_record) if answer.text is None or location is None: await answer.reply_text( "Please, select a valid location using keyboard provided. Use /cancel if you want to cancel this operation.", ) continue break return location