Example #1
0
    def tld_to_country(self, event, tld):
        if not self.country_codes:
            self.country_codes = get_country_codes()

        tld = tld.upper()

        if tld in self.country_codes:
            event.addresponse(u"%(tld)s is the ccTLD for %(country)s", {"tld": tld, "country": self.country_codes[tld]})
        else:
            event.addresponse(u"ISO doesn't know about any such ccTLD")
Example #2
0
    def country_to_tld(self, event, location):
        if not self.country_codes:
            self.country_codes = get_country_codes()

        output = []
        for tld, country in self.country_codes.iteritems():
            if location.lower() in country.lower():
                output.append(u"%(tld)s is the ccTLD for %(country)s" % {"tld": tld, "country": country})
        if output:
            event.addresponse(human_join(output))
        else:
            event.addresponse(u"ISO doesn't know about any TLD for %s", location)
Example #3
0
    def tld_to_country(self, event, tld):
        if not self.country_codes:
            self.country_codes = get_country_codes()

        tld = tld.upper()

        if tld in self.country_codes:
            event.addresponse(u'%(tld)s is the ccTLD for %(country)s', {
                'tld': tld,
                'country': self.country_codes[tld],
            })
        else:
            event.addresponse(u"ISO doesn't know about any such ccTLD")
Example #4
0
    def country_to_tld(self, event, location):
        if not self.country_codes:
            self.country_codes = get_country_codes()

        output = []
        for tld, country in self.country_codes.iteritems():
            if location.lower() in country.lower():
                output.append(u'%(tld)s is the ccTLD for %(country)s' % {
                    'tld': tld,
                    'country': country,
                })
        if output:
            event.addresponse(human_join(output))
        else:
            event.addresponse(u"ISO doesn't know about any TLD for %s",
                              location)
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 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 #7
0
    def _load_currencies(self):
        iso4127_file = cacheable_download(
            'http://www.currency-iso.org/dl_iso_table_a1.xml',
            'conversions/iso4217.xml')
        document = ElementTree.parse(iso4127_file)
        # Code -> [Countries..., Currency Name, post-decimal digits]
        self.currencies = {}
        # Country -> Code
        self.country_currencies = {}
        self.country_codes = get_country_codes()
        # Non-currencies:
        non_currencies = set((
            'BOV CLF COU MXV '
            'UYI XSU XUA '  # Various Fund codes
            'CHE CHW '  # Swiss WIR currencies
            'USN USS '  # US Dollar fund codes
            'XAG XAU XPD XPT '  # Metals
            'XBA XBB XBC XBD '  # Euro Bond Market
            'XDR XTS XXX '  # Other specials
        ).split())
        no_country_codes = set((
            'Saint Martin',
            'Virgin Islands (Us)',
            'Virgin Islands (British)',
        ))
        accociated_all_countries = True
        for currency in document.getiterator('ISO_CURRENCY'):
            code = currency.findtext('ALPHABETIC_CODE').strip()
            name = currency.findtext('CURRENCY').strip()
            place = currency.findtext('ENTITY').strip().title()
            try:
                minor_units = int(currency.findtext('MINOR_UNIT').strip())
            except ValueError:
                minor_units = 2
            if code == '' or code in non_currencies:
                continue
            # Fund codes
            if re.match(r'^Zz[0-9]{2}', place, re.UNICODE):
                continue
            if code in self.currencies:
                self.currencies[code][0].append(place)
            else:
                self.currencies[code] = [[place], name, minor_units]
            if place in no_country_codes:
                continue
            if (code[:2] in self.country_codes
                    and code[:2] not in self.country_currencies):
                self.country_currencies[code[:2]] = code
                continue
            ascii_place = (unicodedata.normalize('NFD', unicode(place)).encode(
                'ASCII', 'ignore').replace('-', ' ').replace('Sint', 'Saint'))

            # Countries with (alternative names)
            swapped_place = None
            m = re.match(r'^(.+?)\s+\((.+)\)$', ascii_place)
            if m is not None:
                swapped_place = '%s (%s)' % (m.group(2), m.group(1))

            for ccode, country in self.country_codes.iteritems():
                country = country.title()
                ascii_country = (unicodedata.normalize('NFD', country).encode(
                    'ASCII', 'ignore').replace('-',
                                               ' ').replace('Sint', 'Saint'))
                if ascii_country in (ascii_place, swapped_place):
                    if ccode not in self.country_currencies:
                        self.country_currencies[ccode] = code
                    break
            else:
                log.info(
                    u"ISO4127 parsing: Can't identify %s as a known "
                    u"country", place)
                accociated_all_countries = False

        # Special cases for shared currencies:
        self.currencies['EUR'][0].append(u'Euro Member Countries')
        self.currencies['XAF'][0].append(
            u"Communaut\xe9 financi\xe8re d'Afrique")
        self.currencies['XCD'][0].append(
            u'Organisation of Eastern Caribbean States')
        self.currencies['XOF'][0].append(
            u'Coop\xe9ration financi\xe8re en Afrique centrale')
        self.currencies['XPF'][0].append(u'Comptoirs Fran\xe7ais du Pacifique')
        return accociated_all_countries
Example #8
0
    def _load_currencies(self):
        iso4127_file = cacheable_download(
                'http://www.currency-iso.org/dam/isocy/downloads'
                '/dl_iso_table_a1.xml',
                'conversions/iso4217.xml')
        document = ElementTree.parse(iso4127_file)
        # Code -> [Countries..., Currency Name, post-decimal digits]
        self.currencies = {}
        # Country -> Code
        self.country_currencies = {}
        self.country_codes = get_country_codes()
        # Non-currencies:
        non_currencies = set(('BOV CLF COU MXV '
                              'UYI XSU XUA '     # Various Fund codes
                              'CHE CHW '         # Swiss WIR currencies
                              'USN USS '         # US Dollar fund codes
                              'XAG XAU XPD XPT ' # Metals
                              'XBA XBB XBC XBD ' # Euro Bond Market
                              'XDR XTS XXX '     # Other specials
                             ).split())
        no_country_codes = set(('Saint Martin',
                                'Virgin Islands (Us)',
                                'Virgin Islands (British)',))
        accociated_all_countries = True
        for currency in document.getiterator('ISO_CURRENCY'):
            code = currency.findtext('ALPHABETIC_CODE').strip()
            name = currency.findtext('CURRENCY').strip()
            place = currency.findtext('ENTITY').strip().title()
            try:
                minor_units = int(currency.findtext('MINOR_UNIT').strip())
            except ValueError:
                minor_units = 2
            if code == '' or code in non_currencies:
                continue
            # Fund codes
            if re.match(r'^Zz[0-9]{2}', place, re.UNICODE):
                continue
            if code in self.currencies:
                self.currencies[code][0].append(place)
            else:
                self.currencies[code] = [[place], name, minor_units]
            if place in no_country_codes:
                continue
            if (code[:2] in self.country_codes
                        and code[:2] not in self.country_currencies):
                    self.country_currencies[code[:2]] = code
                    continue

            # Countries with (alternative names)
            swapped_place = None
            m = re.match(r'^(.+?)\s+\((.+)\)$', place)
            if m is not None:
                swapped_place = '%s (%s)' % (m.group(2), m.group(1))

            for ccode, country in self.country_codes.iteritems():
                country = country.title()
                if country in (place, swapped_place):
                    if ccode not in self.country_currencies:
                        self.country_currencies[ccode] = code
                    break
            else:
                log.info(u"ISO4127 parsing: Can't identify %s as a known "
                         u"country", place)
                accociated_all_countries = False

        # Special cases for shared currencies:
        self.currencies['EUR'][0].append(u'Euro Member Countries')
        self.currencies['XAF'][0].append(u"Communaut\xe9 financi\xe8re d'Afrique")
        self.currencies['XCD'][0].append(u'Organisation of Eastern Caribbean States')
        self.currencies['XOF'][0].append(u'Coop\xe9ration financi\xe8re en Afrique centrale')
        self.currencies['XPF'][0].append(u'Comptoirs Fran\xe7ais du Pacifique')
        return accociated_all_countries