#!/usr/bin/env python3 """ Dice rolling, the core function of any IRC bot. """ import re import random import module @module.commands("roll", "dice", "d") @module.example(".roll 3d1+1", "You roll 3d1+1: (1+1+1)+1 = 4") def roll(bot, trigger): """ .dice XdY[+Z], rolls dice and reports the result. X is the number of dice. Y is the number of faces in the dice. Z is the constant to be applied to the end result. """ if len(trigger.args) < 2: return bot.reply("Roll what?") regex = re.compile(r'(\d+)?d(\d+)([+-]\d+)?') reg = re.match(regex, trigger.args[1]) if not reg: return bot.reply("Invalid dice notation.") num_dice = int(reg.groups()[0]) if reg.groups()[0] else 1 num_sides = int(reg.groups()[1]) modifier = int(reg.groups()[2]) if reg.groups()[2] else 0 num_dice = min(num_dice, 100) num_sides = min(num_sides, 1000) results = [] for _ in range(num_dice): result = random.randint(1, num_sides) results.append(result) total = sum(results) + modifier msg = f"You roll {num_dice}d{num_sides}" if modifier: if modifier > 0: msg += '+' msg += str(modifier) msg += ': ' msg += '(' + '+'.join([str(a) for a in results]) + ')' if modifier: if modifier > 0: msg += '+' msg += str(modifier) msg += " = " + str(total) bot.reply(msg)