Brian S. Stephan
76bcdd5fef
with the discord-irc bridge in play, the bot was sending all !roll results to the bridge user, which wasn't all that useful
81 lines
2.6 KiB
Python
81 lines
2.6 KiB
Python
"""Roll dice when asked, intended for RPGs."""
|
||
import logging
|
||
import random
|
||
import re
|
||
|
||
from django.conf import settings
|
||
|
||
from irc.client import NickMask
|
||
|
||
from dice.roller import DiceRoller
|
||
from ircbot.lib import Plugin
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class Dice(Plugin):
|
||
"""Roll simple or complex dice strings."""
|
||
|
||
def __init__(self, bot, connection, event):
|
||
"""Set up the plugin."""
|
||
self.roller = DiceRoller()
|
||
|
||
super(Dice, self).__init__(bot, connection, event)
|
||
|
||
def start(self):
|
||
"""Set up the handlers."""
|
||
self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!roll\s+(.*)$',
|
||
self.handle_roll, -20)
|
||
self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!random\s+(.*)$',
|
||
self.handle_random, -20)
|
||
|
||
super(Dice, self).start()
|
||
|
||
def stop(self):
|
||
"""Tear down handlers."""
|
||
self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_roll)
|
||
self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_random)
|
||
|
||
super(Dice, self).stop()
|
||
|
||
def handle_random(self, connection, event, match):
|
||
"""Handle the !random command which picks an item from a list."""
|
||
nick = NickMask(event.source).nick
|
||
choices = match.group(1)
|
||
|
||
choices_list = choices.split(' ')
|
||
choice = random.SystemRandom().choice(choices_list)
|
||
|
||
logger.debug(event.recursing)
|
||
if event.recursing:
|
||
reply = "{0:s}".format(choice)
|
||
elif settings.DICE_PREFIX_ROLLER:
|
||
reply = "{0:s}: {1:s}".format(nick, choice)
|
||
else:
|
||
reply = "{0:s}".format(choice)
|
||
return self.bot.reply(event, reply)
|
||
|
||
def handle_roll(self, connection, event, match):
|
||
"""Handle the !roll command which covers most common dice stuff."""
|
||
nick = NickMask(event.source).nick
|
||
dicestr = match.group(1)
|
||
|
||
logger.debug(event.recursing)
|
||
try:
|
||
reply_str = self.roller.do_roll(dicestr)
|
||
except AssertionError as aex:
|
||
reply_str = f"Could not roll dice: {aex}"
|
||
except ValueError:
|
||
reply_str = "Unable to parse roll"
|
||
|
||
if event.recursing:
|
||
reply = "{0:s}".format(reply_str)
|
||
elif settings.DICE_PREFIX_ROLLER:
|
||
reply = "{0:s}: {1:s}".format(nick, reply_str)
|
||
else:
|
||
reply = "{0:s}".format(reply_str)
|
||
return self.bot.reply(event, re.sub(r'(\d+)(.*?\s+)(\(.*?\))', r'\1\214\3', reply))
|
||
|
||
|
||
plugin = Dice
|