aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/hydroroll/plugins/HydroRoll_plugin_dice/__init__.py
blob: 2c9d2b4d2ba0a0101cd20f93230910d79caf192d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import re
import random

from iamai.log import logger

from plugins.hydroroll_plugin_base import CommandPluginBase

from .config import Config

__all__ = ["Dice"]

class Dice(CommandPluginBase[None, Config]):
    Config = Config

    def __post_init__(self):
        self.re_pattern = re.compile(
            r"\s*(?P<dice_times>\d+)d(?P<dice_faces>\d+)([*x](?P<dice_multiply>\d+))?",
            flags=re.I,
        )

    async def handle(self) -> None:
        dice_times = int(self.msg_match.group("dice_times"))
        dice_faces = int(self.msg_match.group("dice_faces"))
        if self.msg_match.group("dice_multiply") is None:
            dice_multiply = None
        else:
            dice_multiply = int(self.msg_match.group("dice_multiply"))

        if dice_times > self.config.max_dice_times:
            await self.event.reply(
                self.format_str(self.config.exceed_max_dice_times_str)
            )
            return

        dice = [random.randint(1, dice_faces) for _ in range(dice_times)]
        dice_sum = sum(dice)
        if dice_multiply is None:
            result_str = f"{dice_times}D{dice_faces}="
            if dice_times != 1:
                result_str += f"{'+'.join(map(lambda x: str(x), dice))}="
            result_str += str(dice_sum)
        else:
            result_str = f"{dice_times}D{dice_faces}x{dice_multiply}="
            if dice_times != 1:
                result_str += (
                    f"({'+'.join(map(lambda x: str(x), dice))})x{dice_multiply}="
                )
            result_str += f"{dice_sum}x{dice_multiply}={dice_sum * dice_multiply}"

        logger.info(f"Dice Plugin: {result_str}")
        await self.event.reply(self.format_str(self.config.message_str, result_str))