예제 #1
0
    def run(self, m):
        if is_command(self, 1, m.content):
            url = 'http://thecatapi.com/api/images/get'
            params = {
                'format': 'src',
                'api_key': self.bot.config.api_keys.cat_api
            }

            photo = send_request(url, params=params, parse=False)

            if photo:
                self.bot.send_message(m, photo, 'photo')
            else:
                return self.bot.send_message(
                    m, self.bot.trans.errors.connection_error)

        elif is_command(self, 2, m.content):
            url = 'https://dog.ceo/api/breeds/image/random'

            data = send_request(url)
            if data:
                self.bot.send_message(m, data.message, 'photo')
            else:
                return self.bot.send_message(
                    m, self.bot.trans.errors.connection_error)
예제 #2
0
    def run(self, m):
        if has_tag(self.bot, m.conversation.id, 'noanimals'):
            return

        if is_command(self, 1, m.content):
            url = 'https://api.thecatapi.com/v1/images/search'
            params = {
                'api_key': self.bot.config.api_keys.cat_api,
                'format': 'src'
            }

            photo = send_request(url, params=params, parse=False, bot=self.bot)

            if photo:
                return self.bot.send_message(m, photo, 'photo')
            else:
                return self.bot.send_message(m, self.bot.trans.errors.connection_error)

        elif is_command(self, 2, m.content):
            url = 'https://dog.ceo/api/breeds/image/random'

            data = send_request(url, bot=self.bot)
            if data:
                return self.bot.send_message(m, data.message, 'photo')
            else:
                return self.bot.send_message(m, self.bot.trans.errors.connection_error)
예제 #3
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'https://www.googleapis.com/customsearch/v1'
        params = {
            'q': input,
            'alt': 'json',
            'num': 8,
            'start': 1,
            'key': self.bot.config.api_keys.google_developer_console,
            'cx': self.bot.config.api_keys.google_custom_search_engine
        }

        data = send_request(url, params)

        if not data or 'error' in data:
            return self.bot.send_message(m, self.bot.trans.errors.connection_error)

        if data.searchInformation.totalResults == 0:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        message = self.bot.trans.plugins.web_search.strings.results % input
        for item in data['items']:
            if len(item['title']) > 26:
                item['title'] = item['title'][:23] + '...'
            message += '\n • <a href="%s">%s</a>' % (item['link'], item['title'])

        return self.bot.send_message(m, message, extra={'format': 'HTML', 'preview': False})
예제 #4
0
파일: calc.py 프로젝트: Felfa/ifarres
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        baseurl = 'http://api.mathjs.org/v1/'
        params = {'expr': input}

        result = send_request(baseurl, params, None, None, None, False, False,
                              True)

        print(result)

        if 'Error' in result:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.invalid_syntax)
        elif 'Infinity' in result:
            return self.bot.send_message(
                m, self.bot.trans.plugins.calc.strings.overflow)

        try:
            self.bot.send_message(m, result)

        except Exception as e:
            self.bot.send_alert(e)
예제 #5
0
 def api_request(self, api_method, params=None, headers=None, files=None):
     url = 'https://api.telegram.org/bot%s/%s' % (
         self.bot.config.bindings_token, api_method)
     try:
         return send_request(url, params, headers, files, post=True)
     except:
         return None
예제 #6
0
파일: weather.py 프로젝트: Felfa/ifarres
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        lat, lon, locality, country = get_coords(input)

        url = 'http://api.wunderground.com/api/%s/webcams/conditions/forecast/q/%s,%s.json' % (
            self.bot.config.api_keys.weather_underground, lat, lon)

        data = send_request(url)

        try:
            weather = data.current_observation
            forecast = data.forecast.simpleforecast.forecastday
            webcams = data.webcams
        except:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        title = self.bot.trans.plugins.weather.strings.title % (locality, country)
        temp = weather.temp_c
        feelslike = ""
        try:
            if (float(weather.feelslike_c) - float(weather.temp_c)) > 0.001:
                feelslike = self.bot.trans.plugins.weather.strings.feelslike % weather.feelslike_c
        except:
            pass

        # weather_string = weather.weather.title()
        weather_string = self.bot.trans.plugins.weather.strings[weather.icon]
        weather_icon = (self.get_weather_icon(weather.icon))
        humidity = weather.relative_humidity
        wind = format(float(weather.wind_kph) / 3.6, '.1f')

        if is_command(self, 1, m.content):
            message = u'%s\n%s %s%s\n🌡%sºC 💧%s 🌬%s m/s' % (
                remove_html(title), weather_icon, weather_string, feelslike, temp, humidity, wind)
            try:
                photo = get_streetview(lat, lon, self.bot.config.api_keys.google_developer_console)
            except Exception as e:
                print(e)
                photo = None

            if photo:
                return self.bot.send_message(m, photo, 'photo', extra={'caption': message})
            else:
                return self.bot.send_message(m, message, 'text', extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            message = self.bot.trans.plugins.weather.strings.titleforecast % (locality, country)
            for day in forecast:
                weekday = self.bot.trans.plugins.weather.strings[day.date.weekday.lower()][:3]
                temp = day.low.celsius
                temp_max = day.high.celsius
                # weather_string = day.conditions.title()
                weather_string = self.bot.trans.plugins.weather.strings[day.icon]
                weather_icon = (self.get_weather_icon(day.icon))
                message += u'\n • <b>%s</b>: 🌡 %s-%sºC %s %s' % (weekday, temp, temp_max, weather_icon, weather_string)

            return self.bot.send_message(m, message, extra={'format': 'HTML'})
예제 #7
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, generate_command_help(self, m.content), extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'https://duckduckgo.com/'
        params = {
            'q': input
        }
        res = requests.post(url, data=params)
        searchObj = re.search(r'vqd=([\d-]+)\&', res.text, re.M | re.I)
        if not searchObj:
            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        headers = {
            'authority': 'duckduckgo.com',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'sec-fetch-dest': 'empty',
            'x-requested-with': 'XMLHttpRequest',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'referer': 'https://duckduckgo.com/',
            'accept-language': self.bot.config.locale + ';q=0.9',
        }

        params = (
            ('l', self.bot.config.locale),
            ('o', 'json'),
            ('q', input),
            ('vqd', searchObj.group(1)),
            ('f', ',,,'),
            ('p', '1'),
            ('v7exp', 'a'),
        )

        requestUrl = url + "i.js"

        data = send_request(requestUrl, headers=headers, params=params)

        if not data or not 'results' in data:
            return self.bot.send_message(m, self.bot.trans.errors.connection_error, extra={'format': 'HTML'})

        if len(data.results) == 0:
            return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

        try:
            i = randint(0, len(data.results) - 1)
            photo = data.results[i].url
            caption = None  # data.results[i].title

        except Exception as e:
            self.bot.send_alert(e)
            photo = None

        if photo:
            return self.bot.send_message(m, photo, 'photo', extra={'caption': caption})
        else:
            return self.bot.send_message(m, self.bot.trans.errors.download_failed)
예제 #8
0
    def ddragon_versions(self):
        data = send_request(
            'https://ddragon.leagueoflegends.com/api/versions.json')
        if data:
            return data[0]

        return None
예제 #9
0
파일: giphy.py 프로젝트: Felfa/ifarres
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        baseurl = 'http://api.giphy.com/v1/gifs/search'
        params = {'api_key': self.bot.config.api_keys.giphy, 'q': input}

        data = send_request(baseurl, params)

        if not data or 'error' in data:
            return self.bot.send_message(
                m, self.bot.trans.errors.connection_error)

        if data.pagination.total_count == 0:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        try:
            i = randint(0, len(data['data']) - 1)
            gif_url = data['data'][i]['images']['original']['url']

        except Exception as e:
            self.bot.send_alert(e)
            gif_url = None

        if gif_url:
            return self.bot.send_message(m, gif_url, 'document')
        else:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.download_failed)
예제 #10
0
    def ddragon_champions(self):
        data = send_request(
            'http://ddragon.leagueoflegends.com/cdn/{}/data/{}/champion.json'.
            format(self.ddragon_versions(), self.bot.config.locale))
        if data:
            return data.data

        return None
예제 #11
0
 def api_request(self, api_method, params=None, headers=None, data=None, files=None):
     url = 'https://api.telegram.org/bot{}/{}'.format(
         self.bot.config['bindings_token'], api_method)
     try:
         res = send_request(url, params, headers, files,
                            data, post=True, bot=self.bot)
         self.request_processing(params, res)
     except:
         return None
예제 #12
0
    def api_request(self, method, params={}, regional=False):
        if regional:
            endpoint = 'https://%s.%s' % (self.region['region'], self.base_url)
        else:
            endpoint = 'https://%s.%s' % (self.region['platform'],
                                          self.base_url)

        headers = {'X-Riot-Token': self.bot.config.api_keys.riot_api}

        return send_request(endpoint + method, params, headers=headers)
예제 #13
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        url = 'https://www.googleapis.com/customsearch/v1'
        params = {
            'q': input,
            'alt': 'json',
            'num': 8,
            'start': 1,
            'key': self.bot.config.api_keys.google_developer_console,
            'cx': self.bot.config.api_keys.google_custom_search_engine
        }

        data = send_request(url, params)

        if not data or 'error' in data:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.connection_error,
                extra={'format': 'HTML'})

        if int(data.searchInformation.totalResults) == 0:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.no_results,
                                         extra={'format': 'HTML'})

        if is_command(self, 1, m.content):
            text = self.bot.trans.plugins.web_search.strings.results % input
            for item in data['items']:
                if len(item.title) > 26:
                    item.title = item.title[:23] + '...'
                text += '\n • <a href="%s">%s</a>' % (item.link, item.title)

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': False
                                  })

        elif is_command(self, 2, m.content):
            text = data['items'][0].link

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': True
                                  })
예제 #14
0
파일: jokes.py 프로젝트: luksireiku/polaris
    def run(self, m):
        url = 'http://api.icndb.com/jokes/random'

        data = send_request(url)

        if not data:
            return self.bot.send_message(m, self.bot.trans.errors.connection_error)
            
        text = html.unescape(data.value.joke).replace('Chuck Norris', self.bot.info.first_name)

        self.bot.send_message(m, text)
예제 #15
0
    def run(self, m):
        url = 'http://api.icndb.com/jokes/random'

        data = send_request(url)

        if not data:
            return self.bot.send_message(
                m, self.bot.trans.errors.connection_error)

        text = html.unescape(data.value.joke).replace('Chuck Norris',
                                                      self.bot.info.first_name)

        self.bot.send_message(m, text)
예제 #16
0
파일: cats.py 프로젝트: luksireiku/polaris
    def run(self, m):
        url = 'http://thecatapi.com/api/images/get'
        params = {
            'format': 'src',
            'api_key': self.bot.config.api_keys.cat_api
        }

        photo = send_request(url, params=params, parse=False)

        if photo:
            self.bot.send_message(m, photo, 'photo')
        else:
            return self.bot.send_message(m, self.bot.trans.errors.connection_error)
예제 #17
0
    def run(self, m):
        url = 'http://api.icndb.com/jokes/random'
        params = {
            'firstName': self.bot.info.first_name,
            'lastName': self.bot.info.last_name
        }

        data = send_request(url, params, bot=self.bot)

        if not data or data['type'] != 'success':
            return self.bot.send_message(
                m, self.bot.trans.errors.connection_error)

        self.bot.send_message(m, data.value.joke, extra={'format': 'HTML'})
예제 #18
0
    def get_class(self, class_id, region):
        locale = 'en_GB'
        if self.bot.config.translation != 'default':
            locale = 'es_ES'

        url = 'https://%s.api.blizzard.com/wow/data/character/classes' % region
        params = {
            'locale': locale,
            'apikey': self.bot.config.api_keys.battle_net
        }

        data = send_request(url, params)
        for class_ in data.classes:
            if class_.id == class_id:
                return class_.name
예제 #19
0
    def get_race(self, race_id, region):
        locale = 'en_GB'
        if self.bot.config.translation != 'default':
            locale = 'es_ES'

        url = 'https://%s.api.blizzard.com/wow/data/character/races' % region
        params = {
            'locale': locale,
            'apikey': self.bot.config.api_keys.battle_net
        }

        data = send_request(url, params)
        for race in data.races:
            if race.id == race_id:
                return race.name
예제 #20
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m,
                                         generate_command_help(
                                             self, m.content),
                                         extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'https://www.googleapis.com/youtube/v3/search'
        params = {
            'type': 'video',
            'part': 'snippet',
            'maxResults': '8',
            'q': input,
            'key': self.bot.config.api_keys.google_developer_console
        }

        data = send_request(url, params, bot=self.bot)

        if 'error' in data or int(data.pageInfo.totalResults) == 0:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        if is_command(self, 1, m.content):
            text = 'https://youtu.be/%s' % data['items'][0].id.videoId

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': True
                                  })

        elif is_command(self, 2, m.content):
            text = self.bot.trans.plugins.youtube_search.strings.results % input
            for item in data['items']:
                if len(item.snippet.title) > 26:
                    item.snippet.title = item.snippet.title[:23] + '...'
                text += '\n • <a href="https://youtu.be/%s">%s</a>' % (
                    item.id.videoId, item.snippet.title)

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': False
                                  })
예제 #21
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        url = 'https://www.googleapis.com/customsearch/v1'
        params = {
            'q': input,
            'searchType': 'image',
            'imgSize': 'xlarge',
            'alt': 'json',
            'num': 8,
            'start': 1,
            'key': self.bot.config.api_keys.google_developer_console,
            'cx': self.bot.config.api_keys.google_custom_search_engine
        }

        data = send_request(url, params)

        if not data or 'error' in data:
            return self.bot.send_message(
                m, self.bot.trans.errors.connection_error)

        if data.searchInformation.totalResults == 0 or 'items' not in data:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        try:
            i = randint(0, len(data['items']) - 1)
            photo = data['items'][i].link
            caption = None  # data['items'][i].title

        except Exception as e:
            self.bot.send_alert(e)
            photo = None

        if photo:
            return self.bot.send_message(m,
                                         photo,
                                         'photo',
                                         extra={'caption': caption})
        else:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.download_failed)
예제 #22
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)

        url = 'https://www.googleapis.com/youtube/v3/search'
        params = {
            'type': 'video',
            'part': 'snippet',
            'maxResults': '5',
            'q': input,
            'key': self.bot.config.api_keys.google_developer_console
        }

        data = send_request(url, params)

        if len(data['items']) == 0:  # and 'error' in data:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        elif is_command(self, 1, m.content):
            text = 'https://youtu.be/%s' % data['items'][0]['id']['videoId']

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': True
                                  })

        elif is_command(self, 2, m.content):
            text = self.bot.trans.plugins.youtube_search.strings.results % input
            for item in data['items']:
                if len(item['snippet']['title']) > 26:
                    item['snippet'][
                        'title'] = item['snippet']['title'][:23] + '...'
                text += '\n • <a href="https://youtu.be/%s">%s</a>' % (
                    item['id']['videoId'], item['snippet']['title'])

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': False
                                  })
예제 #23
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'https://www.googleapis.com/customsearch/v1'
        params = {
            'q': input,
            'searchType': 'image',
            'imgSize': 'xlarge',
            'alt': 'json',
            'num': 8,
            'start': 1,
            'key': self.bot.config.api_keys.google_developer_console,
            'cx': self.bot.config.api_keys.google_custom_search_engine
        }

        data = send_request(url, params)

        if not data or 'error' in data:
            return self.bot.send_message(m, self.bot.trans.errors.connection_error)

        if data.searchInformation.totalResults == 0:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        try:
            i = randint(0, len(data['items']) - 1)
            photo = data['items'][i]['link']
            caption = data['items'][i]['title']

        except Exception as e:
            self.bot.send_alert(e)
            photo = None

        if photo:
            return self.bot.send_message(m, photo, 'photo', extra={'caption': caption})
        else:
            return self.bot.send_message(m, self.bot.trans.errors.download_failed)
예제 #24
0
    def run(self, m):
        if is_command(self, 1, m.content):
            username = get_input(m)

            if not username:
                username = get_setting(self.bot, m.sender.id, 'lastfm.username')
                if not username and m.sender.username:
                    username = m.sender.username
                if not username:
                    return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = 'http://ws.audioscrobbler.com/2.0/'
            params = {
                'method': 'user.getrecenttracks',
                'format': 'json',
                'limit': '1',
                'api_key': self.bot.config.api_keys.lastfm,
                'user': username
            }

            lastfm = send_request(url, params=params)


            # If the user didn't have any tracks or doesn't exist return No Results error. #
            try:
                last = lastfm.recenttracks.track[0]
            except:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            artist = last.artist['#text'].title()
            track = last.name.title()
            album = last.album['#text'].title()
            track_url = last.url

            try:
                nowplaying = last['@attr']['nowplaying']
                if nowplaying == 'true':
                    nowplaying = True
                else:
                    nowplaying == False
            except:
                date = last.date['#text']
                nowplaying = False

            if nowplaying:
                text = self.bot.trans.plugins.lastfm.strings.now_playing % username
            else:
                text = self.bot.trans.plugins.lastfm.strings.last_played % username

            text += '\n🎵 <i>%s</i>\n💽 %s' % (track, artist)
            if album:
                text += ' - %s' % album


            # Gets the link of a Youtube video of the track. #
            url = 'https://www.googleapis.com/youtube/v3/search'
            params = {
                'type': 'video',
                'part': 'snippet',
                'maxResults': '1',
                'q': '%s %s' % (track, artist),
                'key': self.bot.config.api_keys.google_developer_console
            }

            youtube = send_request(url, params=params)

            if not 'error' in youtube and len(youtube['items']) > 0:
                text += '\n\n🌐 %s\n%s\nhttps://youtu.be/%s' % (self.bot.trans.plugins.lastfm.strings.might_be, youtube['items'][0]['snippet']['title'], youtube['items'][0]['id']['videoId'])

            self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})


        elif is_command(self, 2, m.content):
            input = get_input(m)
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            set_setting(self.bot, m.sender.id, 'lastfm.username', input)
            self.bot.send_message(m, self.bot.trans.plugins.lastfm.strings.username_set, extra={'format': 'HTML', 'preview': False})
예제 #25
0
    def run(self, m):
        input = get_input(m)
        baseurl = 'http://www.zaragoza.es/api'

        if is_command(self, 1, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = baseurl + '/recurso/urbanismo-infraestructuras/transporte-urbano/poste/tuzsa-' + input.lstrip(
                '0') + '.json'
            params = {
                'srsname': 'wgs84'
            }

            data = send_request(url, params=params)

            if 'error' in data:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            street = data['title'].split(')')[-1].split('Lí')[0].strip().title()
            parada = data['title'].split(')')[0].replace('(', '')
            line = data['title'].title().split(street)[-1].strip().replace('Líneas: ','')
            buses = []
            nodatabuses = []

            text = '<b>%s</b>\n   Parada: <b>%s</b>  [%s]\n\n' % (street, parada, line)

            for destino in data['destinos']:
                try:
                    tiempo = int(destino['primero'].replace(' minutos', '').rstrip('.'))
                    buses.append((
                        destino['linea'],
                        destino['destino'].rstrip(',').rstrip('.').title(),
                        tiempo
                    ))
                except Exception as e:
                    print(e)
                    tiempo = destino['primero'].rstrip('.').replace('cin', 'ción')
                    nodatabuses.append((
                        destino['linea'],
                        destino['destino'].rstrip(',').rstrip('.').title(),
                        tiempo
                    ))

                try:
                    tiempo = int(destino['segundo'].replace(' minutos', '').rstrip('.'))
                    buses.append((
                        destino['linea'],
                        destino['destino'].rstrip(',').rstrip('.').title(),
                        tiempo
                    ))
                except Exception as e:
                    print(e)
                    tiempo = destino['segundo'].rstrip('.').replace('cin', 'ción')
                    nodatabuses.append((
                        destino['linea'],
                        destino['destino'].rstrip(',').rstrip('.').title(),
                        tiempo
                    ))
            
            
            buses = sorted(buses, key=lambda bus: bus[2])
            buses.extend(nodatabuses)

            for bus in list(buses):
                if is_int(bus[2]):
                    bus = (bus[0], bus[1], '%s min.' % bus[2])
                text += ' • <b>%s</b>  %s <i>%s</i>\n' % (bus[2], bus[0], bus[1])

            text = text.rstrip('\n')
            
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = baseurl + '/recurso/urbanismo-infraestructuras/tranvia/' + input.lstrip('0') + '.json'
            params = {
                'rf': 'html',
                'srsname': 'wgs84'
            }

            data = send_request(url, params=params)
            if 'status' in data:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            tranvias = []

            text = '<b>%s</b>\n   Parada: <b>%s</b>\n\n' % (data['title'].title(), data['id'])

            for destino in data['destinos']:
                tranvias.append((
                    destino['linea'],
                    destino['destino'].rstrip(',').rstrip('.').title(),
                    int(destino['minutos'])
                ))
            
            try:
                tranvias = sorted(tranvias, key=lambda tranvia: tranvia[2])
            except:
                pass

            for tranvia in tranvias:
                text += ' • <b>%s min.</b>  %s <i>%s</i>\n' % (tranvia[2], tranvia[0], tranvia[1])

            # text += '\n%s' % data['mensajes'][-1].replace('INFORMACIN','INFORMACIÓN')
            text = text.rstrip('\n')
            
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})
           

            url = baseurl + '/recurso/urbanismo-infraestructuras/estacion-bicicleta/' + input.lstrip('0') + '.json'
            params = {
                'rf': 'html',
                'srsname': 'utm30n'
            }

            data = send_request(url, params=params)
            if 'error' in data:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            text = '<b>%s</b>\n   Estación: <b>%s</b>\n\n • Bicis Disponibles: <b>%s</b>\n • Anclajes Disponibles: <b>%s</b>' % (data['title'].title(), data['id'], data['bicisDisponibles'], data['anclajesDisponibles'])
            
            return self.bot.send_message(m, text, extra={'format': 'HTML'})
예제 #26
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m,
                                         generate_command_help(
                                             self, m.content),
                                         extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'https://duckduckgo.com/'
        params = {'q': input}
        res = requests.post(url, data=params)
        searchObj = re.search(r'vqd=([\d-]+)\&', res.text, re.M | re.I)
        if not searchObj:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.unknown,
                                         extra={'format': 'HTML'})

        headers = {
            'authority': 'duckduckgo.com',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'sec-fetch-dest': 'empty',
            'x-requested-with': 'XMLHttpRequest',
            'user-agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'referer': 'https://duckduckgo.com/',
            'accept-language': self.bot.config.locale + ';q=0.9',
        }

        params = (
            ('l', self.bot.config.locale),
            ('o', 'json'),
            ('q', input),
            ('vqd', searchObj.group(1)),
            ('f', ',,,'),
            ('p', '1'),
            ('v7exp', 'a'),
        )

        requestUrl = url + "d.js"

        data = send_request(requestUrl, headers=headers, params=params)

        if not data or not 'results' in data:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.connection_error,
                extra={'format': 'HTML'})

        if len(data.results) == 0:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.no_results,
                                         extra={'format': 'HTML'})

        if not is_command(self, 2, m.content):
            text = self.bot.trans.plugins.web_search.strings.results % input
            limit = 8
            for item in data.results:
                if 't' in item:
                    item['t'] = remove_html(item['t'])
                    if len(item['t']) > 26:
                        item['t'] = item['t'][:23] + '...'
                    text += '\n • <a href="%s">%s</a>' % (item['u'], item['t'])
                    limit -= 1
                    if limit <= 0:
                        break

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': False
                                  })

        else:
            text = data.results[0]['u']

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': True
                                  })
예제 #27
0
 def api_request(self, api_method, params=None, headers=None, files=None):
     url = 'https://api.telegram.org/bot%s/%s' % (self.bot.config.bindings_token, api_method)
     try:
         return send_request(url, params, headers, files, post=True)
     except:
         return None
예제 #28
0
    def always(self, m):
        gid = str(m.conversation.id)

        if m.sender.is_bot:
            logging.info('ignoring bot: {} [{}]'.format(
                m.sender.first_name, m.sender.id))
            return

        if m.sender.id == 777000:
            logging.info('ignoring anonymous message: {} [{}]'.format(
                m.sender.first_name, m.sender.id))
            return

        if has_tag(self.bot, m.sender.id, 'muted'):
            logging.info('ignoring muted user: {} [{}]'.format(
                m.sender.first_name, m.sender.id))
            return

        if 'reply_markup' in m.extra:
            logging.info('ignoring reply markup: {} [{}]'.format(
                m.sender.first_name, m.sender.id))
            return

        if 'via_bot_user_id' in m.extra:
            uid = str(m.extra['via_bot_user_id'])
            name = None

            if uid in self.bot.users:
                name = self.bot.users[uid].first_name

            else:
                info = self.bot.bindings.server_request(
                    'getUser', {'user_id': int(uid)})
                name = info['first_name']
                self.bot.users[uid] = {
                    'first_name': info['first_name'],
                    'last_name': info['last_name'],
                    'messages': 0
                }
                set_data('users/%s/%s' % (self.bot.name, uid),
                         self.bot.users[uid])

            logging.info('ignoring message via bot: {} [{}]'.format(
                name, m.extra['via_bot_user_id']))
            return

        if has_tag(self.bot, gid, 'resend:?') or has_tag(
                self.bot, gid, 'fwd:?'):
            for tag in self.bot.tags[gid]:
                forward = False

                if tag.startswith('resend:') or tag.startswith('fwd:'):
                    cid = int(tag.split(':')[1])
                    if 'from_chat_id' in m.extra:
                        if str(m.extra['from_chat_id']) == str(cid):
                            break
                        elif str(m.extra['from_chat_id']) != '0':
                            if has_tag(self.bot, cid, 'resend:?') or has_tag(
                                    self.bot, cid, 'fwd:?'):
                                logging.info('forward')
                                forward = True

                    logging.info('tag: {}, forward: {}'.format(tag, forward))

                if tag.startswith('resend:') and not forward:
                    cid = int(tag.split(':')[1])

                    if m.type == 'photo' or m.type == 'video' or m.type == 'animation' or m.type == 'document' or (
                            m.type == 'text' and 'urls' in m.extra):
                        r = deepcopy(m)
                        r.conversation.id = cid
                        r.conversation.title = tag

                        if 'urls' in r.extra:
                            for url in r.extra['urls']:
                                input_match = compile(
                                    r'(?i)(?:t|telegram|tlgrm)\.(?:me|dog)\/joinchat\/([a-zA-Z0-9\-]+)',
                                    flags=IGNORECASE).search(url)

                                if input_match and input_match.group(
                                        1) or 'joinchat/' in url:
                                    logging.info(
                                        'ignoring telegram url: {}'.format(
                                            fix_telegram_link(url)))
                                else:
                                    if 'instagram' in url:
                                        url = url.split('?')[0]
                                    self.bot.send_message(
                                        r, url, extra={'preview': True})
                        else:
                            self.bot.send_message(r,
                                                  m.content,
                                                  m.type,
                                                  extra={'preview': True})

                    elif m.type != 'text':
                        logging.info('invalid type: %s' % m.type)

                elif tag.startswith('fwd:') or forward:
                    cid = int(tag.split(':')[1])
                    if m.type == 'photo' or m.type == 'document' or m.type == 'url':
                        self.bot.forward_message(m, cid)

        if has_tag(self.bot, gid, 'discord:?'):
            for tag in self.bot.tags[gid]:
                if tag.startswith('discord:'):
                    token = tag.split(':')[1]
                    webhook_url = 'https://discord.com/api/webhooks/{}'.format(
                        token)

                    if m.type == 'photo' or m.type == 'video' or m.type == 'animation' or m.type == 'document' or (
                            m.type == 'text' and 'urls' in m.extra):
                        if 'urls' in m.extra:
                            for url in m.extra['urls']:
                                input_match = compile(
                                    r'(?i)(?:t|telegram|tlgrm)\.(?:me|dog)\/joinchat\/([a-zA-Z0-9\-]+)',
                                    flags=IGNORECASE).search(url)

                                if input_match and input_match.group(
                                        1) or 'joinchat/' in url:
                                    logging.info(
                                        'ignoring telegram url: {}'.format(
                                            fix_telegram_link(url)))
                                else:
                                    if 'instagram' in url:
                                        url = url.split('?')[0]
                                    send_request(webhook_url, {'content': url},
                                                 post=True)
                        else:
                            if m.content.startswith('http'):
                                send_request(webhook_url,
                                             {'content': m.content},
                                             post=True)
                            else:
                                file = self.bot.get_file(m.content)
                                if file:
                                    send_request(
                                        webhook_url,
                                        post=True,
                                        files={'file': open(file, 'rb')})

                    elif m.type != 'text':
                        logging.info('invalid type: %s' % m.type)
예제 #29
0
    def run(self, m):

        input = get_input(m)
        if m.reply:
            uid = str(m.reply.sender.id)
        else:
            uid = str(m.sender.id)

        # Get character data
        if is_command(self, 1, m.content) or is_command(
                self, 2, m.content) or is_command(self, 3, m.content):
            if not input:
                wow = get_setting(self.bot, uid, 'wow')
                if wow:
                    realm = ' '.join(wow.split('/')[:-1])
                    character = wow.split('/')[-1]
                else:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.missing_parameter,
                        extra={'format': 'HTML'})
            else:
                realm = ' '.join(input.split()[:-1])
                character = input.split()[-1]

            if is_command(self, 1, m.content):
                region = 'eu'
                locale = 'en_GB'
                if self.bot.config.translation != 'default':
                    locale = 'es_ES'

            elif is_command(self, 2, m.content):
                region = 'us'
                locale = 'en_US'
                if self.bot.config.translation != 'default':
                    locale = 'es_MX'

            elif is_command(self, 3, m.content):
                set_setting(self.bot, uid, 'wow', '%s/%s' % (realm, character))
                text = self.bot.trans.plugins.world_of_warcraft.strings.character_set % (
                    character.title(), realm.title())
                return self.bot.send_message(m,
                                             text,
                                             extra={
                                                 'format': 'HTML',
                                                 'preview': True
                                             })

            url = 'https://%s.api.blizzard.com/wow/character/%s/%s' % (
                region, realm, character)
            params = {
                'fields': 'guild,progression,items',
                'locale': locale,
                'apikey': self.bot.config.api_keys.battle_net
            }

            data = send_request(url, params)

            if not data or 'status' in data:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.no_results,
                                             extra={'format': 'HTML'})

            render_url = 'https://render-%s.worldofwarcraft.com/character/' % region
            photo = render_url + data.thumbnail.replace(
                'avatar', 'main') + '?update=%s' % int(time() / 3600)
            name = self.bot.trans.plugins.world_of_warcraft.strings.name % (
                data.name, data.realm, data.level)
            race = self.bot.trans.plugins.world_of_warcraft.strings.race % (
                self.get_race(
                    data.race, region), self.get_class(
                        data['class'], region), self.get_gender(data.gender))
            stats = self.bot.trans.plugins.world_of_warcraft.strings.stats % (
                data['items'].averageItemLevelEquipped, data.achievementPoints,
                data.totalHonorableKills)
            progression = self.get_raids(data.progression.raids)

            if 'guild' in data:
                guild = '\n&lt;%s-%s&gt;' % (data.guild.name, data.guild.realm)
            else:
                guild = None

            text = '<a href="%s">⁣</a>' % photo

            if guild:
                text += name + guild + race + stats + progression
            else:
                text += name + race + stats + progression

            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': True
                                         })

        # Reset character
        elif is_command(self, 4, m.content):
            del_setting(self.bot, uid, 'wow')
            text = self.bot.trans.plugins.world_of_warcraft.strings.character_reset
            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': True
                                         })

        # Token price
        elif is_command(self, 5, m.content):
            url = 'https://wowtokenprices.com/current_prices.json'
            data = send_request(url)

            if data:
                text = self.bot.trans.plugins.world_of_warcraft.strings.token_title
                for region in data:
                    text += self.bot.trans.plugins.world_of_warcraft.strings.token_price % (
                        region.upper(), int(data[region].current_price / 1000),
                        int(data[region]['1_day_low'] / 1000),
                        int(data[region]['1_day_high'] / 1000))

                return self.bot.send_message(m,
                                             text,
                                             extra={
                                                 'format': 'HTML',
                                                 'preview': True
                                             })

            else:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.connection_error,
                    extra={
                        'format': 'HTML',
                        'preview': True
                    })
예제 #30
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        status, values = get_coords(input, self.bot)

        if status == 'ZERO_RESULTS' or status == 'INVALID_REQUEST':
            return self.bot.send_message(
                m,
                self.bot.trans.errors.api_limit_exceeded,
                extra={'format': 'HTML'})
        elif status == 'OVER_DAILY_LIMIT':
            return self.bot.send_message(m,
                                         self.bot.trans.errors.no_results,
                                         extra={'format': 'HTML'})
        elif status == 'REQUEST_DENIED':
            return self.bot.send_message(
                m,
                self.bot.trans.errors.connection_error,
                extra={'format': 'HTML'})

        lat, lon, locality, country = values

        url = 'http://api.wunderground.com/api/%s/webcams/conditions/forecast/q/%s,%s.json' % (
            self.bot.config.api_keys.weather_underground, lat, lon)

        data = send_request(url)
        if not data or not 'current_observation' in data:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.no_results,
                                         extra={'format': 'HTML'})

        weather = data.current_observation
        forecast = data.forecast.simpleforecast.forecastday
        webcams = data.webcams

        title = self.bot.trans.plugins.weather.strings.title % (locality,
                                                                country)
        temp = weather.temp_c
        feelslike = ""
        try:
            if (float(weather.feelslike_c) - float(weather.temp_c)) > 0.001:
                feelslike = self.bot.trans.plugins.weather.strings.feelslike % weather.feelslike_c
        except:
            pass

        # weather_string = weather.weather.title()
        if weather.icon == '':
            weather.icon = 'clear'
        weather_string = self.bot.trans.plugins.weather.strings[weather.icon]
        weather_icon = self.get_weather_icon(weather.icon)
        humidity = weather.relative_humidity
        wind = format(float(weather.wind_kph) / 3.6, '.1f')

        if is_command(self, 1, m.content):
            message = u'%s\n%s %s%s\n🌡%sºC 💧%s 🌬%s m/s' % (
                remove_html(title), weather_icon, weather_string, feelslike,
                temp, humidity, wind)
            # try:
            #     photo = get_streetview(lat, lon, self.bot.config.api_keys.google_developer_console)
            # except Exception as e:
            #     catch_exception(e, self.bot)
            photo = None

            if photo:
                return self.bot.send_message(m,
                                             photo,
                                             'photo',
                                             extra={'caption': message})
            else:
                return self.bot.send_message(m,
                                             message,
                                             extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            message = self.bot.trans.plugins.weather.strings.titleforecast % (
                locality, country)
            for day in forecast:
                weekday = self.bot.trans.plugins.weather.strings[
                    day.date.weekday.lower()][:3]
                temp = day.low.celsius
                temp_max = day.high.celsius
                # weather_string = day.conditions.title()
                weather_string = self.bot.trans.plugins.weather.strings[
                    day.icon]
                weather_icon = (self.get_weather_icon(day.icon))
                message += u'\n • <b>%s</b>: 🌡 %s-%sºC %s %s' % (
                    weekday, temp, temp_max, weather_icon, weather_string)

            return self.bot.send_message(m, message, extra={'format': 'HTML'})
예제 #31
0
    def run(self, m):
        input = get_input(m)
        baseurl = 'http://www.zaragoza.es/api'

        if is_command(self, 1, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = 'http://api.drk.cat/zgzpls/bus'
            params = {
                'poste': input
            }
            data = send_request(url, params=params)

            if not data or 'errors' in data:
                return self.bot.send_message(m, self.bot.trans.errors.connection_error, extra={'format': 'HTML'})

            if data.street:
                text = '<b>%s</b>\n   Parada: <b>%s</b>  [%s]\n\n' % (data.street, data.poste, data.lines)
            else:
                text = '<b>Parada: %s</b>\n\n' % (data.poste)

            for bus in list(data.buses):
                text += ' • <b>%s</b>  %s <i>%s</i>\n' % (bus['time'], bus['line'], bus['destination'])

            text = text.rstrip('\n')

            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = baseurl + '/recurso/urbanismo-infraestructuras/tranvia/' + input.lstrip('0') + '.json'
            params = {
                'rf': 'html',
                'srsname': 'wgs84'
            }

            data = send_request(url, params=params)
            if 'status' in data:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            tranvias = []

            text = '<b>%s</b>\n   Parada: <b>%s</b>\n\n' % (data['title'].title(), data['id'])

            for destino in data['destinos']:
                tranvias.append((
                    destino['linea'],
                    destino['destino'].rstrip(',').rstrip('.').title(),
                    int(destino['minutos'])
                ))
            
            try:
                tranvias = sorted(tranvias, key=lambda tranvia: tranvia[2])
            except:
                pass

            for tranvia in tranvias:
                text += ' • <b>%s min.</b>  %s <i>%s</i>\n' % (tranvia[2], tranvia[0], tranvia[1])

            text = text.rstrip('\n')
            
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})
           

            url = baseurl + '/recurso/urbanismo-infraestructuras/estacion-bicicleta/' + input.lstrip('0') + '.json'
            params = {
                'rf': 'html',
                'srsname': 'utm30n'
            }

            data = send_request(url, params=params)
            if 'error' in data:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            text = '<b>%s</b>\n   Estación: <b>%s</b>\n\n • Bicis Disponibles: <b>%s</b>\n • Anclajes Disponibles: <b>%s</b>' % (data['title'].title(), data['id'], data['bicisDisponibles'], data['anclajesDisponibles'])
            
            return self.bot.send_message(m, text, extra={'format': 'HTML'})
예제 #32
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={"format": "HTML"})

        lat, lon, locality, country = get_coords(input)

        url = "http://api.wunderground.com/api/%s/webcams/conditions/forecast/q/%s,%s.json" % (
            self.bot.config.api_keys.weather_underground,
            lat,
            lon,
        )

        data = send_request(url)

        try:
            weather = data.current_observation
            forecast = data.forecast.simpleforecast.forecastday
            webcams = data.webcams
        except:
            return self.bot.send_message(m, self.bot.trans.errors.no_results)

        title = self.bot.trans.plugins.weather.strings.title % (locality, country)
        temp = weather.temp_c
        feelslike = ""
        if (float(weather.feelslike_c) - float(weather.temp_c)) > 0.001:
            feelslike = self.bot.trans.plugins.weather.strings.feelslike % weather.feelslike_c
        # weather_string = weather.weather.title()
        weather_string = self.bot.trans.plugins.weather.strings[weather.icon]
        weather_icon = self.get_weather_icon(weather.icon)
        humidity = weather.relative_humidity
        wind = format(float(weather.wind_kph) / 3.6, ".1f")

        if is_command(self, 1, m.content):
            message = u"%s\n%s %s%s\n🌡%sºC 💧%s 🌬%s m/s" % (
                remove_html(title),
                weather_icon,
                weather_string,
                feelslike,
                temp,
                humidity,
                wind,
            )
            try:
                photo = get_streetview(lat, lon, self.bot.config.api_keys.google_developer_console)
            except Exception as e:
                print(e)
                photo = None

            if photo:
                return self.bot.send_message(m, photo, "photo", extra={"caption": message})
            else:
                return self.bot.send_message(m, message, "text", extra={"format": "HTML"})

        elif is_command(self, 2, m.content):
            message = self.bot.trans.plugins.weather.strings.titleforecast % (locality, country)
            for day in forecast:
                weekday = self.bot.trans.plugins.weather.strings[day.date.weekday.lower()][:3]
                temp = day.low.celsius
                temp_max = day.high.celsius
                # weather_string = day.conditions.title()
                weather_string = self.bot.trans.plugins.weather.strings[day.icon]
                weather_icon = self.get_weather_icon(day.icon)
                message += u"\n • <b>%s</b>: 🌡 %s-%sºC %s %s" % (weekday, temp, temp_max, weather_icon, weather_string)

            return self.bot.send_message(m, message, extra={"format": "HTML"})
예제 #33
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, generate_command_help(self, m.content), extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        status, values = get_coords(input, self.bot)

        if status == 'ZERO_RESULTS' or status == 'INVALID_REQUEST':
            return self.bot.send_message(m, self.bot.trans.errors.api_limit_exceeded, extra={'format': 'HTML'})
        elif status == 'OVER_DAILY_LIMIT':
            return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})
        elif status == 'REQUEST_DENIED':
            return self.bot.send_message(m, self.bot.trans.errors.connection_error, extra={'format': 'HTML'})

        lat, lon, locality, country = values

        url = 'https://api.openweathermap.org/data/2.5/weather'
        params = {
            'APPID': self.bot.config.api_keys.open_weather,
            'lon': lon,
            'lat': lat,
            'units': 'metric',
            'lang': 'es'
        }

        data = send_request(url, params, bot=self.bot)
        logging.info(data)
        if not data or data.cod != 200:
            return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

        title = self.bot.trans.plugins.weather.strings.title % (
            locality, country)
        # weather_string = weather.weather.title()
        #weather_string = str(self.bot.trans.plugins.weather.strings[data.weather.id])
        weather_string = data.weather[0].main
        weather_icon = self.get_weather_icon(data.weather[0].icon)
        temp = round(data.main.temp, 1)
        humidity = data.main.humidity
        wind = data.wind.speed
        feelslike = ''
        # try:
        #     temp_c = mc.Temp(data.main.temp, 'c')
        #     feelslike_c = round(mc.heat_index(temperature=temp_c, humidity=humidity), 1)
        #     if (float(feelslike_c) - float(data.main.temp)) > 0.001:
        #         feelslike = self.bot.trans.plugins.weather.strings.feelslike % feelslike_c
        # except:
        #     pass

        if is_command(self, 1, m.content):
            message = u'%s\n%s %s%s\n🌡%sºC 💧%s%% 🌬%s m/s' % (
                remove_html(title), weather_icon, weather_string, feelslike, temp, humidity, wind)
            try:
                photo = get_streetview(
                    lat, lon, self.bot.config.api_keys.google_developer_console)
            except Exception as e:
                catch_exception(e, self.bot)
                photo = None

            if photo:
                return self.bot.send_message(m, photo, 'photo', extra={'caption': message})
            else:
                return self.bot.send_message(m, message, extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            return self.bot.send_message(m, self.bot.trans.errors.not_implemented, extra={'format': 'HTML'})
예제 #34
0
    def run(self, m):
        if is_command(self, 1, m.content):
            username = get_input(m)

            if not username:
                #username = get_setting(self.bot, m.sender.id, 'lastfm.username')
                tags = has_tag(self.bot, m.sender.id,
                               'lastfm:?', return_match=True)
                if tags and len(tags) > 0:
                    username = tags[0].split(':')[1]
                if not username and m.sender.username:
                    username = m.sender.username
                if not username:
                    return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = 'http://ws.audioscrobbler.com/2.0/'
            params = {
                'method': 'user.getrecenttracks',
                'format': 'json',
                'limit': '1',
                'api_key': self.bot.config.api_keys.lastfm,
                'user': username
            }

            lastfm = send_request(url, params=params, bot=self.bot)

            # If the user didn't have any tracks or doesn't exist return No Results error. #
            try:
                last = lastfm.recenttracks.track[0]
            except:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            artist = last.artist['#text'].title()
            track = last.name.title()
            album = last.album['#text'].title()
            track_url = last.url

            try:
                nowplaying = last['@attr'].nowplaying
                if nowplaying == 'true':
                    nowplaying = True
                else:
                    nowplaying == False
            except:
                date = last.date['#text']
                nowplaying = False

            if nowplaying:
                text = self.bot.trans.plugins.lastfm.strings.now_playing % username
            else:
                text = self.bot.trans.plugins.lastfm.strings.last_played % username

            text += '\n🎵 <i>%s</i>\n💽 %s' % (track, artist)
            if album:
                text += ' - %s' % album

            # Gets the link of a Youtube video of the track. #
            url = 'https://www.googleapis.com/youtube/v3/search'
            params = {
                'type': 'video',
                'part': 'snippet',
                'maxResults': '1',
                'q': '%s %s' % (track, artist),
                'key': self.bot.config.api_keys.google_developer_console
            }

            youtube = send_request(url, params=params, bot=self.bot)

            if not 'error' in youtube and len(youtube['items']) > 0:
                text += '\n\n🌐 %s\n%s\nhttps://youtu.be/%s' % (
                    self.bot.trans.plugins.lastfm.strings.might_be, youtube['items'][0].snippet.title, youtube['items'][0].id.videoId)

            self.bot.send_message(
                m, text, extra={'format': 'HTML', 'preview': False})

        elif is_command(self, 2, m.content):
            input = get_input(m)
            if not input:
                return self.bot.send_message(m, generate_command_help(self, m.content), extra={'format': 'HTML'})
                # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            # set_setting(self.bot, m.sender.id, 'lastfm.username', input)
            del_tag(self.bot, m.sender.id, 'lastfm:?')
            set_tag(self.bot, m.sender.id, 'lastfm:%s' % input)
            self.bot.send_message(m, self.bot.trans.plugins.lastfm.strings.username_set, extra={
                                  'format': 'HTML', 'preview': False})
    def run(self, m):
        input = get_input(m)
        baseurl = 'http://www.zaragoza.es/api'

        if is_command(self, 1, m.content):
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
                # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = 'http://api.drk.cat/zgzpls/bus/stations'
            params = {'number': input}
            data = send_request(url, params=params)

            if not data or 'errors' in data:
                if data and 'errors' in data and 'status' in data.errors and data.errors.status == '404 Not Found':
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.no_results,
                        extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.connection_error,
                        extra={'format': 'HTML'})

            if data.street:
                text = '<b>%s</b>\n   Parada: <b>%s</b>  [%s]\n\n' % (
                    data.street, data.number, data.lines)
            else:
                text = '<b>Parada: %s</b>\n\n' % (data.number)

            for bus in list(data.transports):
                text += ' • <b>%s</b>  %s <i>%s</i>\n' % (bus.time, bus.line,
                                                          bus.destination)

            text = text.rstrip('\n')

            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
                # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = 'http://api.drk.cat/zgzpls/tram/stations'
            try:
                int(input)
                params = {'number': input}
            except ValueError:
                params = {'street': input}

            data = send_request(url, params=params)

            if not data or 'errors' in data:
                if data and 'errors' in data and 'status' in data.errors and data.errors.status == '404 Not Found':
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.no_results,
                        extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.connection_error,
                        extra={'format': 'HTML'})

            if data.street:
                text = '<b>%s</b>\n   Parada: <b>%s</b>  [%s]\n\n' % (
                    data.street, data.number, data.lines)
            else:
                text = '<b>Parada: %s</b>\n\n' % (data.number)

            for bus in list(data.transports):
                text += ' • <b>%s</b>  %s <i>%s</i>\n' % (bus.time, bus.line,
                                                          bus.destination)

            text = text.rstrip('\n')

            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
                # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            url = baseurl + '/recurso/urbanismo-infraestructuras/estacion-bicicleta/' + \
                input.lstrip('0') + '.json'
            params = {'rf': 'html', 'srsname': 'utm30n'}

            data = send_request(url, params=params)

            if not data or 'error' in data or 'errors' in data:
                if data and 'error' in data and data.error == 'Parametros incorrectos':
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.no_results,
                        extra={'format': 'HTML'})
                elif data and 'errors' in data and 'status' in data.errors and data.errors.status == '404 Not Found':
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.no_results,
                        extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.connection_error,
                        extra={'format': 'HTML'})

            text = '<b>%s</b>\n   Estación: <b>%s</b>\n\n • Bicis Disponibles: <b>%s</b>\n • Anclajes Disponibles: <b>%s</b>' % (
                data.title.title(), data.id, data.bicisDisponibles,
                data.anclajesDisponibles)

            return self.bot.send_message(m, text, extra={'format': 'HTML'})