Skip to content

Commit

Permalink
♻️ refactor nation lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
YousefEZ committed Sep 26, 2024
1 parent 99aea31 commit 2408f3b
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 124 deletions.
53 changes: 40 additions & 13 deletions lon.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import os
import sys
from typing import (
Any,
Awaitable,
Callable,
Concatenate,
Expand All @@ -18,8 +19,12 @@
Optional,
TypeVar,
)
from discord.client import Coro
import forge
import qalib
from qalib.interaction import QalibInteraction
from qalib.renderer import Renderer, RenderingOptions
from qalib.template_engines.template_engine import TemplateEngine
from qalib.translators.deserializer import K_contra
from qalib.translators.view import CheckEvent
from typing_extensions import ParamSpec
Expand Down Expand Up @@ -78,15 +83,38 @@ def __init__(self, bot: LeagueOfNations):

@dataclass(frozen=True)
class Event(Generic[K_contra]):
ctx: qalib.interaction.QalibInteraction[K_contra]
bot: LeagueOfNations


@dataclass(frozen=True)
class EventWithContext(Event, Generic[K_contra]):
ctx: qalib.interaction.QalibInteraction[K_contra]


class EventProtocol(Generic[K_contra]):
ctx: qalib.interaction.QalibInteraction[K_contra]
bot: LeagueOfNations


def qalib_event_interaction(
template_engine: TemplateEngine, filename: str, *renderer_options: RenderingOptions
) -> Callable[[Callable[..., Coro[T]]], Callable[..., Coro[T]]]:
renderer_instance: Renderer[str] = Renderer(template_engine, filename, *renderer_options)

def command(func: Callable[..., Coro[T]]) -> Callable[..., Coro[T]]:
@wraps(func)
async def function(
self, item: discord.ui.Item, inter: discord.Interaction, *args: Any, **kwargs: Any
) -> T:
return await func(
self, item, QalibInteraction(inter, renderer_instance), *args, **kwargs
)

return function

return command


def event_with_session(
method: Callable[Concatenate[K, Session, P], Coroutine[None, None, T]],
) -> Callable[Concatenate[K, P], Coroutine[None, None, T]]:
Expand Down Expand Up @@ -141,7 +169,7 @@ def cog_with_session(
method: Callable[
Concatenate[commands.Cog, discord.Interaction, Session, P], Coroutine[None, None, T]
],
) -> Callable[Concatenate[commands.Cog, discord.Interaction, P], Coroutine[None, None, T]]:
):
# This is a hacky way to forge the signature of the method so that discord.py can accept it
@wraps(method, updated=tuple())
@forge.delete("session")
Expand All @@ -164,20 +192,19 @@ async def wrapper(self, ctx: discord.Interaction, *args: P.args, **kwargs: P.kwa

def user_registered(
method: Callable[
Concatenate[commands.Cog, discord.Interaction, Session, P], Coroutine[None, None, None]
Concatenate[commands.Cog, discord.Interaction, P], Coroutine[None, None, None]
],
):
@wraps(method)
async def wrapper(
self, ctx: discord.Interaction, session: Session, *args: P.args, **kwargs: P.kwargs
) -> None:
user = Nation(base_types.UserId(ctx.user.id), session)
if not user.exists:
await ctx.response.send_message(
":x: You are not registered. Please use /start to register."
)
else:
await method(self, ctx, session, *args, **kwargs)
async def wrapper(self, ctx: discord.Interaction, *args: P.args, **kwargs: P.kwargs) -> None:
with Session(self.bot.engine) as session:
user = Nation(base_types.UserId(ctx.user.id), session)
if not user.exists:
await ctx.response.send_message(
":x: You are not registered. Please use /start to register."
)
return
await method(self, ctx, *args, **kwargs)

return wrapper

Expand Down
28 changes: 14 additions & 14 deletions view/cogs/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
TradeSentResponses,
)
from lon import (
Event,
EventWithContext,
LeagueOfNations,
LonCog,
event_with_session,
Expand Down Expand Up @@ -56,7 +56,7 @@


@dataclass(frozen=True)
class ResourceSwitch(Event[TradeSelectMessages]):
class ResourceSwitch(EventWithContext[TradeSelectMessages]):
resource: ResourceName

@event_with_session
Expand All @@ -74,7 +74,7 @@ async def __call__(
"select_resources",
keywords={"Resources": Resources, "nation": nation},
callables={
resource: ResourceSwitch(self.ctx, self.bot, resource)
resource: ResourceSwitch(self.bot, self.ctx, resource)
for resource in nation.trade.resources
},
)
Expand All @@ -99,7 +99,7 @@ async def __call__(


@dataclass(frozen=True)
class TradeOffer(Event[TradeOfferMessages]):
class TradeOffer(EventWithContext[TradeOfferMessages]):
recipient: base_types.UserId

@event_with_session
Expand Down Expand Up @@ -163,7 +163,7 @@ async def cancel(self, *_: Any) -> None:
}


class TradeRequestView(Event[TradeRequestMessages]):
class TradeRequestView(EventWithContext[TradeRequestMessages]):
@event_with_session
async def accept(
self,
Expand Down Expand Up @@ -263,7 +263,7 @@ async def __call__(
}


class TradeView(Event[TradeViewMessages | TradeCancelMessages]):
class TradeView(EventWithContext[TradeViewMessages | TradeCancelMessages]):
@event_with_session
async def cancel(self, session: Session, *_: Any, partner_id: base_types.UserId) -> None:
nation = Nation(as_user_id(self.ctx.user.id), session)
Expand Down Expand Up @@ -322,8 +322,8 @@ class Trade(LonCog):
trade_group = app_commands.Group(name="trade", description="Group related to trade commands")

@trade_group.command(name="select", description="Select resources to trade")
@cog_with_session
@user_registered
@cog_with_session
@qalib.qalib_interaction(Jinja2(ENVIRONMENT), "templates/trade/select.xml")
async def select(
self, ctx: qalib.interaction.QalibInteraction[TradeSelectMessages], session: Session
Expand All @@ -333,15 +333,15 @@ async def select(
"select_resources",
keywords={"Resources": Resources, "nation": nation},
callables={
resource: ResourceSwitch(ctx, self.bot, resource)
resource: ResourceSwitch(self.bot, ctx, resource)
for resource in nation.trade.resources
},
)

@trade_group.command(name="offer", description="Offer a trade to another user")
@cog_with_session
@user_registered
@cog_find_nation("recipient")
@cog_with_session
@qalib.qalib_interaction(Jinja2(ENVIRONMENT), "templates/trade/offer.xml")
async def offer(
self,
Expand All @@ -354,7 +354,7 @@ async def offer(
ctx.user.id,
recipient.identifier,
)
make_offer = TradeOffer(ctx, self.bot, recipient.identifier)
make_offer = TradeOffer(self.bot, ctx, recipient.identifier)
await ctx.display(
"trade_offer",
keywords={
Expand All @@ -367,8 +367,8 @@ async def offer(
)

@trade_group.command(name="requests", description="View trade offers")
@cog_with_session
@user_registered
@cog_with_session
@qalib.qalib_interaction(Jinja2(ENVIRONMENT), "templates/trade/request.xml")
async def requests(
self, ctx: qalib.interaction.QalibInteraction[TradeRequestMessages], session: Session
Expand All @@ -377,13 +377,13 @@ async def requests(
await ctx.display(
"trade_requests",
keywords={"nation": nation, "Resources": Resources},
callables={"trade_identifier": TradeRequestView(ctx, self.bot)},
callables={"trade_identifier": TradeRequestView(self.bot, ctx)},
events={ViewEvents.ON_CHECK: ensure_user(ctx.user.id)},
)

@trade_group.command(name="view", description="Cancel a trade offer")
@cog_with_session
@user_registered
@cog_with_session
@qalib.qalib_interaction(Jinja2(ENVIRONMENT), "templates/trade/view.xml")
async def view(
self,
Expand All @@ -393,7 +393,7 @@ async def view(
await ctx.display(
"trades",
keywords={"nation": Nation(as_user_id(ctx.user.id), session), "Resources": Resources},
callables={"trade_identifier": TradeView(ctx, self.bot)},
callables={"trade_identifier": TradeView(self.bot, ctx)},
events={ViewEvents.ON_CHECK: ensure_user(ctx.user.id)},
)

Expand Down
Loading

0 comments on commit 2408f3b

Please sign in to comment.