bitbot-3.11-fork/modules/dice.py

58 lines
1.9 KiB
Python
Raw Normal View History

#--depends-on commands
2019-09-26 13:04:59 +00:00
import random, re
from src import ModuleManager, utils
ERROR_FORMAT = "Incorrect format! Format must be [number]d[number], e.g. 1d20"
2020-01-14 10:48:09 +00:00
RE_DICE = re.compile("^([1-9]\d*)?d([1-9]\d*)((?:\s*[-+][1-9]\d{,2})*)\s*$",
re.I)
2019-09-26 13:04:59 +00:00
RE_MODIFIERS = re.compile("([-+]\d+)")
2019-09-26 13:15:54 +00:00
MAX_DICE = 6
MAX_SIDES = 100
class Module(ModuleManager.BaseModule):
2019-09-26 13:48:05 +00:00
@utils.hook("received.command.roll")
2019-09-26 13:06:58 +00:00
@utils.hook("received.command.dice", alias_of="roll")
2019-09-26 13:15:54 +00:00
@utils.kwarg("help", "Roll dice DND-style")
@utils.kwarg("usage", "[1-%s]d[1-%d]" % (MAX_DICE, MAX_SIDES))
def roll_dice(self, event):
2019-09-26 13:48:05 +00:00
args = None
if event["args_split"]:
2020-01-14 10:48:09 +00:00
args = event["args"]
2019-09-26 13:48:05 +00:00
else:
args = "1d6"
match = RE_DICE.match(args)
2019-09-26 13:04:59 +00:00
if match:
roll = match.group(0)
2019-09-26 13:32:48 +00:00
dice_count = int(match.group(1) or "1")
2019-09-26 13:04:59 +00:00
side_count = int(match.group(2))
2020-01-14 10:48:09 +00:00
modifiers_str = "".join(match.group(3).split())
modifiers = RE_MODIFIERS.findall(modifiers_str)
2019-09-26 13:04:59 +00:00
if dice_count > 6:
2019-09-26 13:15:54 +00:00
raise utils.EventError("Max number of dice is %s" % MAX_DICE)
if side_count > MAX_SIDES:
raise utils.EventError("Max number of sides is %s"
% MAX_SIDES)
2019-09-26 13:04:59 +00:00
results = random.choices(range(1, side_count+1), k=dice_count)
2019-09-26 13:04:59 +00:00
total_n = sum(results)
for modifier in modifiers:
if modifier[0] == "+":
total_n += int(modifier[1:])
else:
total_n -= int(modifier[1:])
2018-11-17 12:18:26 +00:00
2019-09-26 13:04:59 +00:00
total = ""
if len(results) > 1 or modifiers:
2019-09-26 13:04:59 +00:00
total = " (total: %d)" % total_n
results_str = ", ".join(str(r) for r in results)
event["stdout"].write("Rolled %s and got %s%s" % (
roll, results_str, total))
else:
event["stderr"].write("Invalid format. Example: 2d12+2")