Discord/modules/database.py

41 lines
1.4 KiB
Python
Raw Normal View History

2024-12-16 17:25:35 +02:00
from typing import Dict, Any
from async_pymongo import AsyncClient, AsyncCollection, AsyncDatabase
from libbot.sync import config_get as sync_config_get
2023-05-04 17:09:47 +03:00
from pymongo import MongoClient
2024-12-16 17:25:35 +02:00
from pymongo.synchronous.collection import Collection
from pymongo.synchronous.database import Database
2023-05-04 17:09:47 +03:00
2024-12-16 17:25:35 +02:00
db_config: Dict[str, Any] = sync_config_get("database")
2023-05-04 17:09:47 +03:00
2024-12-16 17:25:35 +02:00
con_string: str = (
"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(
2023-05-04 17:09:47 +03:00
db_config["user"],
db_config["password"],
db_config["host"],
db_config["port"],
2023-05-04 17:14:23 +03:00
db_config["name"],
2023-05-04 17:09:47 +03:00
)
)
2024-12-16 17:25:35 +02:00
db_client: AsyncClient = AsyncClient(con_string)
db_client_sync: MongoClient = MongoClient(con_string)
# Async declarations per default
db: AsyncDatabase = db_client.get_database(name=db_config["name"])
col_users: AsyncCollection = db.get_collection("users")
col_warnings: AsyncCollection = db.get_collection("warnings")
col_analytics: AsyncCollection = db.get_collection("analytics")
2023-05-04 17:09:47 +03:00
2024-12-16 17:25:35 +02:00
# Sync declarations as a fallback
sync_db: Database = db_client_sync.get_database(name=db_config["name"])
2023-05-04 17:09:47 +03:00
2024-12-16 17:25:35 +02:00
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")