Update database/filters_mdb.py
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383 unmodified lines4243444546474849505152532 unmodified lines5657585960616263646566676869702 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061072 unmodified lines1101111121131141151161171181 unmodified linefrom pyrogram import enumsfrom info import DATABASE_URL, DATABASE_NAMEimport logginglogger = logging.getLogger(__name__)logger.setLevel(logging.ERROR)myclient = pymongo.MongoClient(DATABASE_URL)mydb = myclient["ManualFilters"]async def add_filter(grp_id, text, reply_text, btn, file, alert):mycol = mydb[str(grp_id)]# mycol.create_index([('text', 'text')])data = {'text':str(text),'reply':str(reply_text),'btn':str(btn),'file':str(file),'alert':str(alert)}try:mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True)except:logger.exception('Some error occured!', exc_info=True)async def find_filter(group_id, name):mycol = mydb[str(group_id)]query = mycol.find( {"text":name})# query = mycol.find( { "$text": {"$search": name}})try:for file in query:reply_text = file['reply']3 unmodified linesalert = file['alert']except:alert = Nonereturn reply_text, btn, alert, fileidexcept:return None, None, None, Noneasync def get_filters(group_id):mycol = mydb[str(group_id)]texts = []2 unmodified linesfor file in query:text = file['text']texts.append(text)except:passreturn textsasync def delete_filter(message, text, group_id):mycol = mydb[str(group_id)]myquery = {'text':text }query = mycol.count_documents(myquery)if query == 1:mycol.delete_one(myquery)2 unmodified linesquote=True,parse_mode=enums.ParseMode.MARKDOWN)else:await message.reply_text("Couldn't find that filter!", quote=True)async def del_all(message, group_id, title):if str(group_id) not in mydb.list_collection_names():await message.edit_text(f"Nothing to remove in {title}!")returnmycol = mydb[str(group_id)]try:mycol.drop()await message.edit_text(f"All filters from {title} has been removed")except:await message.edit_text("Couldn't remove all filters from group!")returnasync def count_filters(group_id):mycol = mydb[str(group_id)]count = mycol.count()if count == 0:return Falseelse:return countasync def filter_stats():collections = mydb.list_collection_names()if "CONNECTION" in collections:2 unmodified linestotalcount = 0for collection in collections:mycol = mydb[collection]count = mycol.count()totalcount += counttotalcollections = len(collections)return totalcollections, totalcount1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142433 unmodified lines474849505152535455565758596061626364652 unmodified lines68697071727374757677787980818283848586872 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381392 unmodified lines1421431441451461471481491501511 unmodified linefrom pyrogram import enumsfrom info import DATABASE_URL, DATABASE_NAMEimport logginglogger = logging.getLogger(__name__)logger.setLevel(logging.INFO)myclient = pymongo.MongoClient(DATABASE_URL)mydb = myclient["ManualFilters"]async def add_filter(grp_id, text, reply_text, btn, file, alert):"""Add a filter to a specific group."""logger.info(f"Adding filter for group {grp_id} with text: {text}.")mycol = mydb[str(grp_id)]data = {'text': str(text),'reply': str(reply_text),'btn': str(btn),'file': str(file),'alert': str(alert)}try:mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True)logger.info(f"Filter added/updated for group {grp_id} with text: {text}.")except Exception as e:logger.exception(f"Error adding/updating filter for group {grp_id} with text: {text}: {e}")async def find_filter(group_id, name):"""Find a filter in a specific group."""logger.info(f"Finding filter for group {group_id} with text: {name}.")mycol = mydb[str(group_id)]query = mycol.find({"text": name})try:for file in query:reply_text = file['reply']3 unmodified linesalert = file['alert']except:alert = Nonelogger.info(f"Filter found for group {group_id} with text: {name}.")return reply_text, btn, alert, fileidlogger.info(f"No filter found for group {group_id} with text: {name}.")return None, None, None, Noneexcept Exception as e:logger.exception(f"Error finding filter for group {group_id} with text: {name}: {e}")return None, None, None, Noneasync def get_filters(group_id):"""Get all filters in a specific group."""logger.info(f"Getting all filters for group {group_id}.")mycol = mydb[str(group_id)]texts = []2 unmodified linesfor file in query:text = file['text']texts.append(text)logger.info(f"Retrieved {len(texts)} filters for group {group_id}.")return textsexcept Exception as e:logger.exception(f"Error getting filters for group {group_id}: {e}")return []async def delete_filter(message, text, group_id):"""Delete a specific filter from a group."""logger.info(f"Deleting filter for group {group_id} with text: {text}.")mycol = mydb[str(group_id)]myquery = {'text': text}query = mycol.count_documents(myquery)if query == 1:mycol.delete_one(myquery)2 unmodified linesquote=True,parse_mode=enums.ParseMode.MARKDOWN)logger.info(f"Filter deleted for group {group_id} with text: {text}.")else:await message.reply_text("Couldn't find that filter!", quote=True)logger.info(f"No filter found to delete for group {group_id} with text: {text}.")async def del_all(message, group_id, title):"""Delete all filters from a specific group."""logger.info(f"Deleting all filters for group {group_id} titled: {title}.")if str(group_id) not in mydb.list_collection_names():await message.edit_text(f"Nothing to remove in {title}!")logger.info(f"No filters to remove in group {group_id} titled: {title}.")returnmycol = mydb[str(group_id)]try:mycol.drop()await message.edit_text(f"All filters from {title} has been removed")logger.info(f"All filters removed from group {group_id} titled: {title}.")except Exception as e:logger.exception(f"Error removing all filters from group {group_id} titled: {title}: {e}")await message.edit_text("Couldn't remove all filters from group!")async def count_filters(group_id):"""Count the number of filters in a specific group."""logger.info(f"Counting filters for group {group_id}.")mycol = mydb[str(group_id)]count = mycol.count_documents({})if count == 0:logger.info(f"No filters found in group {group_id}.")return Falseelse:logger.info(f"Found {count} filters in group {group_id}.")return countasync def filter_stats():"""Get statistics about all filters."""logger.info("Getting filter statistics.")collections = mydb.list_collection_names()if "CONNECTION" in collections:2 unmodified linestotalcount = 0for collection in collections:mycol = mydb[collection]count = mycol.count_documents({})totalcount += countlogger.info(f"Collection {collection} has {count} filters.")totalcollections = len(collections)logger.info(f"Total collections: {totalcollections}, Total filters: {totalcount}.")return totalcollections, totalcount
database/filters_mdb.py+66-33