1"""Bot class: wiring for the API client, config cache, plugins, and slash-command errors."""
2
3import logging
4import pkgutil
5from typing import TYPE_CHECKING
6
7import discord
8from discord import app_commands
9from discord.ext import commands
10
11from sidequest_bot import plugins
12from sidequest_bot.api_client import APIError, SideQuestAPI
13from sidequest_bot.config_cache import GuildConfigCache
14
15if TYPE_CHECKING:
16 from sidequest_common.settings import APISettings, DiscordSettings
17
18logger = logging.getLogger(__name__)
19
20
[docs]
21def build_intents() -> discord.Intents:
22 """Default intents plus the privileged ones the plugins need.
23
24 ``members``: welcome, auto-role, member logs. ``message_content``: automod filters and logging message text.
25 Both must also be enabled for the application in the Discord Developer Portal.
26 """
27 intents = discord.Intents.default()
28 intents.members = True
29 intents.message_content = True
30 return intents
31
32
[docs]
33class SideQuestBot(commands.Bot):
34 """Slash-command bot. ``api`` and ``configs`` are shared by every plugin."""
35
36 def __init__(self, *, api: SideQuestAPI, dev_guild_id: int | None = None) -> None:
37 super().__init__(
38 command_prefix=commands.when_mentioned, # slash-only; prefix commands are unused
39 intents=build_intents(),
40 allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=True),
41 tree_cls=SideQuestTree,
42 )
43 self.api = api
44 self.configs = GuildConfigCache(api)
45 self.dev_guild_id = dev_guild_id
46
[docs]
47 async def setup_hook(self) -> None:
48 """Load every plugin module, then sync slash commands."""
49 for module in pkgutil.iter_modules(plugins.__path__, prefix=f"{plugins.__name__}."):
50 await self.load_extension(module.name)
51 logger.info("Loaded plugin %s", module.name)
52 if self.dev_guild_id is not None:
53 guild = discord.Object(id=self.dev_guild_id)
54 self.tree.copy_global_to(guild=guild)
55 synced = await self.tree.sync(guild=guild)
56 else:
57 synced = await self.tree.sync()
58 logger.info("Synced %d slash commands", len(synced))
59
[docs]
60 async def close(self) -> None:
61 """Close the API client along with the gateway connection."""
62 await super().close()
63 await self.api.aclose()
64
[docs]
65 async def on_ready(self) -> None:
66 """Log the identity we connected as."""
67 logger.info("Connected as %s (%s) to %d guild(s)", self.user, getattr(self.user, "id", "?"), len(self.guilds))
68
[docs]
69 async def on_message(self, message: discord.Message, /) -> None:
70 """Do nothing: commands are slash-only, and parsing a mention as a prefix command logs CommandNotFound.
71
72 Cog ``on_message`` listeners still run.
73 """
74
[docs]
75 async def send_log(self, guild: discord.Guild, embed: discord.Embed) -> discord.Message | None:
76 """Post ``embed`` to the guild's configured log channel. No-op if unset, missing, or not writable."""
77 config = await self.configs.get(guild.id)
78 if config.log_channel_id is None:
79 return None
80 channel = guild.get_channel(config.log_channel_id)
81 if not isinstance(channel, discord.TextChannel):
82 return None
83 try:
84 return await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
85 except discord.HTTPException:
86 logger.warning("Could not post to log channel %s in guild %s", channel.id, guild.id, exc_info=True)
87 return None
88
89
[docs]
90class SideQuestTree(app_commands.CommandTree[SideQuestBot]):
91 """Command tree that tells users what went wrong (ephemerally) instead of failing silently."""
92
[docs]
93 async def on_error( # ty: ignore[invalid-method-override] # discord.py also binds on_error as an attribute
94 self, interaction: discord.Interaction[SideQuestBot], error: app_commands.AppCommandError, /
95 ) -> None:
96 """Map known failures to a friendly message; log everything unexpected."""
97 original = error.original if isinstance(error, app_commands.CommandInvokeError) else error
98 command_name = interaction.command.name if interaction.command else "?"
99 # CommandOnCooldown and MissingPermissions subclass CheckFailure, so they go first.
100 if isinstance(original, app_commands.CommandOnCooldown):
101 message = f"Slow down! Try again in {original.retry_after:.0f}s."
102 elif isinstance(original, app_commands.MissingPermissions | app_commands.BotMissingPermissions):
103 message = str(original)
104 elif isinstance(original, app_commands.CheckFailure):
105 message = "You can't use this command here."
106 elif isinstance(original, discord.Forbidden):
107 message = "I don't have permission to do that. Check my role's position and permissions."
108 elif isinstance(original, APIError):
109 logger.warning("API error in /%s: %s", command_name, original)
110 message = f"The guild records rejected that: {original.detail}"
111 else:
112 logger.error("Unhandled error in /%s", command_name, exc_info=error)
113 message = "Something went wrong running that command."
114 if interaction.response.is_done():
115 await interaction.followup.send(message, ephemeral=True)
116 else:
117 await interaction.response.send_message(message, ephemeral=True)
118
119
[docs]
120def create_bot(discord_settings: DiscordSettings, api_settings: APISettings) -> SideQuestBot:
121 """Bot wired to the API described by ``api_settings``."""
122 api = SideQuestAPI(api_settings.URL, api_settings.KEY.get_secret_value())
123 return SideQuestBot(api=api, dev_guild_id=discord_settings.GUILD_ID)