Example #1
0
 def rmadison(self, event, package, distro, release):
     distro = distro and distro.lower() or 'all'
     params = {
         'package': package.lower(),
         'text': 'on',
     }
     if release is not None:
         params['s'] = release.lower()
     if distro == 'all':
         params['table'] = 'all'
         distro = 'udd'
     if distro not in self.rmadison_sources:
         event.addresponse(
             "I'm sorry, but I don't have a madison source for %s", distro)
         return
     table = generic_webservice(self.rmadison_sources[distro], params)
     table = table.strip().splitlines()
     if table and table[0] == 'Traceback (most recent call last):':
         # Not very REST
         event.addresponse(u"Whoops, madison couldn't understand that: %s",
                           table[-1])
     versions = []
     for row in table:
         row = [x.strip() for x in row.split('|')]
         if versions and versions[-1][0] == row[1]:
             versions[-1].append(row[2])
         else:
             versions.append([row[1], row[2]])
     versions = human_join(u'%s (%s)' % (r[0], u', '.join(r[1:]))
                           for r in versions)
     if versions:
         event.addresponse(versions)
     else:
         event.addresponse(u"Sorry, I can't find a package called %s",
                           package.lower())
Example #2
0
    def exchange(self, event, command, amount, frm, to):
        rough = command.lower() == 'exchange'

        canonical_frm = self.resolve_currency(frm, rough)
        canonical_to = self.resolve_currency(to, rough)
        if not canonical_frm or not canonical_to:
            if rough:
                event.addresponse(
                    u"Sorry, I don't know about a currency for %s",
                    (not canonical_frm and frm or to))
            return
        if canonical_frm == canonical_to:
            event.addresponse(
                u"Um, that's the same currency. Tell you what, "
                u"I can offer you my special rate of 0.5 %(currency)s for "
                u"each %(code)s you sell me.", {
                    'currency': self.currencies[canonical_frm][1],
                    'code': canonical_frm,
                })
            return

        data = generic_webservice(
            'http://download.finance.yahoo.com/d/quotes.csv', {
                'f': 'l1ba',
                'e': '.csv',
                's': canonical_frm + canonical_to + '=X',
            })
        last_trade_rate, bid, ask = data.strip().split(',')
        if last_trade_rate == 0:
            event.addresponse(
                u"Whoops, looks like I couldn't make that conversion")
            return

        converted = float(amount) * float(last_trade_rate)
        event.addresponse(
            u'%(fresult)s %(fcode)s (%(fcurrency)s) = '
            u'%(tresult)s %(tcode)s (%(tcurrency)s) '
            u'(Last trade rate: %(rate)s, Bid: %(bid)s, Ask: %(ask)s)', {
                'fresult': amount,
                'tresult': u'%0.*f' %
                (self.currencies[canonical_to][2], converted),
                'fcurrency': self.currencies[canonical_frm][1],
                'tcurrency': self.currencies[canonical_to][1],
                'fcode': canonical_frm,
                'tcode': canonical_to,
                'rate': last_trade_rate,
                'bid': bid,
                'ask': ask,
            })
Example #3
0
    def exchange(self, event, command, amount, frm, to):
        rough = command.lower() == 'exchange'

        canonical_frm = self.resolve_currency(frm, rough)
        canonical_to = self.resolve_currency(to, rough)
        if not canonical_frm or not canonical_to:
            if rough:
                event.addresponse(
                    u"Sorry, I don't know about a currency for %s",
                    (not canonical_frm and frm or to))
            return
        if canonical_frm == canonical_to:
            event.addresponse(
                u"Um, that's the same currency. Tell you what, "
                u"I can offer you my special rate of 0.5 %(currency)s for "
                u"each %(code)s you sell me.", {
                    'currency': self.currencies[canonical_frm][1],
                    'code': canonical_frm,
            })
            return

        data = generic_webservice(
                'http://download.finance.yahoo.com/d/quotes.csv', {
                    'f': 'l1ba',
                    'e': '.csv',
                    's': canonical_frm + canonical_to + '=X',
                })
        last_trade_rate, bid, ask = data.strip().split(',')
        if last_trade_rate == 0:
            event.addresponse(
                    u"Whoops, looks like I couldn't make that conversion")
            return

        converted = float(amount) * float(last_trade_rate)
        event.addresponse(
            u'%(fresult)s %(fcode)s (%(fcurrency)s) = '
            u'%(tresult)s %(tcode)s (%(tcurrency)s) '
            u'(Last trade rate: %(rate)s, Bid: %(bid)s, Ask: %(ask)s)', {
                'fresult': amount,
                'tresult': u'%0.*f' % (self.currencies[canonical_to][2],
                                       converted),
                'fcurrency': self.currencies[canonical_frm][1],
                'tcurrency': self.currencies[canonical_to][1],
                'fcode': canonical_frm,
                'tcode': canonical_to,
                'rate': last_trade_rate,
                'bid': bid,
                'ask': ask,
            })
Example #4
0
    def exchange(self, event, command, amount, frm, to):
        if not self.currencies:
            self._load_currencies()

        if not self.country_codes:
            self.country_codes = get_country_codes()

        rough = command.lower() == 'exchange'

        canonical_frm = self._resolve_currency(frm, rough)
        canonical_to = self._resolve_currency(to, rough)
        if not canonical_frm or not canonical_to:
            if rough:
                event.addresponse(
                    u"Sorry, I don't know about a currency for %s",
                    (not canonical_frm and frm or to))
            return

        data = generic_webservice(
            'http://download.finance.yahoo.com/d/quotes.csv', {
                'f': 'l1ba',
                'e': '.csv',
                's': canonical_frm + canonical_to + '=X',
            })
        last_trade_rate, bid, ask = data.strip().split(',')
        if last_trade_rate == 0:
            event.addresponse(
                u"Whoops, looks like I couldn't make that conversion")
            return

        event.addresponse(
            u'%(fresult)s %(fcode)s (%(fcountry)s %(fcurrency)s) = '
            u'%(tresult)0.2f %(tcode)s (%(tcountry)s %(tcurrency)s) '
            u'(Last trade rate: %(rate)s, Bid: %(bid)s, Ask: %(ask)s)', {
                'fresult': amount,
                'tresult': float(amount) * float(last_trade_rate),
                'fcountry': self.currencies[canonical_frm][0][0],
                'fcurrency': self.currencies[canonical_frm][1],
                'tcountry': self.currencies[canonical_to][0][0],
                'tcurrency': self.currencies[canonical_to][1],
                'fcode': canonical_frm,
                'tcode': canonical_to,
                'rate': last_trade_rate,
                'bid': bid,
                'ask': ask,
            })
Example #5
0
    def exchange(self, event, command, amount, frm, to):
        if not self.currencies:
            self._load_currencies()

        if not self.country_codes:
            self.country_codes = get_country_codes()

        rough = command.lower() == 'exchange'

        canonical_frm = self._resolve_currency(frm, rough)
        canonical_to = self._resolve_currency(to, rough)
        if not canonical_frm or not canonical_to:
            if rough:
                event.addresponse(u"Sorry, I don't know about a currency for %s", (not canonical_frm and frm or to))
            return

        data = generic_webservice(
                'http://download.finance.yahoo.com/d/quotes.csv', {
                    'f': 'l1ba',
                    'e': '.csv',
                    's': canonical_frm + canonical_to + '=X',
                })
        last_trade_rate, bid, ask = data.strip().split(',')
        if last_trade_rate == 0:
            event.addresponse(
                    u"Whoops, looks like I couldn't make that conversion")
            return

        event.addresponse(
            u'%(fresult)s %(fcode)s (%(fcountry)s %(fcurrency)s) = '
            u'%(tresult)0.2f %(tcode)s (%(tcountry)s %(tcurrency)s) '
            u'(Last trade rate: %(rate)s, Bid: %(bid)s, Ask: %(ask)s)', {
                'fresult': amount,
                'tresult': float(amount) * float(last_trade_rate),
                'fcountry': self.currencies[canonical_frm][0][0],
                'fcurrency': self.currencies[canonical_frm][1],
                'tcountry': self.currencies[canonical_to][0][0],
                'tcurrency': self.currencies[canonical_to][1],
                'fcode': canonical_frm,
                'tcode': canonical_to,
                'rate': last_trade_rate,
                'bid': bid,
                'ask': ask,
            })
Example #6
0
    def remote_latest(self, service, user):
        if service['api'] == 'twitter':
            # Twitter ommits retweets in the JSON and XML results:
            statuses = generic_webservice(
                '%sstatuses/user_timeline/%s.atom' %
                (service['endpoint'], user.encode('utf-8')), {'count': 1})
            tree = ElementTree.fromstring(statuses)
            latest = tree.find('{http://www.w3.org/2005/Atom}entry')
            if latest is None:
                raise self.NoTweetsException(user)
            return {
                'text':
                latest.findtext('{http://www.w3.org/2005/Atom}content').split(
                    ': ', 1)[1],
                'ago':
                ago(datetime.utcnow() - parse_timestamp(
                    latest.findtext('{http://www.w3.org/2005/Atom}published'))
                    ),
                'url': [
                    x for x in latest.getiterator(
                        '{http://www.w3.org/2005/Atom}link')
                    if x.get('type') == 'text/html'
                ][0].get('href'),
            }
        elif service['api'] == 'laconica':
            statuses = json_webservice(
                '%sstatuses/user_timeline/%s.json' %
                (service['endpoint'], user.encode('utf-8')), {'count': 1})
            if not statuses:
                raise self.NoTweetsException(user)
            latest = statuses[0]
            url = '%s/notice/%i' % (service['endpoint'].split(
                '/api/', 1)[0], latest['id'])

        return {
            'text': decode_htmlentities(latest['text']),
            'ago':
            ago(datetime.utcnow() - parse_timestamp(latest['created_at'])),
            'url': url,
        }
Example #7
0
    def remote_latest(self, service, user):
        if service['api'] == 'twitter':
            # Twitter ommits retweets in the JSON and XML results:
            statuses = generic_webservice(
                '%sstatuses/user_timeline.rss' % service['endpoint'], {
                    'screen_name': user,
                    'count': 1
                })
            tree = ElementTree.fromstring(statuses)
            latest = tree.find('.//item')
            if latest is None:
                if tree.find('.//error'):
                    log.info('Twitter user_latest returned: %s',
                             tree.findtext('.//error'))
                raise self.NoTweetsException(user)
            return {
                'text':
                latest.findtext('description').split(': ', 1)[1],
                'ago':
                ago(datetime.utcnow() -
                    parse_timestamp(latest.findtext('pubDate'))),
                'url':
                latest.findtext('guid'),
            }
        elif service['api'] == 'laconica':
            statuses = json_webservice(
                '%sstatuses/user_timeline/%s.json' %
                (service['endpoint'], user.encode('utf-8')), {'count': 1})
            if not statuses:
                raise self.NoTweetsException(user)
            latest = statuses[0]
            url = '%s/notice/%i' % (service['endpoint'].split(
                '/api/', 1)[0], latest['id'])

        return {
            'text': decode_htmlentities(latest['text']),
            'ago':
            ago(datetime.utcnow() - parse_timestamp(latest['created_at'])),
            'url': url,
        }
Example #8
0
    def remote_latest(self, service, user):
        if service['api'] == 'twitter':
            # Twitter ommits retweets in the JSON and XML results:
            statuses = generic_webservice('%sstatuses/user_timeline.rss'
                                          % service['endpoint'], {
                                              'screen_name': user,
                                              'count': 1
                                          })
            tree = ElementTree.fromstring(statuses)
            latest = tree.find('.//item')
            if latest is None:
                if tree.find('.//error'):
                    log.info('Twitter user_latest returned: %s',
                             tree.findtext('.//error'))
                raise self.NoTweetsException(user)
            return {
                'text': latest.findtext('description')
                        .split(': ', 1)[1],
                'ago': ago(datetime.utcnow() - parse_timestamp(
                    latest.findtext('pubDate'))),
                'url': latest.findtext('guid'),
            }
        elif service['api'] == 'laconica':
            statuses = json_webservice('%sstatuses/user_timeline/%s.json'
                    % (service['endpoint'], user.encode('utf-8')),
                    {'count': 1})
            if not statuses:
                raise self.NoTweetsException(user)
            latest = statuses[0]
            url = '%s/notice/%i' % (service['endpoint'].split('/api/', 1)[0],
                                    latest['id'])

        return {
            'text': decode_htmlentities(latest['text']),
            'ago': ago(datetime.utcnow()
                       - parse_timestamp(latest['created_at'])),
            'url': url,
        }
Example #9
0
 def rmadison(self, event, package, distro, release):
     distro = distro and distro.lower() or 'all'
     params = {
         'package': package.lower(),
         'text': 'on',
     }
     if release is not None:
         params['s'] = release.lower()
     if distro == 'all':
         params['table'] = 'all'
         distro = 'udd'
     if distro not in self.rmadison_sources:
         event.addresponse(
                 "I'm sorry, but I don't have a madison source for %s",
                 distro)
         return
     table = generic_webservice(self.rmadison_sources[distro], params)
     table = table.strip().splitlines()
     if table and table[0] == 'Traceback (most recent call last):':
         # Not very REST
         event.addresponse(u"Whoops, madison couldn't understand that: %s",
                 table[-1])
     versions = []
     for row in table:
         row = [x.strip() for x in row.split('|')]
         if versions and versions[-1][0] == row[1]:
             versions[-1].append(row[2])
         else:
             versions.append([row[1], row[2]])
     versions = human_join(u'%s (%s)' % (r[0], u', '.join(r[1:]))
                           for r in versions)
     if versions:
         event.addresponse(versions)
     else:
         event.addresponse(u"Sorry, I can't find a package called %s",
                           package.lower())
Example #10
0
    def remote_latest(self, service, user):
        if service['api'] == 'twitter':
            # Twitter ommits retweets in the JSON and XML results:
            statuses = generic_webservice('%sstatuses/user_timeline/%s.atom'
                    % (service['endpoint'], user.encode('utf-8')),
                    {'count': 1})
            tree = ElementTree.fromstring(statuses)
            latest = tree.find('{http://www.w3.org/2005/Atom}entry')
            if latest is None:
                raise self.NoTweetsException(user)
            return {
                'text': latest.findtext('{http://www.w3.org/2005/Atom}content')
                        .split(': ', 1)[1],
                'ago': ago(datetime.utcnow() - parse_timestamp(
                    latest.findtext('{http://www.w3.org/2005/Atom}published'))),
                'url': [x for x
                     in latest.getiterator('{http://www.w3.org/2005/Atom}link')
                     if x.get('type') == 'text/html'
                  ][0].get('href'),
            }
        elif service['api'] == 'laconica':
            statuses = json_webservice('%sstatuses/user_timeline/%s.json'
                    % (service['endpoint'], user.encode('utf-8')),
                    {'count': 1})
            if not statuses:
                raise self.NoTweetsException(user)
            latest = statuses[0]
            url = '%s/notice/%i' % (service['endpoint'].split('/api/', 1)[0],
                                    latest['id'])

        return {
            'text': decode_htmlentities(latest['text']),
            'ago': ago(datetime.utcnow()
                       - parse_timestamp(latest['created_at'])),
            'url': url,
        }