Skip to content

Commit 768b309

Browse files
committed
Progress on contet, error handling, whatever
1 parent 573835f commit 768b309

File tree

6 files changed

+74
-49
lines changed

6 files changed

+74
-49
lines changed

discord/bot/cogs/core/events.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -355,12 +355,6 @@ async def handle_command_cooldown(
355355
async def on_command_error(self, ctx: Ctx, e: Exception):
356356
self.bot.error_count += 1
357357

358-
if (custom_error := getattr(ctx, "custom_error", None)) is not None:
359-
e = custom_error
360-
361-
# if not isinstance(e, MaxKarenConcurrencyReached) and ctx.command:
362-
# await self.karen.release_concurrency(ctx.command.qualified_name, ctx.author.id)
363-
364358
if isinstance(e, commands.CommandOnCooldown):
365359
await self.handle_command_cooldown(ctx, e.retry_after, False)
366360
elif isinstance(e, CommandOnKarenCooldownError):
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from datetime import datetime, timedelta, timezone
2+
from typing import Any
3+
4+
from discord.ext.commands import CommandError
5+
6+
7+
class CommandOnKarenCooldown(CommandError):
8+
def __init__(self, cooldown_until: datetime):
9+
self.cooldown_until = cooldown_until
10+
super().__init__(f"You are on cooldown. Try again in {self.remaining.total_seconds():.2f}s")
11+
12+
@property
13+
def remaining(self) -> timedelta:
14+
return self.cooldown_until - datetime.now(timezone.utc)
15+
16+
17+
class UserBotBanned(CommandError):
18+
def __init__(self):
19+
super().__init__("You are banned from this bot")
20+
21+
22+
class BotNotReadyYet(CommandError):
23+
def __init__(self):
24+
super().__init__("Bot has not finished starting yet")
25+
26+
27+
class CommandDisabledByGuild(CommandError):
28+
def __init__(self) -> None:
29+
super().__init__("Command is disabled by this Discord server")

discord/bot/logic/ctx.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
from __future__ import annotations
22

3+
import dataclasses
34
import typing
45

56
import discord
67
from discord.ext.commands import Context
78

89
from bot.models.translation import Translation
10+
from bot.services.karen.resources.discord.guild import DiscordGuildSettings as KarenDiscordGuild
11+
from bot.services.karen.resources.users import User as KarenUser
912

1013
if typing.TYPE_CHECKING:
1114
from bot.villager_bot import VillagerBotCluster
@@ -14,16 +17,17 @@
1417
class CustomContext(Context["VillagerBotCluster"]):
1518
"""Custom context class to provide extra helper methods and multi-language support"""
1619

17-
embed_color: discord.Color | None # used in send_embed(...) and reply_embed(...)
20+
@dataclasses.dataclass(frozen=True, slots=True, kw_only=True, eq=False, match_args=False)
21+
class KarenData:
22+
user: KarenUser
23+
guild: KarenDiscordGuild | None
24+
1825
l: Translation # the translation of the bot text for the current context # noqa: E741
19-
failure_reason: str | None # failure reason used in some command error handling
20-
custom_error: Exception | None
26+
k: KarenData
2127

22-
def __init__(self, *args, embed_color: discord.Color | None = None, **kwargs):
28+
def __init__(self, *args, **kwargs):
2329
super().__init__(*args, **kwargs)
2430

25-
self.embed_color = embed_color
26-
2731
async def send_embed(self, message: str, *, ignore_exceptions: bool = False) -> None:
2832
await self.bot.send_embed(self, message, ignore_exceptions=ignore_exceptions)
2933

@@ -42,6 +46,17 @@ def __repr__(self) -> str:
4246

4347
return f"Ctx({guild_id=}, {author_id=})"
4448

49+
async def async_init(self):
50+
self.l = await self.bot.get_language(self)
51+
52+
karen_guild_settings: KarenDiscordGuild | None = None
53+
if self.guild is not None:
54+
karen_guild_settings = await self.bot.karen.discord.cached.guilds.get(self.guild.id)
55+
56+
karen_user = await self.bot.karen.cached.users.get(self.author.id)
57+
58+
self.k = self.KarenData(user=karen_user, guild=karen_guild_settings)
59+
4560

4661
Ctx = CustomContext
4762

discord/bot/logic/errors.py

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
from .cache import KarenResourceCache
2-
from .client import KarenClient
2+
from .client import KarenClient

discord/bot/villager_bot.py

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing import Any
66

77
import aiohttp
8+
from bot.logic.command_errors import BotNotReadyYet, CommandDisabledByGuild, UserBotBanned
89
import captcha.image
910
import discord
1011
import psutil
@@ -158,32 +159,31 @@ async def on_ready(self):
158159
"An error occurred in on_ready while syncing slash commands",
159160
)
160161

161-
try:
162-
self.logger.info("Syncing db item prices...")
162+
# try:
163+
# self.logger.info("Syncing db item prices...")
163164

164-
item_prices = {v.db_entry.item: v.db_entry.sell_price for k, v in self.d.shop_items.items()}
165-
item_prices.update(
166-
{self.d.farming.name_map[k]: v for k, v in self.d.farming.emerald_yields.items()},
167-
)
168-
item_prices.update({f.item: f.sell_price for f in self.d.fishing_findables})
169-
item_prices.update({
170-
self.d.farming.name_map[crop_type]: emerald_amount
171-
for crop_type, emerald_amount in self.d.farming.emerald_yields.items()
172-
})
165+
# item_prices = {v.db_entry.item: v.db_entry.sell_price for k, v in self.d.shop_items.items()}
166+
# item_prices.update(
167+
# {self.d.farming.name_map[k]: v for k, v in self.d.farming.emerald_yields.items()},
168+
# )
169+
# item_prices.update({f.item: f.sell_price for f in self.d.fishing_findables})
170+
# item_prices.update({
171+
# self.d.farming.name_map[crop_type]: emerald_amount
172+
# for crop_type, emerald_amount in self.d.farming.emerald_yields.items()
173+
# })
173174

174-
await self.get_cog("Database").sync_item_prices(item_prices)
175+
# await self.get_cog("Database").sync_item_prices(item_prices)
175176

176-
self.logger.info("Done syncing db item prices!")
177-
except Exception:
178-
self.logger.exception(
179-
"An error occurred in on_ready while syncing db item prices",
180-
)
177+
# self.logger.info("Done syncing db item prices!")
178+
# except Exception:
179+
# self.logger.exception(
180+
# "An error occurred in on_ready while syncing db item prices",
181+
# )
181182

182183
async def get_context(self, *args, **kwargs) -> CustomContext: # type: ignore[override]
183-
ctx = await super().get_context(*args, **kwargs, cls=CustomContext)
184+
ctx: CustomContext = await super().get_context(*args, **kwargs, cls=CustomContext)
184185

185-
ctx.embed_color = self.embed_color
186-
ctx.l = await self.get_language(ctx)
186+
await ctx.async_init()
187187

188188
return ctx
189189

@@ -230,16 +230,13 @@ async def check_global(self, ctx: CustomContext) -> bool: # the global command
230230
karen_guild_settings = (await self.karen.discord.cached.guilds.get(ctx.guild.id)) if ctx.guild else None
231231

232232
if karen_user.banned:
233-
ctx.failure_reason = "bot_banned"
234-
return False
233+
raise UserBotBanned()
235234

236235
if not self.is_ready():
237-
ctx.failure_reason = "not_ready"
238-
return False
236+
raise BotNotReadyYet()
239237

240238
if karen_guild_settings is not None and command_name in karen_guild_settings.disabled_commands:
241-
ctx.failure_reason = "disabled"
242-
return False
239+
raise CommandDisabledByGuild()
243240

244241
preflight = await self.karen.command_executions.preflight(
245242
CommandExecutionPreflightRequest(

0 commit comments

Comments
 (0)