Ejemplo n.º 1
0
    def advanced_forecast(self):
        print(self.match)
        if self.match and self.match.group('days_to_forecast') and int(self.match.group('days_to_forecast')) <= 5:
            days_to_forecast = int(self.match.group('days_to_forecast'))
        else:
            days_to_forecast = 2
        args = [
            'appid=' + self.config.get('OpenWeatherMapKey'),
            'id=2642182',
            'units=metric'
        ]
        forecast = feeds.get_json(self.endpoints['forecast'] + '?' + '&'.join(args))
        changes = []

        for f in forecast['list']:
            for w in f['weather']:
                if datetime.datetime.fromtimestamp(f['dt']) > (datetime.datetime.now() + datetime.timedelta(days=days_to_forecast)):
                    break
                if len(changes) == 0 or changes[len(changes)-1]['forecast'] != w['description']:
                    changes.append({'forecast': w['description'],
                                    'start': datetime.datetime.fromtimestamp(f['dt']),
                                    'end': datetime.datetime.fromtimestamp(f['dt'])})
                elif changes[len(changes)-1]['forecast'] != w['description']:
                    changes[len(changes)-1]['end'] = datetime.datetime.fromtimestamp(f['dt'])

        change_str = []
        for change in changes:
            change_str.append(change['forecast'] + ' until ' + lib.dt.period_from_datetime(change['end']))

        return 'There will be ' + ' and then '.join((', '.join(change_str)).rsplit(', ', 1))
Ejemplo n.º 2
0
    def __convert(currency, amount, key):
        """ Convert currency into GBP (as long as it's USD!) """
        endpoint = 'https://openexchangerates.org/api/latest.json?app_id=' + key

        r = feeds.get_json(endpoint, None)
        gbp = r['rates']['GBP']
        conversion = float(amount) * float(gbp)
        return conversion
Ejemplo n.º 3
0
 def __get_language_code(self, language):
     if self.languages is None:
         self.languages = feeds.get_json(self.endpoints['languages'])
     if self.languages:
         for r in self.languages:
             if re.search(r['languageName'], language, re.IGNORECASE):
                 return r['languageCode']
     return None
Ejemplo n.º 4
0
    def __convert(currency, amount, key):
        """ Convert currency into GBP (as long as it's USD!) """
        endpoint = 'https://openexchangerates.org/api/latest.json?app_id=' + key

        r = feeds.get_json(endpoint, None)
        gbp = r['rates']['GBP']
        conversion = float(amount) * float(gbp)
        return conversion
Ejemplo n.º 5
0
    def __parse_feed(feed_list, num_items):
        response = []
        for feed in feed_list:
            d = feeds.get_json(feed, None, None, False)
            if d['status'] == 'error':
                response.append(d['message'] + '\n' + feed)
                continue

            cnt = 0
            for entry in d['articles']:
                response.append(entry['title'] + "\n" + entry['url'])
                cnt += 1
                if cnt >= num_items:
                    break

        return '\n\n'.join(response)
Ejemplo n.º 6
0
    def __parse_feed(feed_list, num_items):
        response = []
        for feed in feed_list:
            d = feeds.get_json(feed, None, None, False)
            if d['status'] == 'error':
                response.append(d['message'] + '\n' + feed)
                continue

            cnt = 0
            for entry in d['articles']:
                response.append(entry['title'] + "\n" + entry['url'])
                cnt += 1
                if cnt >= num_items:
                    break

        return '\n\n'.join(response)
Ejemplo n.º 7
0
    def translate(self):
        params = ['text=' + self.match.group(1)]

        language = self.__get_language_code(self.match.group(3))

        if language is None:
            return "I can't translate " + self.match.group(
                2) + " " + self.match.group(3)

        if 'from' in self.match.group(2):
            params.append('from=' + language)
            params.append('to=en')
        else:
            params.append('to=' + language)
            params.append('from=en')
        r = feeds.get_json(self.endpoints['translate'], params)
        if r is None:
            return 'There was a problem with the translator'
        return r['translationText']
Ejemplo n.º 8
0
    def advanced_forecast(self):
        print(self.match)
        if self.match and self.match.group('days_to_forecast') and int(
                self.match.group('days_to_forecast')) <= 5:
            days_to_forecast = int(self.match.group('days_to_forecast'))
        else:
            days_to_forecast = 2
        args = [
            'appid=' + self.config.get('OpenWeatherMapKey'), 'id=2642182',
            'units=metric'
        ]
        forecast = feeds.get_json(self.endpoints['forecast'] + '?' +
                                  '&'.join(args))
        changes = []

        for f in forecast['list']:
            for w in f['weather']:
                if datetime.datetime.fromtimestamp(
                        f['dt']) > (datetime.datetime.now() +
                                    datetime.timedelta(days=days_to_forecast)):
                    break
                if len(changes) == 0 or changes[
                        len(changes) - 1]['forecast'] != w['description']:
                    changes.append({
                        'forecast':
                        w['description'],
                        'start':
                        datetime.datetime.fromtimestamp(f['dt']),
                        'end':
                        datetime.datetime.fromtimestamp(f['dt'])
                    })
                elif changes[len(changes) - 1]['forecast'] != w['description']:
                    changes[len(changes) -
                            1]['end'] = datetime.datetime.fromtimestamp(
                                f['dt'])

        change_str = []
        for change in changes:
            change_str.append(change['forecast'] + ' until ' +
                              lib.dt.period_from_datetime(change['end']))

        return 'There will be ' + ' and then '.join(
            (', '.join(change_str)).rsplit(', ', 1))
Ejemplo n.º 9
0
    def forecast(self):
        args = [
            'appid=' + self.config.get('OpenWeatherMapKey'), 'id=2642182',
            'units=metric'
        ]
        forecast = feeds.get_json(self.endpoints['forecast'] + '?' +
                                  '&'.join(args))

        occurrences = {'rain': set(), 'ice': set()}

        for f in forecast['list']:
            if f['main']['temp'] < 1:
                occurrences['ice'].add(
                    datetime.datetime.fromtimestamp(f['dt']).weekday())

            for w in f['weather']:
                if 'Rain' in w['main']:
                    occurrences['rain'].add(
                        datetime.datetime.fromtimestamp(f['dt']).weekday())

        response = []

        if len(occurrences['rain']) > 0:
            r = []
            for o in occurrences['rain']:
                r.append(calendar.day_name[o])
            # build natural speech list of days
            response.append('It is likely to rain on ' +
                            ' and'.join(', '.join(r).rsplit(',', 1)))

        if len(occurrences['ice']) > 0:
            r = []
            for o in occurrences['ice']:
                r.append(calendar.day_name[o])
            # build natural speech list of days
            response.append('It is likely to be icy on ' +
                            ' and'.join(', '.join(r).rsplit(',', 1)))

        if len(response) == 0:
            response.append('No rain or ice forecast for the next 5 days')

        return '\n'.join(response)
Ejemplo n.º 10
0
    def forecast(self):
        args = [
            'appid=' + self.config.get('OpenWeatherMapKey'),
            'id=2642182',
            'units=metric'
        ]
        forecast = feeds.get_json(self.endpoints['forecast']+'?' + '&'.join(args))

        occurrences = {'rain': set(), 'ice': set()}

        for f in forecast['list']:
            if f['main']['temp'] < 1:
                occurrences['ice'].add(datetime.datetime.fromtimestamp(f['dt']).weekday())

            for w in f['weather']:
                if 'Rain' in w['main']:
                    occurrences['rain'].add(datetime.datetime.fromtimestamp(f['dt']).weekday())

        response = []

        if len(occurrences['rain']) > 0:
            r = []
            for o in occurrences['rain']:
                r.append(calendar.day_name[o])
            # build natural speech list of days
            response.append('It is likely to rain on ' + ' and'.join(', '.join(r).rsplit(',', 1)))

        if len(occurrences['ice']) > 0:
            r = []
            for o in occurrences['ice']:
                r.append(calendar.day_name[o])
            # build natural speech list of days
            response.append('It is likely to be icy on ' + ' and'.join(', '.join(r).rsplit(',', 1)))

        if len(response) == 0:
            response.append('No rain or ice forecast for the next 5 days')

        return '\n'.join(response)
Ejemplo n.º 11
0
 def __get_sources(self):
     params = {'language=en'}
     return feeds.get_json(self.endpoints['sources'], params, None, False)  # @todo make language user specific
Ejemplo n.º 12
0
 def __get_sources(self):
     params = {'language=en'}
     return feeds.get_json(self.endpoints['sources'], params, None,
                           False)  # @todo make language user specific
Ejemplo n.º 13
0
 def __get_json(url):
     return feeds.get_json(url, None, [('User-Agent', 'Mozilla/5.0')])