Exemplo n.º 1
0
 def __init__(self, config=None, dir=None):
   madcow.Madcow.__init__(self, config, dir)
   self.colorlib = ColorLib('mirc')
   keys = silc.create_key_pair("silc.pub", "silc.priv", passphrase="")
   nick = self.config.silcplugin.nick
   silc.SilcClient.__init__(self, keys, nick, nick, nick)
   self.channels = self._delim.split(self.config.silcplugin.channels)
Exemplo n.º 2
0
class Main(Module):

    pattern = re.compile(r'^\s*(election|ev)\s*$', re.I)
    help = u'ev - current election 2008 vote prediction'
    _baseurl = u'http://www.electoral-vote.com/'
    _score_re = re.compile(r'<td class="score">(.*?)</td>', re.DOTALL)
    _dem_re = re.compile(r'<span class="dem">(.*?)\s+(\d+)')
    _gop_re = re.compile(r'<span class="gop">(.*?)\s+(\d+)')
    _tie_re = re.compile(r'(Ties)\s+(\d+)')

    def __init__(self, madcow=None):
        if madcow is not None:
            self.colorlib = madcow.colorlib
        else:
            self.colorlib = ColorLib(u'ansi')

    def colorize(self, color, key, val):
        if key == '_SEN!D':
            key = 'Democrats'
        elif key == '_SEN!R':
            key = 'Republicans'
        key = self.colorlib.get_color(color, text=key)
        return u'%s: %s' % (key, val)

    def response(self, nick, args, kwargs):
        try:
            page = geturl(self._baseurl)
            try:
                score = self._score_re.search(page).group(1)
                dem = self._dem_re.search(score).groups()
                gop = self._gop_re.search(score).groups()
                # XXX diebold patch :D
                #dem, gop = (dem[0], gop[1]), (gop[0], dem[1])
                tie = None
                try:
                    tie = self._tie_re.search(score).groups()
                except AttributeError:
                    pass
            except AttributeError:
                raise Exception(u"couldn't parse page")
            output = [self.colorize(u'blue', *dem), self.colorize(u'red', *gop)]
            if tie:
                output.append(self.colorize(u'white', *tie))
            return u'%s: Projected Senate Seats 2010: %s' % (
                    nick, u', '.join(output))
        except Exception, error:
            log.warn(u'error in module %s' % self.__module__)
            log.exception(error)
            return u'%s: %s' % (nick, error)
Exemplo n.º 3
0
Arquivo: irc.py Projeto: gipi/Richie
    def __init__(self, config=None, dir=None):
        Madcow.__init__(self, config=config, dir=dir)

        self.colorlib = ColorLib('mirc')
        if log.root.level <= log.DEBUG:
            irclib.DEBUG = 1
        else:
            irclib.DEBUG = 0
        self.irc = irclib.IRC()
        self.server = self.irc.server()
        for event in self.events:
            log.info('[IRC] * Registering event: %s' % event)
            self.server.add_global_handler(
                event,
                getattr(self, 'on_' + event),
                0,
            )
        if self.config.irc.channels is not None:
            self.channels = self._delim.split(self.config.irc.channels)
        else:
            self.channels = []
        self.names = {}
        self.last_names_update = unix_time()
Exemplo n.º 4
0
Arquivo: cli.py Projeto: gipi/Richie
class ConsoleProtocol(Madcow):
    _new_nick = re.compile(r'^\s*nick\s+(\S+)\s*$', re.I)
    _cli_usage = [
        'quit - quit madcow',
        'history - show history',
        'nick <nick> - change your nick',
        'clear - clear screen'
    ]
    _prompt = '\x1b[1;31m>>>\x1b[0m '
    _clear = '\x1b[H\x1b[J'

    def __init__(self, config=None, dir=None):
        self.colorlib = ColorLib('ansi')
        Madcow.__init__(self, config=config, dir=dir)
        self.user_nick = os.environ['USER']
        self.shell = Shell(polls=[self.check_response_queue])
        self.usageLines += self._cli_usage

    def run(self):
        self.output("type 'help' for a list of commands")
        while self.running:
            self.check_response_queue()
            try:
                input = self.shell.readline(self._prompt)
            except IOError:
                # this happens when you get EINTR from SIGHUP handling
                continue

            if input.lower() == 'quit':
                break

            if input.lower() == 'history':
                print 'history: %s' % repr(self.shell.history)

            if input.lower() == 'clear':
                sys.stdout.write(self._clear)
                continue

            if len(input) > 0:
                req = Request(message=input)
                req.nick = self.user_nick
                req.channel = 'cli'
                req.private = True
                req.addressed = True

                self.checkAddressing(req)

                if req.message.startswith('^'):
                    req.colorize = True
                    req.message = req.message[1:]

                try:
                    self.user_nick = self._new_nick.search(req.message).group(1)
                    self.output('nick changed to: %s' % self.user_nick, req)
                    continue
                except:
                    pass
                self.process_message(req)

    def protocol_output(self, message, req=None):
        if req is not None and req.colorize is True:
            message = self.colorlib.rainbow(message)
        print message
Exemplo n.º 5
0
Arquivo: cli.py Projeto: gipi/Richie
 def __init__(self, config=None, dir=None):
     self.colorlib = ColorLib('ansi')
     Madcow.__init__(self, config=config, dir=dir)
     self.user_nick = os.environ['USER']
     self.shell = Shell(polls=[self.check_response_queue])
     self.usageLines += self._cli_usage
Exemplo n.º 6
0
class ConsoleProtocol(Madcow):
    _new_nick = re.compile(r'^\s*nick\s+(\S+)\s*$', re.I)
    _cli_usage = [
        'quit - quit madcow', 'history - show history',
        'nick <nick> - change your nick', 'clear - clear screen'
    ]
    _prompt = '\x1b[1;31m>>>\x1b[0m '
    _clear = '\x1b[H\x1b[J'

    def __init__(self, config=None, dir=None):
        self.colorlib = ColorLib('ansi')
        Madcow.__init__(self, config=config, dir=dir)
        self.user_nick = os.environ['USER']
        self.shell = Shell(polls=[self.check_response_queue])
        self.usageLines += self._cli_usage

    def run(self):
        self.output("type 'help' for a list of commands")
        while self.running:
            self.check_response_queue()
            try:
                input = self.shell.readline(self._prompt)
            except IOError:
                # this happens when you get EINTR from SIGHUP handling
                continue

            if input.lower() == 'quit':
                break

            if input.lower() == 'history':
                print 'history: %s' % repr(self.shell.history)

            if input.lower() == 'clear':
                sys.stdout.write(self._clear)
                continue

            if len(input) > 0:
                req = Request(message=input)
                req.nick = self.user_nick
                req.channel = 'cli'
                req.private = True
                req.addressed = True

                self.checkAddressing(req)

                if req.message.startswith('^'):
                    req.colorize = True
                    req.message = req.message[1:]

                try:
                    self.user_nick = self._new_nick.search(
                        req.message).group(1)
                    self.output('nick changed to: %s' % self.user_nick, req)
                    continue
                except:
                    pass
                self.process_message(req)

    def protocol_output(self, message, req=None):
        if req is not None and req.colorize is True:
            message = self.colorlib.rainbow(message)
        print message
Exemplo n.º 7
0
 def __init__(self, config=None, dir=None):
     self.colorlib = ColorLib('ansi')
     Madcow.__init__(self, config=config, dir=dir)
     self.user_nick = os.environ['USER']
     self.shell = Shell(polls=[self.check_response_queue])
     self.usageLines += self._cli_usage
Exemplo n.º 8
0
 def __init__(self, madcow=None):
     if madcow is not None:
         self.colorlib = madcow.colorlib
     else:
         self.colorlib = ColorLib(u'ansi')
Exemplo n.º 9
0
class Main(Module):

    _allow = u'-?(?:[0-9.]+j?|pi|e)'
    _regex = u'^\s*roll\s+(%s?)d(%s)\s*$' % (_allow, _allow)
    pattern = re.compile(_regex, re.I)
    allow_threading = False
    require_addressing = True
    help = u'roll [<numdice>d<sides>] - roll die of the specified size'

    def __init__(self, madcow=None):
        if madcow is not None:
            self.colorlib = madcow.colorlib
        else:
            self.colorlib = ColorLib(u'ansi')

    def roll(self, min, max):
        if isinstance((min * max), (float, complex)):
            return random.uniform(min, max)
        else:
            return random.randint(min, max)

    def normalize(self, val):
        try:
            val = val.lower()
            if val == u'pi':
                val = math.pi
            elif val == u'e':
                val = math.e
            elif val.endswith(u'j'):
                val = complex(val)
            elif u'.' in val:
                val = float(val)
            else:
                val = int(val)
        except:
            val = 1
        return val

    def colorize(self, text, color):
        return self.colorlib.get_color(color, text=text)

    def response(self, nick, args, kwargs):
        num_dice = self.normalize(args[0])
        sides = self.normalize(args[1])

        if sides == 0 or num_dice == 0:
            return u'GOOD JOB, UNIVERSE %s' % self.colorize(u'EXPLODES', u'red')

        if sides == 1 and num_dice == 1:
            return u'CHEATING DETECTED, YOU %s' % self.colorize(u'DIE', u'red')

        min = num_dice
        max = num_dice * sides
        saving_throw = self.roll(min, max)
        save_versus = self.roll(min, max)

        try:
            if saving_throw >= save_versus:
                result = self.colorize(u'LIVES', u'green')
            else:
                result = self.colorize(u'DIES', u'red')
        except:
            result = self.colorize(u'IS TOO COMPLEX', u'yellow')

        return u'%s rolls %s, needs %s, %s %s' % (nick, saving_throw,
                save_versus, nick, result)
Exemplo n.º 10
0
class Main(Module):

    pattern = re.compile(r'^\s*wardb\s+(.+?)\s*$', re.I)
    require_addressing = True
    help = u'wardb <item> - look up warhammer item stats'

    _base_url = u'http://www.wardb.com/'
    _search_url = urljoin(_base_url, u'/search.aspx')
    _items_re = re.compile(r'\[([^\]]+)\]')
    _results_re = re.compile(
            r'<a href="([^"]+/item\.aspx[^"]+)">\s*(.+?)\s*</a>')
    _redirect_re = re.compile(
            r'self\.location="(item.aspx[^"]+)"')
    _bonus_re = re.compile(
            r"<span class='item-tooltip-bonus'>\s*([^<]+)\s*</span>")
    _stat_gap_re = re.compile(
            r'([+-])\s+(\d)')
    _item_name_re = re.compile(
            r'<span class="r(\d+) item-name">([^<]+)</span>')

    _rarity_colors = {
            u'6': u'orange',
            u'5': u'bright magenta',
            u'4': u'bright blue',
            u'3': u'bright green',
            u'2': u'white',
            u'1': u'light gray'}

    def __init__(self, madcow=None):
        self.madcow = madcow
        if madcow:
            self.colorlib = madcow.colorlib
        else:
            self.colorlib = ColorLib(u'ansi')

    def lookup_item(self, item):
        page = geturl(self._search_url, opts={u'search_text': item})
        item = item.lower()
        redirect = self._redirect_re.search(page)
        if redirect:
            url = urljoin(self._base_url, redirect.group(1))
            page = geturl(url)
        elif u'Search results for' in page:
            items = self._results_re.findall(page)
            if not items:
                return
            items = [(v.lower(), k) for k, v in items]
            items = sorted(items)
            map = dict(items)
            if item in map:
                url = map[item]
            else:
                url = items[0][1]
            page = geturl(url)
        bonus = u', '.join(self._bonus_re.findall(page))
        bonus = self._stat_gap_re.sub(r'\1\2', bonus)
        if not bonus:
            bonus = u'No bonuses'
        rarity, name = self._item_name_re.search(page).groups()
        color = self._rarity_colors[rarity]
        name = name.replace('\\', '')
        name = name.strip()
        name = self.colorlib.get_color(color, text=name)
        return u'%s: %s' % (name, bonus)

    def response(self, nick, args, kwargs):
        try:
            return self.lookup_item(args[0])
        except Exception, error:
            log.warn('error in module %s' % self.__module__)
            log.exception(error)