def roll(bot, trigger): """.dice XdY[vZ][+N], rolls dice and reports the result. X is the number of dice. Y is the number of faces in the dice. Z is the number of lowest dice to be dropped from the result. N is the constant to be applied to the end result. """ # This regexp is only allowed to have one captured group, because having # more would alter the output of re.findall. dice_regexp = r"\d*d\d+(?:v\d+)?" # Get a list of all dice expressions, evaluate them and then replace the # expressions in the original string with the results. Replacing is done # using string formatting, so %-characters must be escaped. if not trigger.group(2): return bot.reply("No dice to roll.") arg_str = trigger.group(2) dice_expressions = re.findall(dice_regexp, arg_str) arg_str = arg_str.replace("%", "%%") arg_str = re.sub(dice_regexp, "%s", arg_str) f = lambda dice_expr: _roll_dice(bot, dice_expr) dice = list(map(f, dice_expressions)) if None in dice: # Stop computing roll if there was a problem rolling dice. return def _get_eval_str(dice): return "(%d)" % (dice.get_sum(), ) def _get_pretty_str(dice): if dice.num <= 10: return dice.get_simple_string() elif dice.get_number_of_faces() <= 10: return dice.get_compressed_string() else: return "(...)" eval_str = arg_str % (tuple(map(_get_eval_str, dice))) pretty_str = arg_str % (tuple(map(_get_pretty_str, dice))) # Showing the actual error will hopefully give a better hint of what is # wrong with the syntax than a generic error message. try: result = eval_equation(eval_str) except Exception as e: bot.reply("SyntaxError, eval(%s), %s" % (eval_str, e)) return bot.reply("You roll %s: %s = %d" % ( trigger.group(2), pretty_str, result))
def c(bot, trigger): """Evaluate some calculation.""" if not trigger.group(2): return bot.reply("Nothing to calculate.") # Account for the silly non-Anglophones and their silly radix point. eqn = trigger.group(2).replace(',', '.') try: result = eval_equation(eqn) result = "{:.10g}".format(result) except ZeroDivisionError: result = "Division by zero is not supported in this universe." except Exception as e: result = "{error}: {msg}".format(error=type(e), msg=e) bot.reply(result)