Skip to content

Commit 38ec93f

Browse files
committed
Implement basic custom prefixes
1 parent 90e78bb commit 38ec93f

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

bot/libs/utils/prefix.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

bot/rodhaj.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@
1919
RodhajHelp,
2020
send_error_embed,
2121
)
22+
from libs.utils.prefix import get_prefix
2223
from libs.utils.reloader import Reloader
2324

2425
if TYPE_CHECKING:
2526
from cogs.tickets import Tickets
2627

28+
2729
TRANSPROGRAMMER_GUILD_ID = 1183302385020436480
2830

2931

@@ -46,13 +48,14 @@ def __init__(
4648
allowed_mentions=discord.AllowedMentions(
4749
everyone=False, replied_user=False
4850
),
49-
command_prefix=["r>", "?", "!"],
51+
command_prefix=get_prefix,
5052
help_command=RodhajHelp(),
5153
intents=intents,
5254
tree_cls=RodhajCommandTree,
5355
*args,
5456
**kwargs,
5557
)
58+
self.default_prefix = "r>"
5659
self.logger = logging.getLogger("rodhaj")
5760
self.session = session
5861
self.partial_config: Optional[PartialConfig] = None

0 commit comments

Comments
 (0)