from functools import cached_property import pymongo import settings class Mongo: def __init__(self): url = f"mongodb://{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@{settings.MONGO_HOST}:27017/" self.client = pymongo.MongoClient(url) self.database = self.client.get_database("pizda-bot") self.chats_collection.create_index([ ("chat_id", 1) ]) self.counter_collection.create_index([ ("chat_id", 1), ("username", 1), ]) def __getitem__(self, item): return self.database.get_collection(item) @cached_property def chats_collection(self): return self["chats"] @cached_property def counter_collection(self): return self["counter"] def inc(self, username, chat_id): if self.counter_collection.find_one({"chat_id": chat_id, "username": username}): self.counter_collection.update_one({"chat_id": chat_id, "username": username}, {"$inc": {"count": 1}}) else: self.counter_collection.insert_one({"chat_id": chat_id, "username": username, "count": 1}) def inc_points(self, username, chat_id): if self.counter_collection.find_one({"chat_id": chat_id, "username": username}): self.counter_collection.update_one({"chat_id": chat_id, "username": username}, {"$inc": {"points": 1}}) else: self.counter_collection.insert_one({"chat_id": chat_id, "username": username, "points": 1}) mongo = Mongo()