Working on #14

This commit is contained in:
kku 2024-12-16 16:25:35 +01:00
parent 41112018da
commit 454ce2b6fb
7 changed files with 62 additions and 50 deletions

View File

@ -5,7 +5,7 @@ import discord
import discord.member import discord.member
from libbot import config_get from libbot import config_get
from modules.database import col_users, col_warnings from modules.database import col_warnings, sync_col_users, sync_col_warnings, col_users
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -40,7 +40,7 @@ class HoloUser:
else: else:
self.id = user self.id = user
jav_user = col_users.find_one({"user": self.id}) jav_user = sync_col_users.find_one({"user": self.id})
if jav_user is None: if jav_user is None:
raise UserNotFoundError(user=user, user_id=self.id) raise UserNotFoundError(user=user, user_id=self.id)
@ -57,29 +57,29 @@ class HoloUser:
### Returns: ### Returns:
* `int`: Number of warnings * `int`: Number of warnings
""" """
warns = col_warnings.find_one({"user": self.id}) warns = sync_col_warnings.find_one({"user": self.id})
return 0 if warns is None else warns["warns"] return 0 if warns is None else warns["warns"]
def warn(self, count=1, reason: str = "Not provided") -> None: async def warn(self, count=1, reason: str = "Not provided") -> None:
"""Warn and add count to warns number """Warn and add count to warns number
### Args: ### Args:
* `count` (int, optional): Count of warnings to be added. Defaults to 1. * `count` (int, optional): Count of warnings to be added. Defaults to 1.
""" """
warns = col_warnings.find_one({"user": self.id}) warns = await col_warnings.find_one({"user": self.id})
if warns is not None: if warns is not None:
col_warnings.update_one( await col_warnings.update_one(
filter={"_id": self.db_id}, {"_id": self.db_id},
update={"$set": {"warns": warns["warns"] + count}}, {"$set": {"warns": warns["warns"] + count}},
) )
else: else:
col_warnings.insert_one(document={"user": self.id, "warns": count}) await col_warnings.insert_one(document={"user": self.id, "warns": count})
logger.info(f"User {self.id} was warned {count} times due to: {reason}") logger.info(f"User {self.id} was warned {count} times due to: {reason}")
def set(self, key: str, value: Any) -> None: async def set(self, key: str, value: Any) -> None:
"""Set attribute data and save it into database """Set attribute data and save it into database
### Args: ### Args:
@ -90,14 +90,16 @@ class HoloUser:
raise AttributeError() raise AttributeError()
setattr(self, key, value) setattr(self, key, value)
col_users.update_one(
filter={"_id": self.db_id}, update={"$set": {key: value}}, upsert=True await col_users.update_one(
{"_id": self.db_id}, {"$set": {key: value}}, upsert=True
) )
logger.info(f"Set attribute {key} of user {self.id} to {value}") logger.info(f"Set attribute {key} of user {self.id} to {value}")
@staticmethod
async def is_moderator( async def is_moderator(
self, member: Union[discord.User, discord.Member, discord.member.Member] member: Union[discord.User, discord.Member, discord.member.Member]
) -> bool: ) -> bool:
"""Check if user is moderator or council member """Check if user is moderator or council member
@ -119,8 +121,9 @@ class HoloUser:
return False return False
@staticmethod
async def is_council( async def is_council(
self, member: Union[discord.User, discord.Member, discord.member.Member] member: Union[discord.User, discord.Member, discord.member.Member]
) -> bool: ) -> bool:
"""Check if user is a member of council """Check if user is a member of council

View File

@ -46,7 +46,7 @@ class Analytics(commands.Cog):
} }
) )
col_analytics.insert_one( await col_analytics.insert_one(
{ {
"user": message.author.id, "user": message.author.id,
"channel": message.channel.id, "channel": message.channel.id,

View File

@ -19,7 +19,7 @@ class CustomChannels(commands.Cog):
@commands.Cog.listener() @commands.Cog.listener()
async def on_guild_channel_delete(self, channel: GuildChannel): async def on_guild_channel_delete(self, channel: GuildChannel):
col_users.find_one_and_update( await col_users.find_one_and_update(
{"customchannel": channel.id}, {"$set": {"customchannel": None}} {"customchannel": channel.id}, {"$set": {"customchannel": None}}
) )
@ -77,7 +77,7 @@ class CustomChannels(commands.Cog):
manage_channels=True, manage_channels=True,
) )
holo_user_ctx.set("customchannel", created_channel.id) await holo_user_ctx.set("customchannel", created_channel.id)
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@ -178,7 +178,7 @@ class CustomChannels(commands.Cog):
color=Color.fail, color=Color.fail,
) )
) )
holo_user_ctx.set("customchannel", None) await holo_user_ctx.set("customchannel", None)
return return
# Return if the confirmation is missing # Return if the confirmation is missing
@ -194,7 +194,7 @@ class CustomChannels(commands.Cog):
await custom_channel.delete(reason="Власник запросив видалення") await custom_channel.delete(reason="Власник запросив видалення")
holo_user_ctx.set("customchannel", None) await holo_user_ctx.set("customchannel", None)
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(

View File

@ -40,7 +40,7 @@ class Data(commands.Cog):
# Return if the user is not an owner and not in the council # Return if the user is not an owner and not in the council
if (ctx.user.id not in self.client.owner_ids) and not ( if (ctx.user.id not in self.client.owner_ids) and not (
await holo_user.is_council(ctx.author) await HoloUser.is_council(ctx.author)
): ):
logging.info( logging.info(
"User %s tried to use /export but permission denied", "User %s tried to use /export but permission denied",
@ -108,11 +108,9 @@ class Data(commands.Cog):
async def data_migrate_cmd(self, ctx: ApplicationContext, kind: str): async def data_migrate_cmd(self, ctx: ApplicationContext, kind: str):
await ctx.defer() await ctx.defer()
holo_user = HoloUser(ctx.author)
# Return if the user is not an owner and not in the council # Return if the user is not an owner and not in the council
if (ctx.user.id not in self.client.owner_ids) and not ( if (ctx.user.id not in self.client.owner_ids) and not (
await holo_user.is_council(ctx.author) await HoloUser.is_council(ctx.author)
): ):
logging.info( logging.info(
"User %s tried to use /migrate but permission denied", "User %s tried to use /migrate but permission denied",
@ -156,7 +154,7 @@ class Data(commands.Cog):
if member.bot: if member.bot:
continue continue
if col_users.find_one({"user": member.id}) is None: if (await col_users.find_one({"user": member.id})) is None:
user = {} user = {}
defaults = await config_get("user", "defaults") defaults = await config_get("user", "defaults")
@ -165,7 +163,7 @@ class Data(commands.Cog):
for key in defaults: for key in defaults:
user[key] = defaults[key] user[key] = defaults[key]
col_users.insert_one(document=user) await col_users.insert_one(document=user)
logging.info( logging.info(
"Added DB record for user %s during migration", member.id "Added DB record for user %s during migration", member.id

View File

@ -18,7 +18,7 @@ class Logger(commands.Cog):
and (message.author.bot is False) and (message.author.bot is False)
and (message.author.system is False) and (message.author.system is False)
): ):
if col_users.find_one({"user": message.author.id}) is None: if (await col_users.find_one({"user": message.author.id})) is None:
user = {} user = {}
defaults = await config_get("user", "defaults") defaults = await config_get("user", "defaults")
@ -27,7 +27,7 @@ class Logger(commands.Cog):
for key in defaults: for key in defaults:
user[key] = defaults[key] user[key] = defaults[key]
col_users.insert_one(document=user) await col_users.insert_one(document=user)
@commands.Cog.listener() @commands.Cog.listener()
async def on_member_join(self, member: Member): async def on_member_join(self, member: Member):
@ -51,7 +51,7 @@ class Logger(commands.Cog):
) )
) )
if col_users.find_one({"user": member.id}) is None: if (await col_users.find_one({"user": member.id})) is None:
user = {} user = {}
defaults = await config_get("user", "defaults") defaults = await config_get("user", "defaults")
@ -60,7 +60,7 @@ class Logger(commands.Cog):
for key in defaults: for key in defaults:
user[key] = defaults[key] user[key] = defaults[key]
col_users.insert_one(document=user) await col_users.insert_one(document=user)
def setup(client: PycordBot): def setup(client: PycordBot):

View File

@ -1,12 +1,19 @@
from typing import Dict, Any
from async_pymongo import AsyncClient, AsyncCollection, AsyncDatabase
from libbot.sync import config_get as sync_config_get
from pymongo import MongoClient from pymongo import MongoClient
from ujson import loads from pymongo.synchronous.collection import Collection
from pymongo.synchronous.database import Database
with open("config.json", "r", encoding="utf-8") as f: db_config: Dict[str, Any] = sync_config_get("database")
db_config = loads(f.read())["database"]
f.close()
db_client = MongoClient( con_string: str = (
"mongodb://{0}:{1}@{2}:{3}/{4}".format( "mongodb://{0}:{1}/{2}".format(
db_config["host"], db_config["port"], db_config["name"]
)
if db_config["user"] is None or db_config["password"] is None
else "mongodb://{0}:{1}@{2}:{3}/{4}".format(
db_config["user"], db_config["user"],
db_config["password"], db_config["password"],
db_config["host"], db_config["host"],
@ -14,14 +21,20 @@ db_client = MongoClient(
db_config["name"], db_config["name"],
) )
) )
db = db_client.get_database(name=db_config["name"])
collections = db.list_collection_names() db_client: AsyncClient = AsyncClient(con_string)
db_client_sync: MongoClient = MongoClient(con_string)
for collection in ["users", "warnings", "scheduler", "analytics"]: # Async declarations per default
if not collection in collections: db: AsyncDatabase = db_client.get_database(name=db_config["name"])
db.create_collection(collection)
col_users = db.get_collection("users") col_users: AsyncCollection = db.get_collection("users")
col_warnings = db.get_collection("warnings") col_warnings: AsyncCollection = db.get_collection("warnings")
col_analytics = db.get_collection("analytics") col_analytics: AsyncCollection = db.get_collection("analytics")
# Sync declarations as a fallback
sync_db: Database = db_client_sync.get_database(name=db_config["name"])
sync_col_users: Collection = sync_db.get_collection("users")
sync_col_warnings: Collection = sync_db.get_collection("warnings")
sync_col_analytics: Collection = sync_db.get_collection("analytics")

View File

@ -1,8 +1,6 @@
aiofiles==24.1.0 aiofiles~=24.1.0
apscheduler==3.11.0 apscheduler~=3.11.0
pymongo~=4.10.0 async_pymongo==0.1.11
requests~=2.32.3 libbot[speed,pycord]==3.2.3
ujson~=5.10.0 ujson~=5.10.0
WaifuPicsPython==0.2.0 WaifuPicsPython==0.2.0
--extra-index-url https://git.end-play.xyz/api/packages/profitroll/pypi/simple
libbot[speed,pycord]==3.2.3