Skip to content

Commit

Permalink
Merge pull request #239 from UWCS/bugfix/roll
Browse files Browse the repository at this point in the history
Run `!roll` on a separate process (instead of thread) and with timeout.
  • Loading branch information
Mole1424 authored Feb 6, 2024
2 parents e78bff9 + f9dc10b commit 9dc276b
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions cogs/commands/roll.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@
{body}
"""

TIMEOUT_OUT = """
:hourglass: **DICE OUTTATIME** :hourglass:
{ping} - **{error}**
"""

DICE_TIMEOUT = 3.0 # seconds


class Roll(commands.Cog):
def __init__(self, bot: Bot):
Expand All @@ -65,24 +72,32 @@ def __init__(self, bot: Bot):
help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT, aliases=["r"], rest_is_raw=True
)
async def roll(self, ctx: Context, *, message: clean_content):
loop = asyncio.get_event_loop()
display_name = get_name_string(ctx.message)
p = await Parallelism.get(self.bot)
future = p.execute_on_process(run, message, display_name)

def work():
return run(message, display_name)
try:
result = await asyncio.wait_for(future, DICE_TIMEOUT)
except asyncio.TimeoutError:
result = TIMEOUT_OUT.format(
ping=display_name, error=f"Ran out of time ({DICE_TIMEOUT}s)!"
)

p = await Parallelism.get(self.bot)
p.send_to_ctx_after_threaded(work, ctx, loop)
await ctx.reply(result)

@app_commands.command(name="roll", description=SHORT_HELP_TEXT)
async def roll_slash(self, int: discord.Interaction, dice: str):
loop = asyncio.get_event_loop()
p = await Parallelism.get(self.bot)
future = p.execute_on_process(run, dice, int.user.display_name)

def work():
return run(dice, "")
try:
result = await asyncio.wait_for(future, DICE_TIMEOUT)
except asyncio.TimeoutError:
result = TIMEOUT_OUT.format(
ping=int.user.display_name, error=f"Ran out of time ({DICE_TIMEOUT}s)!"
)

p = await Parallelism.get(self.bot)
p.send_to_int_after_threaded(work, int, loop)
await int.response.send_message(result)


def run(message, display_name):
Expand Down

0 comments on commit 9dc276b

Please sign in to comment.