Skip to content

Commit

Permalink
Merge pull request #625 from creftos/master
Browse files Browse the repository at this point in the history
[dice]Fix empty & invalid argument, close #624 & close #626
  • Loading branch information
tyrope committed Sep 29, 2014
2 parents 195302c + d51db97 commit 6a6cae2
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions willie/modules/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def get_number_of_faces(self):
return len(self.dice) + len(self.dropped)


def _roll_dice(dice_expression):
def _roll_dice(bot, dice_expression):
result = re.search(
r"""
(?P<dice_num>\d*)
Expand All @@ -131,11 +131,17 @@ def _roll_dice(dice_expression):
dice_num = int(result.group('dice_num') or 1)
dice_type = int(result.group('dice_type'))

# Dice can't have zero or a negative number of sides.
if dice_type <= 0:
bot.reply("I don't have any dice with %d sides. =(" % dice_type)
return None # Signal there was a problem

# Upper limit for dice should be at most a million. Creating a dict with
# more than a million elements already takes a noticeable amount of time
# on a fast computer and ~55kB of memory.
if dice_num > 1000:
return None
bot.reply('I only have 1000 dice. =(')
return None # Signal there was a problem

dice = DicePouch(dice_num, dice_type, 0)

Expand Down Expand Up @@ -171,13 +177,18 @@ def roll(bot, trigger):
# 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)
dice = list(map(_roll_dice, dice_expressions))

f = lambda dice_expr: _roll_dice (bot, dice_expr)
dice = list(map(f, dice_expressions))

if None in dice:
bot.reply("I only have 1000 dice. =(")
# Stop computing roll if there was a problem rolling dice.
return

def _get_eval_str(dice):
Expand Down

0 comments on commit 6a6cae2

Please sign in to comment.