Skip to content

Commit 1537298

Browse files
committed
Add additional database support potentials
1 parent ac44377 commit 1537298

File tree

5 files changed

+186
-100
lines changed

5 files changed

+186
-100
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@ however, insignificant breaking changes do not guarantee a major version bump, s
1919
### Changed
2020

2121
- Bump discord.py version to v1.3.3.
22-
- Renamed `bot.owner_ids` to `bot.bot_owner_ids` as the attribute is now defined interally for team support.
22+
- Renamed `bot.owner_ids` to `bot.bot_owner_ids` as the attribute is now defined internally for team support.
2323
- Deleting channel manually will now close the thread.
2424
- Deleting messages will no longer cause the bot to produce warnings.
2525
- Plugins will automatically be removed when it fails to load.
26+
- Moved all database-related activities to clients.py under MongoDBClient, with possible future hook for additional database support.
27+
- Deprecated `bot.plugin_db.get_partition` in favour of `bot.api.get_plugin_partition` (not final).
2628

2729
### Fixed
2830

bot.py

Lines changed: 9 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@
1818

1919
from aiohttp import ClientSession
2020
from emoji import UNICODE_EMOJI
21-
from motor.motor_asyncio import AsyncIOMotorClient
22-
from pymongo.errors import ConfigurationError
2321

2422
from pkg_resources import parse_version
2523

@@ -32,7 +30,7 @@
3230
pass
3331

3432
from core import checks
35-
from core.clients import ApiClient, PluginDatabaseClient
33+
from core.clients import ApiClient, PluginDatabaseClient, MongoDBClient
3634
from core.config import ConfigManager
3735
from core.utils import human_join, normalize_alias
3836
from core.models import PermissionLevel, SafeFormatter, getLogger, configure_logging
@@ -72,22 +70,7 @@ def __init__(self):
7270
self.log_file_name = os.path.join(temp_dir, f"{self.token.split('.')[0]}.log")
7371
self._configure_logging()
7472

75-
mongo_uri = self.config["mongo_uri"]
76-
if mongo_uri is None:
77-
logger.critical("A Mongo URI is necessary for the bot to function.")
78-
raise RuntimeError
79-
80-
try:
81-
self.db = AsyncIOMotorClient(mongo_uri).modmail_bot
82-
except ConfigurationError as e:
83-
logger.critical(
84-
"Your MONGO_URI might be copied wrong, try re-copying from the source again. "
85-
"Otherwise noted in the following message:"
86-
)
87-
logger.critical(e)
88-
sys.exit(0)
89-
90-
self.plugin_db = PluginDatabaseClient(self)
73+
self.plugin_db = PluginDatabaseClient(self) # Deprecated
9174
self.startup()
9275

9376
@property
@@ -158,7 +141,11 @@ def session(self) -> ClientSession:
158141
@property
159142
def api(self) -> ApiClient:
160143
if self._api is None:
161-
self._api = ApiClient(self)
144+
if self.config["database_type"].lower() == "mongodb":
145+
self._api = MongoDBClient(self)
146+
else:
147+
logger.critical("Invalid database type.")
148+
raise RuntimeError
162149
return self._api
163150

164151
async def get_prefix(self, message=None):
@@ -376,37 +363,16 @@ def command_perm(self, command_name: str) -> PermissionLevel:
376363

377364
async def on_connect(self):
378365
try:
379-
await self.validate_database_connection()
366+
await self.api.validate_database_connection()
380367
except Exception:
381368
logger.debug("Logging out due to failed database connection.")
382369
return await self.logout()
383370

384371
logger.debug("Connected to gateway.")
385372
await self.config.refresh()
386-
await self.setup_indexes()
373+
await self.api.setup_indexes()
387374
self._connected.set()
388375

389-
async def setup_indexes(self):
390-
"""Setup text indexes so we can use the $search operator"""
391-
coll = self.db.logs
392-
index_name = "messages.content_text_messages.author.name_text_key_text"
393-
394-
index_info = await coll.index_information()
395-
396-
# Backwards compatibility
397-
old_index = "messages.content_text_messages.author.name_text"
398-
if old_index in index_info:
399-
logger.info("Dropping old index: %s", old_index)
400-
await coll.drop_index(old_index)
401-
402-
if index_name not in index_info:
403-
logger.info('Creating "text" index for logs collection.')
404-
logger.info("Name: %s", index_name)
405-
await coll.create_index(
406-
[("messages.content", "text"), ("messages.author.name", "text"), ("key", "text")]
407-
)
408-
logger.debug("Successfully configured and verified database indexes.")
409-
410376
async def on_ready(self):
411377
"""Bot startup, sets uptime."""
412378

@@ -1213,37 +1179,6 @@ async def on_command_error(self, context, exception):
12131179
else:
12141180
logger.error("Unexpected exception:", exc_info=exception)
12151181

1216-
async def validate_database_connection(self):
1217-
try:
1218-
await self.db.command("buildinfo")
1219-
except Exception as exc:
1220-
logger.critical("Something went wrong while connecting to the database.")
1221-
message = f"{type(exc).__name__}: {str(exc)}"
1222-
logger.critical(message)
1223-
1224-
if "ServerSelectionTimeoutError" in message:
1225-
logger.critical(
1226-
"This may have been caused by not whitelisting "
1227-
"IPs correctly. Make sure to whitelist all "
1228-
"IPs (0.0.0.0/0) https://i.imgur.com/mILuQ5U.png"
1229-
)
1230-
1231-
if "OperationFailure" in message:
1232-
logger.critical(
1233-
"This is due to having invalid credentials in your MONGO_URI. "
1234-
"Remember you need to substitute `<password>` with your actual password."
1235-
)
1236-
logger.critical(
1237-
"Be sure to URL encode your username and password (not the entire URL!!), "
1238-
"https://www.urlencoder.io/, if this issue persists, try changing your username and password "
1239-
"to only include alphanumeric characters, no symbols."
1240-
""
1241-
)
1242-
raise
1243-
else:
1244-
logger.debug("Successfully connected to the database.")
1245-
logger.line("debug")
1246-
12471182
async def post_metadata(self):
12481183
info = await self.application_info()
12491184

cogs/modmail.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -669,12 +669,7 @@ async def logs_closed_by(self, ctx, *, user: User = None):
669669
"""
670670
user = user if user is not None else ctx.author
671671

672-
query = {"guild_id": str(self.bot.guild_id), "open": False, "closer.id": str(user.id)}
673-
674-
projection = {"messages": {"$slice": 5}}
675-
676-
entries = await self.bot.db.logs.find(query, projection).to_list(None)
677-
672+
entries = await self.bot.api.search_closed_by(user.id)
678673
embeds = self.format_log_embeds(entries, avatar_url=self.bot.guild.icon_url)
679674

680675
if not embeds:
@@ -748,15 +743,7 @@ async def logs_search(self, ctx, limit: Optional[int] = None, *, query):
748743

749744
await ctx.trigger_typing()
750745

751-
query = {
752-
"guild_id": str(self.bot.guild_id),
753-
"open": False,
754-
"$text": {"$search": f'"{query}"'},
755-
}
756-
757-
projection = {"messages": {"$slice": 5}}
758-
759-
entries = await self.bot.db.logs.find(query, projection).to_list(limit)
746+
entries = await self.bot.api.search_by_text(query, limit)
760747

761748
embeds = self.format_log_embeds(entries, avatar_url=self.bot.guild.icon_url)
762749

0 commit comments

Comments
 (0)