|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Union |
| 4 | + |
| 5 | +import discord |
| 6 | +from async_lru import alru_cache |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from bot.rodhaj import Rodhaj |
| 10 | + |
| 11 | + |
| 12 | +@alru_cache(maxsize=1024) |
| 13 | +async def get_prefix(bot: Rodhaj, message: discord.Message) -> Union[str, list[str]]: |
| 14 | + """Obtains the prefix for the guild |
| 15 | +
|
| 16 | + This coroutine is heavily cached in order to reduce database calls |
| 17 | + and improved performance |
| 18 | +
|
| 19 | +
|
| 20 | + Args: |
| 21 | + bot (Rodhaj): An instance of `Rodhaj` |
| 22 | + message (discord.Message): The message that is processed |
| 23 | +
|
| 24 | + Returns: |
| 25 | + Union[str, List[str]]: The default prefix or |
| 26 | + a list of prefixes (including the default) |
| 27 | + """ |
| 28 | + user_id = bot.user.id # type: ignore |
| 29 | + |
| 30 | + # By putting the base with the mentions, we are effectively |
| 31 | + # doing the exact same thing as commands.when_mentioned |
| 32 | + base = [f"<@!{user_id}> ", f"<@{user_id}> ", bot.default_prefix] |
| 33 | + if message.guild is None: |
| 34 | + get_prefix.cache_invalidate(bot, message) |
| 35 | + return base |
| 36 | + |
| 37 | + query = """ |
| 38 | + SELECT prefix |
| 39 | + FROM guild_config |
| 40 | + WHERE id = $1; |
| 41 | + """ |
| 42 | + prefixes = await bot.pool.fetchval(query, message.guild.id) |
| 43 | + if prefixes is None: |
| 44 | + get_prefix.cache_invalidate(bot, message) |
| 45 | + return base |
| 46 | + base.extend(item for item in prefixes) |
| 47 | + return base |
0 commit comments