Skip to content

Commit

Permalink
Rewrite jdr start command
Browse files Browse the repository at this point in the history
  • Loading branch information
ttgc committed Mar 23, 2024
1 parent 170d7a1 commit c310724
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 9 deletions.
38 changes: 37 additions & 1 deletion src/dpylib/cogs/jdr/jdr.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>


from typing import Optional
import discord
from discord.ext import commands
from dices import Expression
from config import Log
from lang import localize
from models import JdrDTO
from utils.aliases import JdrChannel
from ...common.contextext import ExtendedContext, prepare_ctx


Expand All @@ -41,6 +45,38 @@ async def roll(self, ctx: ExtendedContext, *, expression: str) -> None:
Special dice example : `/rollindep 1d{1,2,3,4,5,6,7,8,9,10,Jack,Queen,King}+1d{Clubs,Diamonds,Hearts,Spades}` will return a single card with its value and its color (example : Queen of Spades)"""
parser = Expression(expression)
result = parser()
Log.info("rolled '%s' in channel %d of server %d", result, ctx.channel.id, ctx.guild.id) # pyright: ignore
Log.info("rolled '%s' in channel %d of server %d", result, ctx.channel.id, ctx.guild.id)
await ctx.send(await localize(ctx, 'rollindep', result), reference=ctx.message)

@commands.hybrid_group(aliases=['rp'])
async def jdr(self, ctx: ExtendedContext) -> None:
pass

@prepare_ctx
@commands.cooldown(1, 60, commands.BucketType.guild)
@jdr.command(name='start', aliases=['new', '+'], description="Create a new JDR in this channel")
async def jdr_start(self, ctx: ExtendedContext, channel: discord.abc.GuildChannel, label: Optional[str] = None) -> None:
"""TBD"""
srv = await ctx.ext.server

if not isinstance(channel, JdrChannel.__value__):
await ctx.send(await localize(ctx, ''), reference=ctx.message)

if not srv or not isinstance(ctx.author, discord.Member):
Log.error(
"JDR create unexpected init error for guild %d and channel %d with owner %d",
ctx.guild.id,
channel.id,
ctx.author.id
)
await ctx.send(await localize(ctx, ''), reference=ctx.message)
return

jdr = await JdrDTO.create(srv, channel.id, ctx.author, fetch=False, label=label)

if jdr:
Log.info("JDR created in guild %d, channel %d with owner %d", ctx.guild.id, channel.id, ctx.author.id)
await ctx.send(await localize(ctx, ''), reference=ctx.message)
else:
Log.warn("JDR cannot be created in guild %d, channel %d with owner %d", ctx.guild.id, channel.id, ctx.author.id)
await ctx.send(await localize(ctx, ''), reference=ctx.message)
8 changes: 8 additions & 0 deletions src/dpylib/common/contextext.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from typing import Optional
from enum import StrEnum
import asyncio
import discord
from discord.ext import commands
from models import MemberDTO, ServerDTO, JdrDTO
from lang import Language
Expand Down Expand Up @@ -81,6 +82,13 @@ def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.ext = ContextExtension(self)

@discord.utils.cached_property
def guild(self) -> discord.Guild:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available."""
if not (guild := super().guild):
raise commands.GuildNotFound('CTX')
return guild


def prepare_ctx(cmd: commands.Command) -> commands.Command:

Expand Down
32 changes: 32 additions & 0 deletions src/dpylib/common/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!usr/bin/env python3
#-*-coding:utf-8-*-

## TtgcBot - a bot for discord
## Copyright (C) 2017-2024 Thomas PIOT
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>


from typing import Optional
import discord
from models import ServerDTO


def extract_top_role(srv: ServerDTO, user: discord.Member) -> Optional[int]:
if srv.admin_role and (role := user.get_role(srv.admin_role)):
return role.id
elif srv.mj_role and (role := user.get_role(srv.mj_role)):
return role.id

return None
7 changes: 5 additions & 2 deletions src/lang/localizing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>


from dpylib.common.contextext import ExtendedContext
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from dpylib.common.contextext import ExtendedContext

async def localize(ctx: ExtendedContext, msgkey: str, *args) -> str:

async def localize(ctx: 'ExtendedContext', msgkey: str, *args) -> str:
lang = await ctx.ext.get_lang()
return lang[msgkey].format(*args)
28 changes: 27 additions & 1 deletion src/models/jdr.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>


from typing import Self, Optional
from typing import Self, Optional, TYPE_CHECKING
from dataclasses import dataclass
from network.api import API
from network.httprequest import HTTP
Expand All @@ -27,6 +27,11 @@
from network.exceptions import HTTPException
from config import Log
from utils.decorators import catch
from dpylib.common.user import extract_top_role

if TYPE_CHECKING:
import discord
from .server import ServerDTO


@dataclass
Expand Down Expand Up @@ -91,3 +96,24 @@ async def get_jdr_list(cls, srv_id: int) -> list[Self]:
) for x in response.result.get('jdr', [])]

return []

@catch(HTTPException, error_value=None, logger=Log.error, asynchronous=True)
@classmethod
async def create(cls, srv: 'ServerDTO', chan_id: int, owner: 'discord.Member', *, fetch: bool = True, **params) -> Optional[Self]:
async with API('/api/jdr/create') as api:
body = {
'server': srv.id,
'channel': chan_id,
'extensions': list(params.get('extensions', [])),
'owner': owner.id,
'label': params.get('label', None)
}
response = await api(HTTP.POST, f'/api/jdr/create', body, requester=owner.id, role=extract_top_role(srv, owner))
response.raise_errors()

dto = cls(srv.id, chan_id)

if fetch:
await dto.fetch()

return dto
5 changes: 0 additions & 5 deletions src/network/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,6 @@ async def __aenter__(self) -> Self:
}
}

if self.requester:
body["member"] = self.requester
if self.requester_role:
body["role"] = self.requester_role

response = await HTTP.POST(f"{self.url}/api/Login", body, expected_result=HttpResultType.TEXT, https=self.https)
response.raise_errors()
self.logged = response.status.ok
Expand Down
2 changes: 2 additions & 0 deletions src/utils/aliases.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@


from typing import Awaitable, Callable
import discord


type AsyncCallable[T] = Callable[..., Awaitable[T]]
type JdrChannel = discord.TextChannel | discord.ForumChannel | discord.VoiceChannel

0 comments on commit c310724

Please sign in to comment.