Fixed _set() and _remove() methods

This commit is contained in:
2025-04-22 23:28:58 +02:00
parent 5bf1537968
commit 004b5336d8
4 changed files with 30 additions and 34 deletions

View File

@@ -77,44 +77,49 @@ class PycordUser:
"id": self.id,
}
async def _set(self, key: str, value: Any, cache: Optional[Cache] = None) -> None:
async def _set(self, cache: Optional[Cache] = None, **kwargs) -> None:
"""Set attribute data and save it into the database.
Args:
key (str): Attribute to change
value (Any): Value to set
cache (:obj:`Cache`, optional): Cache engine to write the update into
**kwargs (str): Mapping of attribute names and respective values to be set
"""
if not hasattr(self, key):
raise AttributeError()
for key, value in kwargs.items():
if not hasattr(self, key):
raise AttributeError()
setattr(self, key, value)
setattr(self, key, value)
await self.__collection__.update_one({"_id": self._id}, {"$set": {key: value}}, upsert=True)
await self.__collection__.update_one({"_id": self._id}, {"$set": kwargs}, upsert=True)
self._update_cache(cache)
logger.info("Set attribute '%s' of user %s to '%s'", key, self.id, value)
logger.info("Set attributes of user %s to %s", self.id, kwargs)
async def _remove(self, key: str, cache: Optional[Cache] = None) -> None:
async def _remove(self, *args: str, cache: Optional[Cache] = None) -> None:
"""Remove attribute data and save it into the database.
Args:
key (str): Attribute to remove
cache (:obj:`Cache`, optional): Cache engine to write the update into
*args (str): List of attributes to remove
"""
if not hasattr(self, key):
raise AttributeError()
attributes: Dict[str, Any] = {}
default_value: Any = PycordUser.get_default_value(key)
for key in args:
if not hasattr(self, key):
raise AttributeError()
setattr(self, key, default_value)
default_value: Any = self.get_default_value(key)
await self.__collection__.update_one({"_id": self._id}, {"$set": {key: default_value}}, upsert=True)
setattr(self, key, default_value)
attributes[key] = default_value
await self.__collection__.update_one({"_id": self._id}, {"$set": attributes}, upsert=True)
self._update_cache(cache)
logger.info("Removed attribute '%s' of user %s", key, self.id)
logger.info("Reset attributes %s of user %s to default values", args, self.id)
def _get_cache_key(self) -> str:
return f"{self.__short_name__}_{self.id}"