コード例 #1
0
ファイル: weather.py プロジェクト: Jzarecta/madcow
class Main(Module):

    pattern = re.compile(u"^\s*(fc|forecast|weather|ws|pws)(?:\s+(.*)$)?")
    require_addressing = True
    help = u"fc|forecast, ws|weather, pws [zipcode|city,state|city,country|pws] - look up weather forecast/conditions"
    error = u"Couldn't find that place, maybe a bomb dropped on it"

    def init(self):
        colorlib = self.madcow.colorlib
        self.weather = Weather(colorlib, self.log)
        self.learn = Learn(madcow=self.madcow)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        query = args[1]

        if not query:
            location = self.learn.lookup("location", nick)
        elif query.startswith("@"):
            location = self.learn.lookup("location", query[1:])
        else:
            location = query
        if location:
            if cmd in ("fc", "forecast"):
                message = self.weather.forecast(location)
            elif cmd in ("weather", "ws"):
                message = self.weather.official_station(location)
            elif cmd == "pws":
                message = self.weather.personal_station(location)
        else:
            message = u"I couldn't look that up"
        return u"%s: %s" % (nick, message)
コード例 #2
0
class Main(Module):

    pattern = re.compile(u'^\s*(?:fc|forecast|weather)(?:\s+(.*)$)?')
    require_addressing = True
    help = u'fc [location] - look up weather forecast'
    error = u"Couldn't find that place, maybe a bomb dropped on it"

    def init(self):
        colorlib = self.madcow.colorlib
        self.weather = Weather(colorlib)
        self.learn = Learn(madcow=self.madcow)

    def response(self, nick, args, kwargs):
        query = args[0]
        if not query:
            location = self.learn.lookup('location', nick)
        elif query.startswith('@'):
            location = self.learn.lookup('location', query[1:])
        else:
            location = query
        if location:
            message = self.weather.forecast(location)
        else:
            message = u"I couldn't look that up"
        return u'%s: %s' % (nick, message)
コード例 #3
0
ファイル: weather.py プロジェクト: seunboi4u/madcow
class Main(Module):

    pattern = re.compile(u'^\s*(fc|forecast|weather|ws|pws)(?:\s+(.*)$)?')
    require_addressing = True
    help = u'fc|forecast, ws|weather, pws [zipcode|city,state|city,country|pws] - look up weather forecast/conditions'
    error = u"Couldn't find that place, maybe a bomb dropped on it"

    def init(self):
        colorlib = self.madcow.colorlib
        self.weather = Weather(colorlib, self.log)
        self.learn = Learn(madcow=self.madcow)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        query = args[1]

        if not query:
            location = self.learn.lookup('location', nick)
        elif query.startswith('@'):
            location = self.learn.lookup('location', query[1:])
        else:
            location = query
        if location:
            if cmd in ('fc', 'forecast'):
                message = self.weather.forecast(location)
            elif cmd in ('weather', 'ws'):
                message = self.weather.official_station(location)
            elif cmd == 'pws':
                message = self.weather.personal_station(location)
        else:
            message = u"I couldn't look that up"
        return u'%s: %s' % (nick, message)
コード例 #4
0
class Main(Module):
    pattern = re.compile('^\s*(?:fc|forecast|weather)(?:\s+(.*)$)?')
    require_addressing = True
    help = 'fc [location] - look up weather forecast'

    def __init__(self, madcow=None):
        self.weather = Weather()
        try:
            self.learn = Learn(madcow=madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):

        try:
            args = args[0]
        except:
            args = None

        if args is None or args == '' and self.learn:
            query = self.learn.lookup('location', nick)
        elif args.startswith('@') and self.learn:
            query = self.learn.lookup('location', args[1:])
        else:
            query = args

        if query is None or query == '':
            return '%s: unknown nick. %s' % (nick, __usage__)

        try:
            return '%s: %s' % (nick, self.weather.forecast(query))
        except Exception, e:
            log.warn('error in %s: %s' % (self.__module__, e))
            log.exception(e)
            return "Couldn't find that place, maybe a bomb dropped on it"
コード例 #5
0
class Main(Module):
    pattern = re.compile(u'^\s*(nb|notes?)(?:\s+(.*)$)?')
    require_addressing = True
    dbname = u'note'
    help = u'notes|nb <nick>                        show notes associated to a nick (staff only)\n\
notes|nb <nick> <note>                 add a note to a nick (staff only)'

    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)

    def set(self, nick, target_nick, note):
        d = datetime.now()
        # append notes, don't overwrite
        old_notes = self.learn.lookup(self.dbname, target_nick)
        notes = old_notes if old_notes else ""
        self.learn.set(
            self.dbname, target_nick.lower(),
            notes + '\n[' + d.strftime("%D") + '] [' + nick + '] ' + note)

    def get(self, target_nick):
        return self.learn.lookup(self.dbname, target_nick)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        note = False
        params = []
        if args[1]:
            params = args[1].partition(' ')

        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False

        try:
            note = params[2]
        except IndexError:
            note = False
        """ if nick passed, set user as staff """
        if target_nick and (self.staff.is_staff(nick)
                            or settings.OWNER_NICK == nick):
            if note:
                self.set(nick=nick, target_nick=target_nick, note=note)
                return u'%s: Note added to %s\'s record.' % (nick, target_nick)
            else:
                notes = self.get(target_nick=target_nick)
                if notes:
                    return u'%s: Staff notes on %s\n%s' % (nick, target_nick,
                                                           notes)
                else:
                    return u'%s: No notes found for %s' % (nick, target_nick)
コード例 #6
0
ファイル: notes.py プロジェクト: Havvy/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(nb|notes?)(?:\s+(.*)$)?')
    require_addressing = True
    dbname = u'note'
    help = u'notes|nb <nick>                        show notes associated to a nick (staff only)\n\
notes|nb <nick> <note>                 add a note to a nick (staff only)'
    
    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)
        
    def set(self, nick, target_nick, note):
        d = datetime.now()
        # append notes, don't overwrite
        old_notes = self.learn.lookup(self.dbname, target_nick) 
        notes = old_notes if old_notes else ""
        self.learn.set(self.dbname, target_nick.lower(), notes + '\n[' + d.strftime("%D") + '] [' + nick + '] ' + note)
        
    def get(self, target_nick):
        return self.learn.lookup(self.dbname, target_nick)
        
    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        note = False
        params = []
        if args[1]:
            params = args[1].partition(' ')
        
        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False
            
        try:
            note = params[2]
        except IndexError:
            note = False

        """ if nick passed, set user as staff """
        if target_nick and (self.staff.is_staff(nick) or settings.OWNER_NICK == nick):
            if note:
                self.set(nick=nick, target_nick=target_nick, note=note)
                return u'%s: Note added to %s\'s record.' % (nick, target_nick)
            else:
                notes = self.get(target_nick=target_nick)
                if notes:
                    return u'%s: Staff notes on %s\n%s' % (nick, target_nick, notes)
                else:
                    return u'%s: No notes found for %s' % (nick, target_nick)
コード例 #7
0
ファイル: karma.py プロジェクト: gipi/Richie
class Karma(Base):
    """Infobot style karma"""

    _adjust_pattern = re.compile(r"^\s*(.*?)[+-]([+-]+)\s*$")
    _query_pattern = re.compile(r"^\s*karma\s+(\S+)\s*\?*\s*$")
    _dbname = "karma"

    def __init__(self, madcow):
        self.learn = Learn(madcow)

    def process(self, nick, input):
        kr = KarmaResponse(reply=None, matched=False)

        # see if someone is trying to adjust karma
        try:
            target, adjustment = Karma._adjust_pattern.search(input).groups()
            # don't let people adjust their own karma ;p
            if nick.lower() != target.lower():
                self.adjust(nick=target, adjustment=adjustment)
            kr.matched = True
        except:
            pass

        # detect a query for someone's karma
        try:
            target = Karma._query_pattern.search(input).group(1)
            karma = self.query(nick=target)
            kr.matched = True
            kr.reply = "%s: %s's karma is %s" % (nick, target, karma)
        except:
            pass

        return kr

    def set(self, nick, karma):
        self.learn.set(Karma._dbname, nick.lower(), str(karma))

    def adjust(self, nick, adjustment):
        karma = self.query(nick)
        adjustment, size = adjustment[0], len(adjustment)
        exec("karma " + adjustment + "= size")
        self.set(nick=nick, karma=karma)

    def query(self, nick):
        karma = self.learn.lookup(Karma._dbname, nick.lower())
        if karma is None:
            karma = 0
            self.set(nick=nick, karma=karma)
        return int(karma)
コード例 #8
0
ファイル: karma.py プロジェクト: seunboi4u/madcow
class Karma(object):
    """Infobot style karma"""

    _adjust_pattern = re.compile(r'^\s*(.*?)[+-]([+-]+)\s*$')
    _query_pattern = re.compile(r'^\s*karma\s+(\S+)\s*\?*\s*$')
    _dbname = u'karma'

    def __init__(self, madcow):
        self.learn = Learn(madcow)

    def process(self, nick, input):
        kr = KarmaResponse(reply=None, matched=False)

        # see if someone is trying to adjust karma
        try:
            target, adjustment = Karma._adjust_pattern.search(input).groups()
            # don't let people adjust their own karma ;p
            if nick.lower() != target.lower():
                self.adjust(nick=target, adjustment=adjustment)
            kr.matched = True
        except AttributeError:
            pass

        # detect a query for someone's karma
        try:
            target = Karma._query_pattern.search(input).group(1)
            karma = self.query(nick=target)
            kr.matched = True
            kr.reply = u"%s: %s's karma is %s" % (nick, target, karma)
        except AttributeError:
            pass
        return kr

    def set(self, nick, karma):
        self.learn.set(Karma._dbname, nick.lower(), unicode(karma))

    def adjust(self, nick, adjustment):
        karma = self.query(nick)
        adjustment, size = adjustment[0], len(adjustment)
        exec(u'karma ' + adjustment + u'= size')
        self.set(nick=nick, karma=karma)

    def query(self, nick):
        karma = self.learn.lookup(Karma._dbname, nick.lower())
        if karma is None:
            karma = 0
            self.set(nick=nick, karma=karma)
        return int(karma)
コード例 #9
0
ファイル: summon.py プロジェクト: gipi/Richie
class Main(Module):
    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = 'summon <nick> [reason] - summon user'

    def __init__(self, madcow):
        self.learn = Learn(madcow)
        self.config = madcow.config

    def response(self, nick, args, kwargs):
        try:
            sendto, reason = args
            email = self.learn.lookup('email', sendto)
            if email is None:
                return "%s: I don't know the email for %s" % (nick, sendto)
            body = 'To: %s <%s>\n' % (sendto, email)
            body += 'From: %s\n' % (self.config.smtp.sender)
            body += 'Subject: Summon from %s' % nick
            body += '\n'
            body += 'You were summoned by %s. Reason: %s' % (nick, reason)

            smtp = SMTP(self.config.smtp.server)
            if len(self.config.smtp.user):
                smtp.login(self.config.smtp.user, self.config.smtp.password)
            smtp.sendmail(self.config.smtp.sender, [email], body)

            return "%s: summoned %s" % (nick, sendto)

        except Exception, e:
            log.warn('error in %s: %s' % (self.__module__, e))
            log.exception(e)
            return "%s: I couldn't make that summon: %s" % (nick, e)
コード例 #10
0
 def init(self):
     self.colorlib = self.madcow.colorlib
     try:
         self.learn = Learn(madcow=madcow)
     except:
         self.learn = None
     self.google = Google()
コード例 #11
0
ファイル: summon.py プロジェクト: gipi/Richie
class Main(Module):
    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = 'summon <nick> [reason] - summon user'

    def __init__(self, madcow):
        self.learn = Learn(madcow)
        self.config = madcow.config

    def response(self, nick, args, kwargs):
        try:
            sendto, reason = args
            email = self.learn.lookup('email', sendto)
            if email is None:
                return "%s: I don't know the email for %s" % (nick, sendto)
            body = 'To: %s <%s>\n' % (sendto, email)
            body += 'From: %s\n' % (self.config.smtp.sender)
            body += 'Subject: Summon from %s' % nick
            body += '\n'
            body += 'You were summoned by %s. Reason: %s' % (nick, reason)

            smtp = SMTP(self.config.smtp.server)
            if len(self.config.smtp.user):
                smtp.login(self.config.smtp.user, self.config.smtp.password)
            smtp.sendmail(self.config.smtp.sender, [email], body)

            return "%s: summoned %s" % (nick, sendto)

        except Exception, e:
            log.warn('error in %s: %s' % (self.__module__, e))
            log.exception(e)
            return "%s: I couldn't make that summon: %s" % (nick, e)
コード例 #12
0
ファイル: sunrise.py プロジェクト: cjones/madcow
class Main(Module):

    pattern = re.compile(r'^\s*(sunrise|sunset)(?:\s+(@?)(.+?))?\s*$', re.I)
    help = '(sunrise|sunset) [location|@nick] - get time of sun rise/set'
    error = u"That place doesn't have a sun, sorry"

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=madcow)
        except:
            self.learn = None
        self.google = Google()

    def response(self, nick, args, kwargs):
        query, args = args[0], args[1:]
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.google.sunrise_sunset(query, location)
        return u'%s: %s' % (nick, response)
コード例 #13
0
class Main(Module):

    pattern = re.compile(r'^\s*(sunrise|sunset)(?:\s+(@?)(.+?))?\s*$', re.I)
    help = '(sunrise|sunset) [location|@nick] - get time of sun rise/set'
    error = u"That place doesn't have a sun, sorry"

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=madcow)
        except:
            self.learn = None
        self.google = Google()

    def response(self, nick, args, kwargs):
        query, args = args[0], args[1:]
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.google.sunrise_sunset(query, location)
        return u'%s: %s' % (nick, response)
コード例 #14
0
ファイル: summon.py プロジェクト: Havvy/madcow
class Main(Module):

    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = u'summon <nick> [reason] - summon user'
    error = u"I couldn't make that summon"

    def init(self):
        self.learn = Learn(self.madcow)

    def response(self, nick, args, kwargs):
        sendto, reason = args
        email = self.learn.lookup('email', sendto)
        if email is None:
            return u"%s: I don't know the email for %s" % (nick, sendto)
        body = u'\n'.join((u'To: %s <%s>' % (sendto, email),
                           u'From: ' + settings.SMTP_FROM,
                           u'Subject: Summon from ' + nick,
                           u'',
                           u'You were summoned by %s. Reason: %s' % (nick, reason)))
        smtp = SMTP(settings.SMTP_SERVER)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        if settings.SMTP_USER and settings.SMTP_PASS:
            smtp.login(settings.SMTP_USER, settings.SMTP_PASS)
        smtp.sendmail(settings.SMTP_FROM, [encode(email, 'ascii')], encode(body))
        return u"%s: summoned %s" % (nick, sendto)
コード例 #15
0
ファイル: sunrise.py プロジェクト: cjones/madcow
 def init(self):
     self.colorlib = self.madcow.colorlib
     try:
         self.learn = Learn(madcow=madcow)
     except:
         self.learn = None
     self.google = Google()
コード例 #16
0
class Main(Module):

    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = u'summon <nick> [reason] - summon user'
    error = u"I couldn't make that summon"

    def init(self):
        self.learn = Learn(self.madcow)

    def response(self, nick, args, kwargs):
        sendto, reason = args
        email = self.learn.lookup(u'email', sendto)
        if email is None:
            return u"%s: I don't know the email for %s" % (nick, sendto)

        # just make all this shit ASCII, email is best that way...
        email = email.encode('ascii', 'replace')
        if reason:
            reason = reason.encode('ascii', 'replace')
        anick = nick.encode('ascii', 'replace')

        body = 'To: %s <%s>\n' % (sendto.encode('ascii', 'replace'), email)
        body += 'From: %s\n' % settings.SMTP_FROM
        body += 'Subject: Summon from %s' % anick
        body += '\n'
        body += 'You were summoned by %s. Reason: %s' % (anick, reason)

        smtp = SMTP(settings.SMTP_SERVER)
        if settings.SMTP_USER and settings.SMTP_PASS:
            smtp.login(settings.SMTP_USER, settings.SMTP_PASS)
        smtp.sendmail(settings.SMTP_FROM, [email], body)

        return u"%s: summoned %s" % (nick, sendto)
コード例 #17
0
ファイル: summon.py プロジェクト: seunboi4u/madcow
class Main(Module):

    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = u'summon <nick> [reason] - summon user'
    error = u"I couldn't make that summon"

    def init(self):
        self.learn = Learn(self.madcow)

    def response(self, nick, args, kwargs):
        sendto, reason = args
        email = self.learn.lookup('email', sendto)
        if email is None:
            return u"%s: I don't know the email for %s" % (nick, sendto)
        body = u'\n'.join(
            (u'To: %s <%s>' % (sendto, email), u'From: ' + settings.SMTP_FROM,
             u'Subject: Summon from ' + nick, u'',
             u'You were summoned by %s. Reason: %s' % (nick, reason)))
        smtp = SMTP(settings.SMTP_SERVER)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        if settings.SMTP_USER and settings.SMTP_PASS:
            smtp.login(settings.SMTP_USER, settings.SMTP_PASS)
        smtp.sendmail(settings.SMTP_FROM, [encode(email, 'ascii')],
                      encode(body))
        return u"%s: summoned %s" % (nick, sendto)
コード例 #18
0
ファイル: yelp.py プロジェクト: compbrain/madcow
 def __init__(self, madcow=None):
     try:
         self.default_location = madcow.config.yelp.default_location
     except:
         self.default_location = DEFAULT_LOCATION
     try:
         self.learn = Learn(madcow=madcow)
     except:
         self.learn = None
コード例 #19
0
ファイル: yelp.py プロジェクト: Spacexplosion/Quaking-Mad-Cow
 def init(self):
     try:
         self.default_location = settings.YELP_DEFAULT_LOCATION
     except:
         self.default_location = DEFAULT_LOCATION
     try:
         self.learn = Learn(madcow=self.madcow)
     except:
         self.learn = None
コード例 #20
0
ファイル: weather.py プロジェクト: compbrain/madcow
 def __init__(self, madcow=None):
     if madcow is not None:
         colorlib = madcow.colorlib
     else:
         colorlib = ColorLib(u'ansi')
     self.weather = Weather(colorlib)
     try:
         self.learn = Learn(madcow=madcow)
     except:
         self.learn = None
コード例 #21
0
ファイル: yelp.py プロジェクト: compbrain/madcow
class Main(Module):

    pattern = re.compile(r'^\s*yelp\s+(.+?)(?:\s+@(.+))?\s*$', re.I)
    help = 'yelp <name> [@location] - restaraunt reviews'

    def __init__(self, madcow=None):
        try:
            self.default_location = madcow.config.yelp.default_location
        except:
            self.default_location = DEFAULT_LOCATION
        try:
            self.learn = Learn(madcow=madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):
        try:
            # sanity check args and pick default search location
            desc, loc = args
            if desc.startswith('@') and not loc:
                raise Exception('invalid search')
            if not loc:
                if self.learn:
                    loc = self.learn.lookup(u'location', nick)
                if not loc:
                    loc = self.default_location

            # perform search
            opts = opts={'find_desc': desc, 'ns': 1, 'find_loc': loc, 'rpp': 1}
            page = geturl(SEARCHURL, opts)

            # extract meaningful data from first result
            soup = BeautifulSoup(page, convertEntities='html')
            result = soup.body.find('div', 'businessresult clearfix')
            name = result.find('a', id='bizTitleLink0').findAll(text=True)
            name = clean_re.search(u''.join(name)).group(1)
            cat = result.find('div', 'itemcategories').a.renderContents()
            rating = result.find('div', 'rating').img['alt']
            rating = rating.replace(' star rating', '')
            reviews = result.find('a', 'reviews')
            url = urljoin(BASEURL, reviews['href'])
            reviews = reviews.renderContents()
            address = [i.strip() for i in result.address.findAll(text=True)]
            address = u', '.join(part for part in address if part)

            # return rendered page
            return RESULT_FMT % {'nick': nick, 'name': name, 'cat': cat,
                                 'rating': rating, 'reviews': reviews,
                                 'address': address, 'url': url}

        except Exception, error:
            log.warn('error in module %s' % self.__module__)
            log.exception(error)
            return u"%s: I couldn't look that up" % nick
コード例 #22
0
ファイル: wunderground.py プロジェクト: seunboi4u/madcow
    def init(self):
        opts = {}
        for key, default in self.defaults.iteritems():
            setting = 'WUNDERGROUND_' + key.upper()
            val = getattr(settings, setting, None)
            if val is None:
                val = default
            opts[key] = val

        self.api = WeatherUnderground(log=self.madcow.log, **opts)
        self.learn = Learn(madcow=self.madcow)
        self.method_triggers = [(getattr(self.api, method_name), triggers, pws)
                                for method_name, triggers, pws in self._method_triggers]
コード例 #23
0
ファイル: weather.py プロジェクト: compbrain/madcow
class Main(Module):

    pattern = re.compile(u'^\s*(?:fc|forecast|weather)(?:\s+(.*)$)?')
    require_addressing = True
    help = u'fc [location] - look up weather forecast'

    def __init__(self, madcow=None):
        if madcow is not None:
            colorlib = madcow.colorlib
        else:
            colorlib = ColorLib(u'ansi')
        self.weather = Weather(colorlib)
        try:
            self.learn = Learn(madcow=madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):

        args = args[0] if args else None

        if not args and self.learn:
            query = self.learn.lookup(u'location', nick)
        elif args.startswith(u'@') and self.learn:
            query = self.learn.lookup(u'location', args[1:])
        else:
            query = args

        if not query:
            return u'%s: unknown nick. %s' % (nick, USAGE)

        try:
            return u'%s: %s' % (nick, self.weather.forecast(query))
        except Exception, error:
            log.warn(u'error in module %s' % self.__module__)
            log.exception(error)
            return u"Couldn't find that place, maybe a bomb dropped on it"
コード例 #24
0
ファイル: noaa.py プロジェクト: seunboi4u/madcow
class Main(Module):

    pattern = re.compile(r'^\s*noaa(?:\s+(@?)(.+?))?\s*$', re.I)
    help = 'noaa [location|@nick] - alternative weather (us only)'
    noaa_url = 'http://www.weather.gov/'
    noaa_search = 'http://forecast.weather.gov/zipcity.php'
    error = 'Something bad happened'
    fc_re = re.compile(r'^myforecast-current')

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=self.madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.getweather(location)
        if not response:
            response = self.error
        return u'%s: %s' % (nick, response)

    def getweather(self, location):
        """Look up NOAA weather"""
        soup = getsoup(self.noaa_search, {'inputstring': location},
                       referer=self.noaa_url)
        return u' / '.join(
            map(self.render, soup.findAll(attrs={'class': self.fc_re})))

    @staticmethod
    def render(node):
        data = strip_html(decode(node.renderContents(), 'utf-8'))
        return data.strip()
コード例 #25
0
ファイル: summon.py プロジェクト: compbrain/madcow
class Main(Module):

    pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$')
    require_addressing = True
    help = u'summon <nick> [reason] - summon user'

    def __init__(self, madcow):
        self.learn = Learn(madcow)
        self.config = madcow.config

    def response(self, nick, args, kwargs):
        try:
            sendto, reason = args
            email = self.learn.lookup(u'email', sendto)
            if email is None:
                return u"%s: I don't know the email for %s" % (nick, sendto)

            # just make all this shit ASCII, email is best that way...
            email = email.encode('ascii', 'replace')
            if reason:
                reason = reason.encode('ascii', 'replace')
            anick = nick.encode('ascii', 'replace')

            body = 'To: %s <%s>\n' % (sendto.encode('ascii', 'replace'), email)
            body += 'From: %s\n' % (self.config.smtp.sender)
            body += 'Subject: Summon from %s' % anick
            body += '\n'
            body += 'You were summoned by %s. Reason: %s' % (anick, reason)

            smtp = SMTP(self.config.smtp.server)
            if len(self.config.smtp.user):
                smtp.login(self.config.smtp.user, self.config.smtp.password)
            smtp.sendmail(self.config.smtp.sender, [email], body)

            return u"%s: summoned %s" % (nick, sendto)

        except Exception, error:
            log.warn(u'error in module %s' % self.__module__)
            log.exception(error)
            return u"%s: I couldn't make that summon: %s" % (nick, error)
コード例 #26
0
ファイル: xray.py プロジェクト: seunboi4u/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(xray)(?:\s+(.*)$)?')
    require_addressing = False
    help = u'xray <nick>        show all staff-accessible data for <nick> (staff only)'
    
    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)
        self.company = Company(madcow=self.madcow)
        self.realname = Realname(madcow=self.madcow)
        self.notes = Notes(madcow=self.madcow)
    
    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = args[1].strip()
        real_name = False
        
        # only staff members & bot owner are allowed to get xray data
        if self.staff.is_staff(nick) or settings.OWNER_NICK == nick:
            if target_nick:
                name = self.realname.get(target_nick);
                company = self.company.get(target_nick);
                notes = self.notes.get(target_nick);
                email = self.learn.lookup('email', target_nick)
                summary = ''
                if name:
                    summary = summary + 'Name: ' + name + '\n'
                if email:
                    summary = summary + 'Email: ' + email + '\n'
                if company:
                    summary = summary + 'Company: ' + company + '\n'
                if notes:
                    summary = summary + u'=' * 75 + notes + '\n'
                if summary:
                    return u'%s: Here\'s the skinny on %s\n\n%s' % (nick, target_nick, summary)
                else:
                    return u'%s: No data found for %s' % (nick, target_nick)
            else:
                return u'%s: xray only works if you tell me who to scan.' % (nick)
コード例 #27
0
ファイル: noaa.py プロジェクト: Havvy/madcow
class Main(Module):

    pattern = re.compile(r'^\s*noaa(?:\s+(@?)(.+?))?\s*$', re.I)
    help = 'noaa [location|@nick] - alternative weather (us only)'
    noaa_url = 'http://www.weather.gov/'
    noaa_search = 'http://forecast.weather.gov/zipcity.php'
    error = 'Something bad happened'
    fc_re = re.compile(r'^myforecast-current')

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=self.madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.getweather(location)
        if not response:
            response = self.error
        return u'%s: %s' % (nick, response)

    def getweather(self, location):
        """Look up NOAA weather"""
        soup = getsoup(self.noaa_search, {'inputstring': location}, referer=self.noaa_url)
        return u' / '.join(map(self.render, soup.findAll(attrs={'class': self.fc_re})))

    @staticmethod
    def render(node):
        data = strip_html(decode(node.renderContents(), 'utf-8'))
        return data.strip()
コード例 #28
0
class Main(Module):
    pattern = re.compile(u'^\s*(staff)(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'staff'
    help = u'staff                          list staff members\n\
staff <nick>                   check if specific user is a staff member\n\
staff <nick> add/remove        add/remove user from staff list (staff only)'

    def init(self):
        self.learn = Learn(madcow=self.madcow)

    def set(self, nick):
        self.learn.set(self.dbname, nick.lower(), True)

    def unset(self, nick):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(nick.lower())
            if dbm.has_key(key):
                del dbm[key]
                return True
            return False
        finally:
            dbm.close()

    def get_staff(self):
        staff_db = self.learn.get_db('staff')
        return staff_db

    def is_staff(self, nick):
        staff_db = self.get_staff()
        return nick in staff_db

    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        action = False
        params = []
        if args[1]:
            params = args[1].split()
        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False

        try:
            action = params[1]
        except IndexError:
            action = False
        """ if nick passed, set user as staff """
        if target_nick:
            # if an action is passed, and requesting user is staff or owner, perform the action
            if action and (self.is_staff(nick) or settings.OWNER_NICK == nick):
                if action == 'remove':
                    self.unset(nick=target_nick)
                    return u'%s: %s is no longer marked as staff' % (
                        nick, target_nick)
                elif action == "add":
                    self.set(nick=target_nick)
                    return u'%s: %s is now marked as staff' % (nick,
                                                               target_nick)
                else:
                    return u'%s: I\'m not sure what you want me to do here. \'%s\' is not a valid staff action.' % (
                        nick, action)

            # otherwise, respond with staff membership status for nick, ignoring the action
            if self.is_staff(target_nick):
                return u'%s: Yes, %s is a staff member' % (nick, target_nick)
            else:
                return u'%s: No, %s is not a staff member' % (nick,
                                                              target_nick)
        else:
            staff_db = self.get_staff()
            staff_nicks = staff_db.keys()
            if len(staff_nicks):
                return u'%s: Staff members are: %s' % (nick,
                                                       ", ".join(staff_nicks))
            else:
                return u'%s: There are currently no users marked as staff members.' % (
                    nick)
コード例 #29
0
 def __init__(self, madcow=None):
     self.weather = Weather()
     try:
         self.learn = Learn(madcow=madcow)
     except:
         self.learn = None
コード例 #30
0
ファイル: xray.py プロジェクト: seunboi4u/madcow
 def init(self):
     self.learn = Learn(madcow=self.madcow)
     self.staff = Staff(madcow=self.madcow)
     self.company = Company(madcow=self.madcow)
     self.realname = Realname(madcow=self.madcow)
     self.notes = Notes(madcow=self.madcow)
コード例 #31
0
ファイル: karma.py プロジェクト: seunboi4u/madcow
 def __init__(self, madcow):
     self.learn = Learn(madcow)
コード例 #32
0
ファイル: company.py プロジェクト: Havvy/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(compan[y|ies])(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'company'
    help = u'companies                          list all company/nick associations (staff only)\n\
company <nick>                     show company associated with user (staff only)\n\
company <nick> <company_name>      set company information for user (staff only)'
    
    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)
        
    def set(self, nick, company):
        self.learn.set(self.dbname, nick.lower(), company)
        
    def unset(self, nick):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(nick.lower())
            if dbm.has_key(nick):
                del dbm[nick]
                return True
            return False
        finally:
            dbm.close()
    
    def get_companies(self):
        company_db = self.learn.get_db('company');
        return company_db
    
    def has_company(self, nick):
        company_db = self.get_companies()
        return nick in company_db
   
    def get(self, nick):
        return self.learn.lookup(self.dbname, nick)
    
    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        company = False
        params = []
        if args[1]:
            params = args[1].partition(' ')
        
        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False
            
        try:
            company = params[2]
        except IndexError:
            company = False
            
        # only staff members & bot owner are allowed to get & set company data
        if self.staff.is_staff(nick) or settings.OWNER_NICK == nick:
            if target_nick:
                if company:
                    self.set(target_nick, company)
                    return u'%s: setting company for %s to %s' % ( nick, target_nick, company )
                else:
                    company_name = self.get(target_nick)
                    if company_name:
                        return u'%s: %s works at %s' % ( nick, target_nick, company_name )
                    else:
                        return u'%s: I don\'t know where %s works' % ( nick, target_nick )
            else:
                company_list = "\n\nRecorded companies:\n"
                for user_nick, company_name in self.get_companies().iteritems():
                    company_list = company_list + user_nick + " works at " + company_name + "\n"
                return u'%s: %s' % (nick, company_list)
コード例 #33
0
ファイル: summon.py プロジェクト: gipi/Richie
 def __init__(self, madcow):
     self.learn = Learn(madcow)
     self.config = madcow.config
コード例 #34
0
ファイル: realname.py プロジェクト: Havvy/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(names?)(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'realname'
    help = u'names                          show list of associated nicks and names (staff only)\n\
name <nick>                    show real name associated with user (staff only)\n\
name <nick> <real_name>        set real name for user (staff only)'
    
    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)
        
    def set(self, nick, name):
        self.learn.set(self.dbname, nick.lower(), name)
        
    def unset(self, nick):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(nick.lower())
            if dbm.has_key(nick):
                del dbm[nick]
                return True
            return False
        finally:
            dbm.close()
    
    def get_names(self):
        name_db = self.learn.get_db('realname');
        return name_db
    
    def has_name(self, nick):
        name_db = self.get_names()
        return nick in name_db
   
    def get(self, nick):
        return self.learn.lookup(self.dbname, nick)
    
    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        real_name = False
        params = []
        if args[1]:
            params = args[1].partition(' ')
        
        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False
            
        try:
            real_name = params[2]
        except IndexError:
            real_name = False
            
        # only staff members & bot owner are allowed to get & set real_name data
        if self.staff.is_staff(nick) or settings.OWNER_NICK == nick:
            if target_nick:
                if real_name:
                    self.set(target_nick, real_name)
                    return u'%s: Setting name for %s to %s' % ( nick, target_nick, real_name )
                else:
                    name = self.get(nick=target_nick)
                    if name:
                        return u'%s: %s is %s' % ( nick, target_nick, name )
                    else:
                        return u'%s: Sorry, I don\'t who %s is.' % ( nick, target_nick )
            else:
                name_list = "\n\nRecorded names:\n"
                for user_nick, name in self.get_names().iteritems():
                    name_list = name_list + user_nick + ": " + name + "\n"
                return u'%s: %s' % (nick, name_list)
コード例 #35
0
ファイル: noaa.py プロジェクト: Spacexplosion/Quaking-Mad-Cow
class Main(Module):

    pattern = re.compile(r'^\s*noaa(?:\s+(@?)(.+?))?\s*$', re.I)
    help = 'noaa [location|@nick] - alternative weather (us only)'
    noaa_url = 'http://www.weather.gov/'
    noaa_search = 'http://forecast.weather.gov/zipcity.php'
    error = 'Something bad happened'

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=self.madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.getweather(location)
        return u'%s: %s' % (nick, response)

    def getweather(self, location):
        """Look up NOAA weather"""
        soup = getsoup(self.noaa_search, {'inputstring': location},
                       referer=self.noaa_url)

        # jesus f*****g christ, their html is bad.. looks like 1987
        # nested tables, font tags, and not a single class or id.. good game
        current = soup.find('img', alt='Current Local Weather')
        if not current:
            return u'NOAA website is having issues'
        current = current.findNext('table').table.table
        temp = current.td.font.renderContents().replace('<br />', '|')
        temp = strip_html(temp.decode('utf-8')).replace('\n', '').strip()
        cond, _, tempf, tempc = temp.split('|')
        tempc = tempc.replace('(', '').replace(')', '')
        tempf, tempc = self.docolor(tempf, tempc)
        other = current.table
        items = [u'%s (%s) - %s' % (tempf, tempc, cond)]
        for row in other('tr'):
            if row.a:
                continue
            cells = row('td')
            key = self.render(cells[0])
            val = self.render(cells[1])
            items.append(u'%s %s' % (key, val))
        return u', '.join(items)

    def docolor(self, tempf, tempc):
        temp = int(tempf.split(u'\xb0')[0])
        blink = False
        if temp < 0:
            color = 'magenta'
        elif temp >=0 and temp < 40:
            color = 'blue'
        elif temp >= 40 and temp < 60:
            color = 'cyan'
        elif temp >= 60 and temp < 80:
            color = 'green'
        elif temp >= 80 and temp < 90:
            color = 'yellow'
        elif temp >= 90 and temp < 100:
            color = 'red'
        elif temp >= 100:
            color = 'red'
            blink = True
        tempf = self.colorlib.get_color(color, text=tempf)
        tempc = self.colorlib.get_color(color, text=tempc)
        if blink:
            tempf = u'\x1b[5m' + tempf + u'\x1b[0m'
            tempc = u'\x1b[5m' + tempc + u'\x1b[0m'
        return tempf, tempc

    @staticmethod
    def render(node):
        data = strip_html(node.renderContents().decode('utf-8', 'ignore'))
        return data.strip()
コード例 #36
0
ファイル: links.py プロジェクト: seunboi4u/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(link|shortcut)s?(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'links'
    help = u'shortcuts                         show list of resource shortcuts\n\
link <shortcut>                   show link for specified shortcut \n\
link <shortcut> <url>             set link for specified shortcut (staff only)\n\
link <shortcut> delete           remove link for specified shortcut (staff only)'

    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)

    def set(self, shortcut, url):
        self.learn.set(self.dbname, shortcut.lower(), url)

    def unset(self, shortcut):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(shortcut.lower())
            if dbm.has_key(shortcut):
                del dbm[shortcut]
                return True
            return False
        finally:
            dbm.close()

    def get_shortcuts(self):
        link_db = self.learn.get_db(self.dbname)
        return link_db

    def has_name(self, shortcut):
        link_db = self.get_shortcuts()
        return shortcut in link_db

    def get(self, shortcut):
        return self.learn.lookup(self.dbname, shortcut)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        shortcut = False
        link = False
        params = []
        if args[1]:
            params = args[1].partition(' ')

        try:
            shortcut = params[0]
        except IndexError:
            shortcut = False

        try:
            link = params[2]
        except IndexError:
            link = False

        # only staff members & bot owner are allowed to set/change shortcuts
        if shortcut and link and (self.staff.is_staff(nick)
                                  or settings.OWNER_NICK == nick):
            if link == "delete":
                self.unset(shortcut)
                return u'%s: Okay, I\'ve deleted the link for %s.  It used to be %s, and now it\'s nothing. How sad.' % (
                    nick, shortcut, link)
            else:
                self.set(shortcut, link)
                return u'%s: Okay, I\'ve set the link for %s to %s' % (
                    nick, shortcut, link)
        elif shortcut:
            link_url = self.get(shortcut)
            if link_url:
                return u'%s: %s - %s' % (nick, shortcut, link_url)
            else:
                return u'%s: Sorry, there is no \'%s\' shortcut.' % (nick,
                                                                     shortcut)
        else:
            kwargs['req'].make_private(
            )  # don't spam the channel with all the links.  there could be a lot of them.
            links = self.get_shortcuts()
            if len(links):
                link_list = "Here are all the current shortcuts:\n"
                for shortcut, url in links.iteritems():
                    link_list = link_list + shortcut + ": " + url + "\n"
                return u'%s' % (link_list)
            else:
                return u'Sorry, no shortcuts have been defined yet.'
コード例 #37
0
ファイル: wunderground.py プロジェクト: seunboi4u/madcow
class Main(Module):

    defaults = {
            'api_key': 'CHANGEME',
            'lang': 'EN',
            'prefer_metric': False,
            'primary_only': False,
            'api_scheme': 'http',
            'api_netloc': 'api.wunderground.com',
            'do_color': True,
            'user_agent': None,
            'timeout': 10,
            }

    trigger_map = {
            'conditions': {
                True: {
                    'basic': ['pwb', 'pw'],
                    'extended': ['pws', 'pwd'],
                    'full': ['pwsx', 'pwdx'],
                    },
                False: {
                    'basic': ['wb'],
                    'extended': ['ws', 'weather', 'weath'],
                    'full': ['wsx'],
                    },
                },
            'data': {
                False: {
                    'almanac': ['alma', 'almanac', 'records', 'highs', 'lows'],
                    'forecast': ['forecast', 'fc', 'fce', 'fcx'],
                    'storm': ['storm', 'storms', 'hurricane', 'hurricanes'],
                    },
                },
            }

    triggers = set()
    _method_triggers = []
    help_lines = [u'Weather Underground query shortcuts:']
    for query_type, station_types in trigger_map.iteritems():
        for pws, handlers in station_types.iteritems():
            for handler, _triggers in handlers.iteritems():
                if _triggers:
                    triggers.update(_triggers)
                    trigger_desc = u'[{}]'.format('|'.join(_triggers))
                    if query_type == 'conditions':
                        meth_desc = u'look up weather conditions'
                        notes = []
                        if pws:
                            notes.append(u'include personal weather stations')
                        else:
                            notes.append(u'official stations only')
                        if handler == 'basic':
                            notes.append(u'brief result')
                        if handler == 'full':
                            notes.append(u'extended result')
                        if notes:
                            meth_desc += u' ({})'.format(', '.join(notes))
                    else:
                        meth_desc = u'look up extended {} data'.format(handler)
                    triggers.update(_triggers)
                    help_lines.append(u'{} - {}'.format(trigger_desc, meth_desc))
                    _method_triggers.append(('get_{}_{}'.format(handler, query_type), frozenset(_triggers), pws))

    help = u'\n'.join(help_lines)
    regex = r'^\s*({})(?:\s+(.+?))?\s*$'.format('|'.join(map(re.escape, sorted(triggers))))
    pattern = re.compile(regex, re.IGNORECASE)
    require_addressing = True

    def init(self):
        opts = {}
        for key, default in self.defaults.iteritems():
            setting = 'WUNDERGROUND_' + key.upper()
            val = getattr(settings, setting, None)
            if val is None:
                val = default
            opts[key] = val

        self.api = WeatherUnderground(log=self.madcow.log, **opts)
        self.learn = Learn(madcow=self.madcow)
        self.method_triggers = [(getattr(self.api, method_name), triggers, pws)
                                for method_name, triggers, pws in self._method_triggers]

    def response(self, nick, args, kwargs, _strip=lambda x: x.strip()):
        trigger, query = ('' if arg is None else _strip(arg) for arg in args)
        trigger = trigger.lower()
        for method, triggers, pws in self.method_triggers:
            if trigger in triggers:
                res = None
                break
        else:
            res = u': internal configuration error: no handler found for that keyword.'
        if not res:
            if not query:
                loc = self.learn.lookup('location', nick)
            elif query.startswith(u'@'):
                loc = self.learn.lookup('location', query[1:])
            else:
                loc = query
            if loc:
                try:
                    res = method(loc, pws=pws)
                except APILookupError, exc:
                    res = u'API lookup error: {}'.format(exc.message)
            else:
                res = u"I couldn't look that up: be sure to specify a query or set your default location with: set location <nick> <zip|city|airport_code>"
        if len(_strip(res).splitlines()) == 1:
            res = u'{}: {}'.format(nick, res)
        return res
コード例 #38
0
 def init(self):
     self.learn = Learn(madcow=self.madcow)
     self.staff = Staff(madcow=self.madcow)
コード例 #39
0
ファイル: weather.py プロジェクト: seunboi4u/madcow
 def init(self):
     colorlib = self.madcow.colorlib
     self.weather = Weather(colorlib, self.log)
     self.learn = Learn(madcow=self.madcow)
コード例 #40
0
ファイル: noaa.py プロジェクト: seunboi4u/madcow
 def init(self):
     self.colorlib = self.madcow.colorlib
     try:
         self.learn = Learn(madcow=self.madcow)
     except:
         self.learn = None
コード例 #41
0
class Main(Module):
    pattern = re.compile(u'^\s*(names?)(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'realname'
    help = u'names                          show list of associated nicks and names (staff only)\n\
name <nick>                    show real name associated with user (staff only)\n\
name <nick> <real_name>        set real name for user (staff only)'

    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)

    def set(self, nick, name):
        self.learn.set(self.dbname, nick.lower(), name)

    def unset(self, nick):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(nick.lower())
            if dbm.has_key(nick):
                del dbm[nick]
                return True
            return False
        finally:
            dbm.close()

    def get_names(self):
        name_db = self.learn.get_db('realname')
        return name_db

    def has_name(self, nick):
        name_db = self.get_names()
        return nick in name_db

    def get(self, nick):
        return self.learn.lookup(self.dbname, nick)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        real_name = False
        params = []
        if args[1]:
            params = args[1].partition(' ')

        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False

        try:
            real_name = params[2]
        except IndexError:
            real_name = False

        # only staff members & bot owner are allowed to get & set real_name data
        if self.staff.is_staff(nick) or settings.OWNER_NICK == nick:
            if target_nick:
                if real_name:
                    self.set(target_nick, real_name)
                    return u'%s: Setting name for %s to %s' % (
                        nick, target_nick, real_name)
                else:
                    name = self.get(nick=target_nick)
                    if name:
                        return u'%s: %s is %s' % (nick, target_nick, name)
                    else:
                        return u'%s: Sorry, I don\'t who %s is.' % (
                            nick, target_nick)
            else:
                name_list = "\n\nRecorded names:\n"
                for user_nick, name in self.get_names().iteritems():
                    name_list = name_list + user_nick + ": " + name + "\n"
                return u'%s: %s' % (nick, name_list)
コード例 #42
0
 def init(self):
     self.learn = Learn(self.madcow)
コード例 #43
0
ファイル: summon.py プロジェクト: seunboi4u/madcow
 def init(self):
     self.learn = Learn(self.madcow)
コード例 #44
0
ファイル: noaa.py プロジェクト: sempernex/madcow
class Main(Module):

    pattern = re.compile(r'^\s*noaa(?:\s+(@?)(.+?))?\s*$', re.I)
    help = 'noaa [location|@nick] - alternative weather (us only)'
    noaa_url = 'http://www.weather.gov/'
    noaa_search = 'http://forecast.weather.gov/zipcity.php'
    error = 'Something bad happened'

    def init(self):
        self.colorlib = self.madcow.colorlib
        try:
            self.learn = Learn(madcow=self.madcow)
        except:
            self.learn = None

    def response(self, nick, args, kwargs):
        if not args[1]:
            args = 1, nick
        if args[0]:
            location = self.learn.lookup('location', args[1])
            if not location:
                return u'%s: Try: set location <nick> <location>' % nick
        else:
            location = args[1]
        response = self.getweather(location)
        return u'%s: %s' % (nick, response)

    def getweather(self, location):
        """Look up NOAA weather"""
        soup = getsoup(self.noaa_search, {'inputstring': location},
                       referer=self.noaa_url)

        # jesus f*****g christ, their html is bad.. looks like 1987
        # nested tables, font tags, and not a single class or id.. good game
        current = soup.find('img', alt='Current Local Weather')
        if not current:
            return u'NOAA website is having issues'
        current = current.findNext('table').table.table
        temp = current.td.font.renderContents().replace('<br />', '|')
        temp = strip_html(decode(temp, 'utf-8')).replace('\n', '').strip()
        cond, _, tempf, tempc = temp.split('|')
        tempc = tempc.replace('(', '').replace(')', '')
        tempf, tempc = self.docolor(tempf, tempc)
        other = current.table
        items = [u'%s (%s) - %s' % (tempf, tempc, cond)]
        for row in other('tr'):
            if row.a:
                continue
            cells = row('td')
            key = self.render(cells[0])
            val = self.render(cells[1])
            items.append(u'%s %s' % (key, val))
        return u', '.join(items)

    def docolor(self, tempf, tempc):
        temp = int(tempf.split(u'\xb0')[0])
        blink = False
        if temp < 0:
            color = 'magenta'
        elif temp >= 0 and temp < 40:
            color = 'blue'
        elif temp >= 40 and temp < 60:
            color = 'cyan'
        elif temp >= 60 and temp < 80:
            color = 'green'
        elif temp >= 80 and temp < 90:
            color = 'yellow'
        elif temp >= 90 and temp < 100:
            color = 'red'
        elif temp >= 100:
            color = 'red'
            blink = True
        tempf = self.colorlib.get_color(color, text=tempf)
        tempc = self.colorlib.get_color(color, text=tempc)
        if blink:
            tempf = u'\x1b[5m' + tempf + u'\x1b[0m'
            tempc = u'\x1b[5m' + tempc + u'\x1b[0m'
        return tempf, tempc

    @staticmethod
    def render(node):
        data = strip_html(decode(node.renderContents(), 'utf-8'))
        return data.strip()
コード例 #45
0
ファイル: summon.py プロジェクト: compbrain/madcow
 def __init__(self, madcow):
     self.learn = Learn(madcow)
     self.config = madcow.config
コード例 #46
0
ファイル: karma.py プロジェクト: gipi/Richie
 def __init__(self, madcow):
     self.learn = Learn(madcow)
コード例 #47
0
ファイル: realname.py プロジェクト: Havvy/madcow
 def init(self):
     self.learn = Learn(madcow=self.madcow)
     self.staff = Staff(madcow=self.madcow)
コード例 #48
0
ファイル: company.py プロジェクト: seunboi4u/madcow
class Main(Module):
    pattern = re.compile(u'^\s*(compan[y|ies])(?:\s+(.*)$)?')
    require_addressing = False
    dbname = u'company'
    help = u'companies                          list all company/nick associations (staff only)\n\
company <nick>                     show company associated with user (staff only)\n\
company <nick> <company_name>      set company information for user (staff only)'

    def init(self):
        self.learn = Learn(madcow=self.madcow)
        self.staff = Staff(madcow=self.madcow)

    def set(self, nick, company):
        self.learn.set(self.dbname, nick.lower(), company)

    def unset(self, nick):
        dbm = self.learn.dbm(self.dbname)
        try:
            key = encode(nick.lower())
            if dbm.has_key(nick):
                del dbm[nick]
                return True
            return False
        finally:
            dbm.close()

    def get_companies(self):
        company_db = self.learn.get_db('company')
        return company_db

    def has_company(self, nick):
        company_db = self.get_companies()
        return nick in company_db

    def get(self, nick):
        return self.learn.lookup(self.dbname, nick)

    def response(self, nick, args, kwargs):
        cmd = args[0]
        target_nick = False
        company = False
        params = []
        if args[1]:
            params = args[1].partition(' ')

        try:
            target_nick = params[0]
        except IndexError:
            target_nick = False

        try:
            company = params[2]
        except IndexError:
            company = False

        # only staff members & bot owner are allowed to get & set company data
        if self.staff.is_staff(nick) or settings.OWNER_NICK == nick:
            if target_nick:
                if company:
                    self.set(target_nick, company)
                    return u'%s: setting company for %s to %s' % (
                        nick, target_nick, company)
                else:
                    company_name = self.get(target_nick)
                    if company_name:
                        return u'%s: %s works at %s' % (nick, target_nick,
                                                        company_name)
                    else:
                        return u'%s: I don\'t know where %s works' % (
                            nick, target_nick)
            else:
                company_list = "\n\nRecorded companies:\n"
                for user_nick, company_name in self.get_companies().iteritems(
                ):
                    company_list = company_list + user_nick + " works at " + company_name + "\n"
                return u'%s: %s' % (nick, company_list)
コード例 #49
0
ファイル: noaa.py プロジェクト: Spacexplosion/Quaking-Mad-Cow
 def init(self):
     self.colorlib = self.madcow.colorlib
     try:
         self.learn = Learn(madcow=self.madcow)
     except:
         self.learn = None
コード例 #50
0
ファイル: weather.py プロジェクト: Jzarecta/madcow
 def init(self):
     colorlib = self.madcow.colorlib
     self.weather = Weather(colorlib, self.log)
     self.learn = Learn(madcow=self.madcow)