Beispiel #1
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'})

        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)
Beispiel #2
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'})

        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)
    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)
Beispiel #4
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'})

        self.bot.send_message(m, input.capitalize(), extra={'format': 'Markdown'})
Beispiel #5
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 = ""
        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'})
Beispiel #6
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'})

        langs = [
            'af', 'aq', 'ar', 'hy', 'ca', 'zh', 'zh-cn', 'zh-tw', 'zh-yue',
            'hr', 'cs', 'da', 'nl', 'en-au', 'en-uk', 'en-us', 'eo', 'fi',
            'fr', 'de', 'el', 'ht', 'hu', 'is', 'id', 'it', 'ja', 'ko', 'la',
            'lv', 'mk', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru', 'sr', 'sk',
            'es', 'es-es', 'es-us', 'sw', 'sv', 'ta', 'th', 'tr', 'vi', 'cy'
        ]

        for lang in langs:
            if first_word(input) == lang:
                language = lang
                text = all_but_first_word(input)
                break
            else:
                if self.bot.config.translation != 'default':
                    language = 'es-es'
                else:
                    language = 'en-us'
                text = input

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

        url = 'http://translate.google.com/translate_tts'
        params = {
            'tl': language,
            'q': text,
            'ie': 'UTF-8',
            'total': len(text),
            'idx': 0,
            'client': 'tw-ob',
            'key': self.bot.config.api_keys.google_developer_console
        }
        headers = {
            "Referer":
            'http://translate.google.com/',
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.8 Safari/537.36"
        }

        file = download(url, params, headers)
        voice = mp3_to_ogg(file)

        if voice:
            return self.bot.send_message(m, voice, 'voice')
        else:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.download_failed)
Beispiel #7
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})
Beispiel #8
0
    def run(self, m):
        input = get_input(m)

        if not is_owner(self.bot, m.sender.id) and not is_trusted(self.bot, m.sender.id):
            return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

        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'})

        if not m.reply:
            input = all_but_first_word(input)

        target = get_target(self.bot, m, get_input(m))
        if target:
            name = get_username(self.bot, target, False)

        elif first_word(input) == '-g':
            target = str(m.conversation.id)
            name = get_username(self.bot, target, False)

        else:
            target = str(m.sender.id)
            name = get_username(self.bot, target, False)

        tags = input.split()

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

        # Adds a tag to user or group. #
        if is_command(self, 1, m.content):
            for tag in tags:
                if not has_tag(self.bot, target, tag):
                    set_tag(self.bot, target, tag)
            return self.bot.send_message(m, self.bot.trans.plugins.tags.strings.tagged % (name, tags), extra={'format': 'HTML'})

        # Removes a tag from user or group. #
        elif is_command(self, 2, m.content):
            for tag in tags:
                if has_tag(self.bot, target, tag):
                    del_tag(self.bot, target, tag)
            return self.bot.send_message(m, self.bot.trans.plugins.tags.strings.untagged % (name, tags), extra={'format': 'HTML'})
Beispiel #9
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'})

        self.bot.send_message(m, input, extra={'format': 'Markdown'})
Beispiel #10
0
    def run(self, m):
        input = get_input(m)

        if not is_trusted(self.bot, m.sender.id):
            return self.bot.send_message(
                m,
                self.bot.trans.errors.permission_required,
                extra={'format': 'HTML'})

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

        if m.reply:
            target = str(m.reply.sender.id)
            name = m.reply.sender.first_name

        elif first_word(input) == '-g':
            target = str(m.conversation.id)
            name = m.conversation.title
            input = all_but_first_word(input)

        elif first_word(input).isdigit():
            target = first_word(input)
            name = target
            input = all_but_first_word(input)

        else:
            target = str(m.sender.id)
            name = m.sender.first_name

        tags = input.split()

        # Adds a tag to user or group. #
        if is_command(self, 1, m.content):
            for tag in tags:
                if not has_tag(self.bot, target, tag):
                    set_tag(self.bot, target, tag)
            return self.bot.send_message(
                m,
                self.bot.trans.plugins.tags.strings.tagged % (name, tags),
                extra={'format': 'HTML'})

        # Removes a tag from user or group. #
        elif is_command(self, 2, m.content):
            for tag in tags:
                if has_tag(self.bot, target, tag):
                    del_tag(self.bot, target, tag)
            return self.bot.send_message(
                m,
                self.bot.trans.plugins.tags.strings.untagged % (name, tags),
                extra={'format': 'HTML'})
Beispiel #11
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
                                  })
Beispiel #12
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'})

        self.bot.send_message(m, input.capitalize())
Beispiel #13
0
    def run(self, m):
        if not is_trusted(self.bot, m.sender.id):
            return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

        input = get_input(m)
        text = self.bot.trans.errors.no_results

        # Shutdown
        if is_command(self, 1, m.content):
            self.bot.stop()
            text = self.bot.trans.plugins.core.strings.shutting_down

        # Reload plugins
        elif is_command(self, 2, m.content):
            self.plugins = self.init_plugins()
            text = self.bot.trans.plugins.core.strings.reloading_plugins

        # Reload database
        elif is_command(self, 3, m.content):
            self.bot.get_database()
            text = self.bot.trans.plugins.core.strings.reloading_database

        # Send messages
        elif is_command(self, 4, m.content):
            text = self.bot.trans.errors.not_implemented

        # Run shell commands
        elif is_command(self, 5, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})
            return self.bot.send_message(m, '<code>%s</code>' % (subprocess.getoutput(input)), extra={'format': 'HTML'})

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

            cout = StringIO()
            sys.stdout = cout
            cerr = StringIO()
            sys.stderr = cerr

            exec(input)

            if cout.getvalue():
                return self.bot.send_message(m, '<code>%s</code>' % str(cout.getvalue()), extra={'format': 'HTML'})

            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__

        if text:
            self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #14
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'})

        delay = first_word(input)
        if delay:
            delaytime = delay[:-1]
            unit = delay[-1:]
            if not is_int(delaytime) or is_int(unit) or not self.to_seconds(
                    delaytime, unit):
                return self.bot.send_message(
                    m, self.bot.trans.plugins.reminders.strings.wrongdelay)

        alarm = time() + self.to_seconds(delaytime, unit)

        text = all_but_first_word(input)
        if not text:
            return self.bot.send_message(
                m, self.bot.trans.plugins.reminders.strings.noreminder)

        reminder = DictObject(OrderedDict())
        reminder.id = '%s:%s' % (m.sender.id, time())
        reminder.alarm = alarm
        reminder.chat_id = m.conversation.id
        reminder.text = text
        reminder.first_name = m.sender.first_name
        if m.sender.username:
            reminder.username = m.sender.username

        self.bot.reminders = wait_until_received('reminders/' + self.bot.name)
        self.sort_reminders()
        self.bot.reminders['list'].append(reminder)
        self.sort_reminders()

        if unit == 's':
            delay = delay.replace('s', ' seconds')
        if unit == 'm':
            delay = delay.replace('m', ' minutes')
        if unit == 'h':
            delay = delay.replace('h', ' hours')
        if unit == 'd':
            delay = delay.replace('d', ' days')

        message = self.bot.trans.plugins.reminders.strings.added % (
            m.sender.first_name, delay, text)

        return self.bot.send_message(m, message, extra={'format': 'HTML'})
    def run(self, m):
        url = 'https://www.worldometers.info/coronavirus/'

        country = get_input(m, ignore_reply=False)
        if country:
            url += 'country/' + country.lower().lstrip()

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

        res = requests.get(url)

        if res.status_code != 200:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.connection_error,
                extra={'format': 'HTML'})

        soup = BeautifulSoup(res.text, 'html.parser')

        try:
            counters = soup.findAll(class_='maincounter-number')
            cases = counters[0].find('span').get_text()
            deaths = counters[1].find('span').get_text()
            recovered = counters[2].find('span').get_text()

            text = None
            if country:
                text = self.bot.trans.plugins.coronavirus.strings.input_result % (
                    country.title(), cases, deaths, recovered)
            else:
                text = self.bot.trans.plugins.coronavirus.strings.result % (
                    cases, deaths, recovered)

            text += '\n\n<a href="%s">%s</a>' % (
                url, self.bot.trans.plugins.coronavirus.strings.source)

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

        except Exception as e:
            self.bot.send_message(m,
                                  self.bot.trans.errors.no_results,
                                  extra={'format': 'HTML'})
Beispiel #16
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'})

        self.reminders.load_database()
        # Lists all pins #
        delay = first_word(input)
        if delay:
            delaytime = delay[:-1]
            unit = delay[-1:]
            if not is_int(delaytime) or is_int(unit):
                return self.bot.send_message(
                    m, self.bot.trans.plugins.reminders.strings.wrongdelay)

        alarm = time() + self.to_seconds(delaytime, unit)

        text = all_but_first_word(input)
        if not text:
            return self.bot.send_message(
                m, self.bot.trans.plugins.reminders.strings.noreminder)

        reminder = DictObject(OrderedDict())
        reminder.id = '%s:%s' % (m.sender.id, time())
        reminder.alarm = alarm
        reminder.chat_id = m.conversation.id
        reminder.text = text
        reminder.first_name = m.sender.first_name
        reminder.username = m.sender.username

        self.reminders.list.append(reminder)
        self.sort_reminders()
        self.reminders.store_database()

        if unit == 's':
            delay = delay.replace('s', ' segundos')
        if unit == 'm':
            delay = delay.replace('m', ' minutos')
        if unit == 'h':
            delay = delay.replace('h', ' horas')
        if unit == 'd':
            delay = delay.replace('d', ' días')

        message = self.bot.trans.plugins.reminders.strings.added % (
            m.sender.first_name, delay, text)

        return self.bot.send_message(m, message, extra={'format': 'HTML'})
Beispiel #17
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'})

        langs = [
            'af', 'aq', 'ar', 'hy', 'ca', 'zh', 'zh-cn', 'zh-tw', 'zh-yue',
            'hr', 'cs', 'da', 'nl', 'en-au', 'en-uk', 'en-us', 'eo',
            'fi', 'fr', 'de', 'el', 'ht', 'hu', 'is', 'id',
            'it', 'ja', 'ko', 'la', 'lv', 'mk', 'no', 'pl',
            'pt', 'pt-br', 'ro', 'ru', 'sr', 'sk', 'es', 'es-es',
            'es-us', 'sw', 'sv', 'ta', 'th', 'tr', 'vi', 'cy'
        ]

        for lang in langs:
            if first_word(input) == lang:
                language = lang
                text = all_but_first_word(input)
                break
            else:
                language = 'en-us'
                text = input
                
        if not text:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

        url = 'http://translate.google.com/translate_tts'
        params = {
            'tl': language,
            'q': text,
            'ie': 'UTF-8',
            'total': len(text),
            'idx': 0,
            'client': 'tw-ob',
            'key': self.bot.config.api_keys.google_developer_console
        }
        headers = {
            "Referer": 'http://translate.google.com/',
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.8 Safari/537.36"
        }
        file = download(url, params, headers)
        voice = mp3_to_ogg(file)

        if voice:
            return self.bot.send_message(m, voice, 'voice')
        else:
            return self.bot.send_message(m, self.bot.trans.errors.download_failed)
    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
                                  })
Beispiel #19
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)
Beispiel #20
0
    def inline(self, m):
        input = get_input(m)

        results = []

        for plugin in self.bot.plugins:
            if hasattr(plugin, 'inline') and hasattr(plugin, 'commands'):
                for command in plugin.commands:
                    if not 'hidden' in command or not command.hidden:
                        title = command.command.replace('/', '')

                        if 'description' in command:
                            description = command.description
                        else:
                            description = ''

                        parameters = ''
                        if 'parameters' in command and command.parameters:
                            for parameter in command.parameters:
                                name, required = list(parameter.items())[0]
                                # Bold for required parameters, and italic for optional #
                                if required:
                                    parameters = ' <b>&lt;{}&gt;</b>'.format(
                                        name)
                                else:
                                    parameters = ' [{}]'.format(name)

                        results.append({
                            'type':
                            'article',
                            'id':
                            command.command.replace('/',
                                                    self.bot.config.prefix),
                            'title':
                            title,
                            'input_message_content': {
                                'message_text':
                                command.command.replace(
                                    '/', self.bot.config.prefix)
                            },
                            'description':
                            description
                        })

        self.bot.answer_inline_query(m, results)
Beispiel #21
0
    def run(self, m):
        if m.conversation.id > 0:
            return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

        input = get_input(m, ignore_reply=False)
        parameter = first_word(input)
        enabled = ['reactions', 'roulette',
                   'replies', 'pole', 'fiesta', 'nsfw']
        disabled = ['antispam', 'antiarab', 'antirussian', 'polereset']
        config = {}

        for param in enabled:
            config[param] = not has_tag(
                self.bot, m.conversation.id, 'no' + param)

        for param in disabled:
            config[param] = has_tag(self.bot, m.conversation.id, param)

        text = ''
        if not input:
            text = self.bot.trans.plugins.config.strings.explanation % "', '".join(
                config)
            for param in config:
                text += '\n' + ('✔️' if config[param] else '❌') + \
                    ' ' + self.bot.trans.plugins.config.strings[param]

        elif parameter in enabled or parameter in disabled:
            if not is_admin(self.bot, m.sender.id, m) and not is_trusted(self.bot, m.sender.id, m):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if config[parameter]:
                if parameter in enabled:
                    set_tag(self.bot, m.conversation.id, 'no' + parameter)
                elif parameter in disabled:
                    del_tag(self.bot, m.conversation.id, parameter)
            else:
                if parameter in enabled:
                    del_tag(self.bot, m.conversation.id, 'no' + parameter)
                elif parameter in disabled:
                    set_tag(self.bot, m.conversation.id, parameter)

            text = ('❌' if config[parameter] else '✔️') + \
                ' ' + self.bot.trans.plugins.config.strings[parameter]

        return self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #22
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"})

        self.reminders.load_database()
        # Lists all pins #
        delay = first_word(input)
        if delay:
            delaytime = delay[:-1]
            unit = delay[-1:]
            if not is_int(delaytime) or is_int(unit):
                return self.bot.send_message(m, self.bot.trans.plugins.reminders.strings.wrongdelay)

        alarm = time() + self.to_seconds(delaytime, unit)

        text = all_but_first_word(input)
        if not text:
            return self.bot.send_message(m, self.bot.trans.plugins.reminders.strings.noreminder)

        reminder = DictObject(OrderedDict())
        reminder.id = "%s:%s" % (m.sender.id, time())
        reminder.alarm = alarm
        reminder.chat_id = m.conversation.id
        reminder.text = text
        reminder.first_name = m.sender.first_name
        reminder.username = m.sender.username

        self.reminders.list.append(reminder)
        self.sort_reminders()
        self.reminders.store_database()

        if unit == "s":
            delay = delay.replace("s", " seconds")
        if unit == "m":
            delay = delay.replace("m", " minutes")
        if unit == "h":
            delay = delay.replace("h", " hours")
        if unit == "d":
            delay = delay.replace("d", " days")

        message = self.bot.trans.plugins.reminders.strings.added % (m.sender.first_name, delay, text)

        return self.bot.send_message(m, message, extra={"format": "HTML"})
Beispiel #23
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
                                  })
Beispiel #24
0
    def run(self, m):
        if not is_trusted(self.bot, m.sender.id):
            return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

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

        input = get_input(m)
        if m.reply:
            target = str(m.reply.sender.id)
            name = m.reply.sender.first_name

        elif first_word(input) == '-g':
            target = str(m.conversation.id)
            name = m.conversation.title
            input = all_but_first_word(input)

        elif first_word(input).isdigit():
            target = first_word(input)
            name = target
            input = all_but_first_word(input)

        else:
            target = str(m.sender.id)
            name = m.sender.first_name

        tags = input.split()

        # Adds a tag to user or group. #
        if is_command(self, 1, m.content):
            for tag in tags:
                if not has_tag(self.bot, target, tag):
                    set_tag(self.bot, target, tag)
            return self.bot.send_message(m, self.bot.trans.plugins.tags.strings.tagged % (name, tags), extra={'format': 'HTML'})

        # Removes a tag from user or group. #
        elif is_command(self, 2, m.content):
            for tag in tags:
                if has_tag(self.bot, target, tag):
                    del_tag(self.bot, target, tag)
            return self.bot.send_message(m, self.bot.trans.plugins.tags.strings.untagged % (name, tags), extra={'format': 'HTML'})
Beispiel #25
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)
Beispiel #26
0
    def inline(self, m):
        input = get_input(m)

        results = []

        result = {
            'type': 'article',
            'id': '0',
            'title': 'test',
            'input_message_content': {
                'message_text': 'this is a test',
                'parse_mode': 'HTML'
            },
            'description': 'test description'
        }

        results.append(result)

        extra = {
            'switch_pm_text': 'switch to pm',
            'switch_pm_parameter': 'test'
        }

        self.bot.answer_inline_query(m, results, extra)
Beispiel #27
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
                    })
Beispiel #28
0
    def run(self, m):
        input = get_input(m)

        if input:
            for plugin in self.bot.plugins:
                text = plugin.description

                for command in plugin.commands:
                    command = DictObject(command)
                    # If the command is hidden, ignore it #
                    if ('hidden' in command
                            and not command.hidden) or not 'hidden' in command:
                        # Adds the command and parameters#
                        if input in command.command.replace('/',
                                                            '').rstrip('\s'):
                            text += '\n • ' + command.command.replace(
                                '/', self.bot.config.prefix)
                            if 'parameters' in command and command.parameters:
                                for parameter in command.parameters:
                                    name, required = list(parameter.items())[0]
                                    # Bold for required parameters, and italic for optional #
                                    if required:
                                        text += ' <b>&lt;%s&gt;</b>' % name
                                    else:
                                        text += ' [%s]' % name

                            if 'description' in command:
                                text += '\n   <i>%s</i>' % command.description
                            else:
                                text += '\n   <i>?¿</i>'

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

        if is_command(self, 3, m.content):
            text = ''
        else:
            text = self.bot.trans.plugins.help.strings.commands

        # Iterates the initialized plugins #
        for plugin in self.bot.plugins:
            for command in plugin.commands:
                command = DictObject(command)
                # If the command is hidden, ignore it #
                if not 'hidden' in command or not command.hidden:
                    # Adds the command and parameters#
                    if is_command(self, 3, m.content):
                        show = False
                        if 'parameters' in command and command.parameters:
                            allOptional = True
                            for parameter in command.parameters:
                                name, required = list(parameter.items())[0]
                                if required:
                                    allOptional = False

                            show = allOptional

                        else:
                            show = True

                        if show:
                            text += '\n' + command.command.lstrip('/')

                            if 'description' in command:
                                text += ' - %s' % command.description
                            else:
                                text += ' - ?¿'

                    else:
                        text += '\n • ' + command.command.replace(
                            '/', self.bot.config.prefix)
                        if 'parameters' in command and command.parameters:
                            for parameter in command.parameters:
                                name, required = list(parameter.items())[0]
                                # Bold for required parameters, and italic for optional #
                                if required:
                                    text += ' <b>&lt;%s&gt;</b>' % name
                                else:
                                    text += ' [%s]' % name

                        if 'description' in command:
                            text += '\n   <i>%s</i>' % command.description
                        else:
                            text += '\n   <i>?¿</i>'

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #29
0
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.pins:
                if self.pins[pin].creator == m.sender.id:
                    pins.append(pin)

            if len(pins) > 0:
                text = self.bot.trans.plugins.pins.strings.pins % len(pins)
                for pin in pins:
                    text += '\n • #%s' % pin

            else:
                text = self.bot.trans.plugins.pins.strings.no_pins

            # If the message is too long send an error message instead #
            if len(text) < 4096:
                return self.bot.send_message(m, text, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Add a pin #
        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'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not m.reply:
                return self.bot.send_message(m, self.bot.trans.errors.needs_reply, extra={'format': 'HTML'})

            if input in self.pins:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.already_pinned % input, extra={'format': 'HTML'})

            self.pins[input] = {
                'content': m.reply.content.replace('<','&lt;').replace('>','&gt;'),
                'creator': m.sender.id,
                'type': m.reply.type
            }
            
            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.pinned % input, extra={'format': 'HTML'})

        # Remove a pin #
        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'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not input in self.pins:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.not_found % input, extra={'format': 'HTML'})

            if not m.sender.id == self.pins[input]['creator']:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.not_creator % input, extra={'format': 'HTML'})

            del(self.pins[input])
            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.unpinned % input, extra={'format': 'HTML'})

        # Check what pin was triggered #
        else:
            # Finds the first 3 pins of the message and sends them. #
            pins = findall(r"#(\w+)", m.content.lower())
            count = 3

            for pin in pins:
                if pin in self.pins:
                    # You can reply with a pin and the message will reply too. #
                    if m.reply:
                        reply = m.reply.id
                    else:
                        reply = m.id

                    self.bot.send_message(m, self.pins[pin]['content'], self.pins[pin]['type'], extra={'format': 'HTML'}, reply = reply)
                    count -= 1

                if count == 0:
                    return
Beispiel #30
0
    def run(self, m):
        input = get_input(m)

        if input:
            for plugin in self.bot.plugins:
                text = plugin.description
                for command in plugin.commands:
                    # If the command is hidden, ignore it #
                    if not 'hidden' in command or not command['hidden']:
                        # Adds the command and parameters#
                        if input in command['command'].replace('/', '').rstrip('\s'):
                            text += '\n • ' + command['command'].replace('/', self.bot.config.prefix)
                            if 'parameters' in command:
                                for parameter in command['parameters']:
                                    name, required = list(parameter.items())[0]
                                    # Bold for required parameters, and italic for optional #
                                    if required:
                                        text += ' <b>&lt;%s&gt;</b>' % name
                                    else:
                                        text += ' [%s]' % name

                            if 'description' in command:
                                text += '\n   <i>%s</i>' % command['description']
                            else:
                                text += '\n   <i>?¿</i>'

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

        
        if is_command(self, 3, m.content):
            text = ''
        else:
            text = self.bot.trans.plugins.help.strings.commands

        # Iterates the initialized plugins #
        for plugin in self.bot.plugins:
            for command in plugin.commands:
                # If the command is hidden, ignore it #
                if not 'hidden' in command or not command['hidden']:
                    # Adds the command and parameters#
                    if self.commands[-1]['command'].replace('/', self.bot.config.prefix) in m.content:
                        text += '\n' + command['command'].lstrip('/')

                        if 'description' in command:
                            text += ' - %s' % command['description']
                        else:
                            text += ' - ?¿'
                    else:
                        text += '\n • ' + command['command'].replace('/', self.bot.config.prefix)
                        if 'parameters' in command:
                            for parameter in command['parameters']:
                                name, required = list(parameter.items())[0]
                                # Bold for required parameters, and italic for optional #
                                if required:
                                    text += ' <b>&lt;%s&gt;</b>' % name
                                else:
                                    text += ' [%s]' % name

                        if 'description' in command:
                            text += '\n   <i>%s</i>' % command['description']
                        else:
                            text += '\n   <i>?¿</i>'

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #31
0
    def run(self, m):
        input = get_input(m)
        commands = []

        if is_command(self, 2, m.content):
            text = ''
        else:
            text = self.bot.trans.plugins.help.strings.commands

        # Iterates the initialized plugins #
        for plugin in self.bot.plugins:
            if hasattr(plugin, 'commands'):
                for command in plugin.commands:
                    command = DictObject(command)
                    # Adds the command and parameters#
                    if is_command(self, 2, m.content):
                        show = False
                        if 'parameters' in command and command.parameters:
                            allOptional = True
                            for parameter in command.parameters:
                                name, required = list(parameter.items())[0]
                                if required:
                                    allOptional = False

                            show = allOptional

                        else:
                            show = True

                        if self.bot.config.prefix != '/' and (
                                not 'keep_default' in command
                                or not command.keep_default):
                            show = False

                        if not command.command.startswith('/'):
                            show = False

                        if show:
                            text += '\n' + command.command.lstrip('/')

                            if 'description' in command:
                                text += ' - {}'.format(command.description)
                                commands.append({
                                    'command':
                                    command.command.lstrip('/'),
                                    'description':
                                    command.description
                                })
                            else:
                                text += ' - No description'
                                commands.append({
                                    'command':
                                    command.command.lstrip('/'),
                                    'description':
                                    'No description'
                                })

                    else:
                        # If the command is hidden, ignore it #
                        if not 'hidden' in command or not command.hidden:
                            doc = generate_command_help(
                                plugin, command['command'], False)
                            if doc:
                                lines = doc.splitlines()

                                text += '\n • {}'.format(lines[0])

                                if len(lines) > 1:
                                    text += '\n   {}'.format(lines[1])
                                else:
                                    text += '\n   <i>No description</i>'

        if is_command(self, 2, m.content):
            self.bot.send_message(m,
                                  'setMyCommands',
                                  'api',
                                  extra={'commands': json.dumps(commands)})

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #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"})
Beispiel #33
0
    def run(self, m):
        input = get_input(m)
        uid = str(m.sender.id)
        gid = str(m.conversation.id)

        # List all administration commands. #
        if is_command(self, 1, m.content):
            text = self.bot.trans.plugins.administration.strings.commands
            for command in self.commands:
                # Adds the command and parameters#
                if self.commands[-1]['command'].replace('/', self.bot.config.prefix) in m.content:
                    text += '\n' + command['command'].lstrip('/')

                    if 'description' in command:
                        text += ' - %s' % command['description']
                    else:
                        text += ' - ?¿'
                else:
                    text += '\n • ' + command['command'].replace('/', self.bot.config.prefix)
                    if 'parameters' in command:
                        for parameter in command['parameters']:
                            name, required = list(parameter.items())[0]
                            # Bold for required parameters, and italic for optional #
                            if required:
                                text += ' <b>&lt;%s&gt;</b>' % name
                            else:
                                text += ' [%s]' % name

                    if 'description' in command:
                        text += '\n   <i>%s</i>' % command['description']
                    else:
                        text += '\n   <i>?¿</i>'
                        text += '\n   <i>?¿</i>'

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

        # List all groups. #
        if is_command(self, 2, m.content):
            text = self.bot.trans.plugins.administration.strings.groups
            for gid, attr in self.administration.items():
                text += '\n • %s |%s|' % (self.groups[gid]['title'], attr['alias'])
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # Join a group. #
        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'})

            for id in self.administration:
                if (input in self.administration or
                    input in self.administration[id]['alias'] or
                    input in self.groups[id]['title']):
                    gid_to_join = id
                    break

            if not gid_to_join in self.administration:
                return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (self.groups[gid_to_join]['title'], self.administration[gid_to_join]['description'], self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid_to_join]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1
            if not self.administration[gid_to_join]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if not self.administration[gid_to_join]['link']:
                text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
            else:
                text += '\n\n<a href="%s">%s</a>' % (self.administration[gid_to_join]['link'], self.bot.trans.plugins.administration.strings.join)
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Information about a group. #
        elif is_command(self, 4, m.content) or is_command(self, 9, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})
            if not gid in self.administration:
                if is_command(self, 4, m.content):
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})
                elif is_command(self, 9, m.content):
                    return

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (self.groups[gid]['title'], self.administration[gid]['description'], self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if is_command(self, 4, m.content):
                if not self.administration[gid]['link']:
                    text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
                else:
                    text += '\n\n<a href="%s">%s</a>' % (self.bot.trans.plugins.administration.strings.join. self.administration[gid]['link'])
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Rules of a group. #
        elif is_command(self, 5, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})
            if not gid in self.administration:
                return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            if input and is_int(input):
                try:
                    i = int(input)
                    text = '%s. <i>%s</i>' % (i, self.administration[gid]['rules'][i - 1])
                except:
                    text = self.bot.trans.plugins.administration.strings.notfound

            else:
                text = self.bot.trans.plugins.administration.strings.rules
                i = 1
                for rule in self.administration[gid]['rules']:
                    text += '\n %s. <i>%s</i>' % (i, rule)
                    i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Kicks a user. #
        elif is_command(self, 6, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

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

            if m.reply:
                target = m.reply.sender.id
            elif input:
                target = input
            else:
                target = m.sender.id

            res = self.bot.kick_user(m, target)
            self.bot.unban_user(m, target)
            if res is None:
                return self.bot.send_message(m, self.bot.trans.errors.admin_required, extra={'format': 'HTML'})
            elif not res:
                return self.bot.send_message(m, self.bot.trans.errors.failed, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m, '<pre>An enemy has been slain.</pre>', extra={'format': 'HTML'})

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

        # Bans a user. #
        elif is_command(self, 7, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

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

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

        # Configures a group. #
        elif is_command(self, 8, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_trusted(self.bot, m.sender.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            parameters = [
                'add',
                'remove',
                'alias',
                'description',
                'rules',
                'rule'
            ]

            if not input:
                text = '<b>Available commands:</b>'
                for param in parameters:
                    text += '\n • %scfg %s' % (self.bot.config.prefix, param)
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if first_word(input) == 'add':
                if not gid in self.administration:
                    self.administration[gid] = {
                        'alias': None,
                        'description': None,
                        'link': None,
                        'rules': []
                    }
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.added % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.already_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'remove':
                if gid in self.administration:
                    del(self.administration[gid])
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.removed % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'alias':
                if gid in self.administration:
                    self.administration[gid]['alias'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'description':
                if gid in self.administration:
                    self.administration[gid]['description'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'link':
                if gid in self.administration:
                    self.administration[gid]['link'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rules':
                if gid in self.administration:
                    self.administration[gid]['rules'] = all_but_first_word(input).split('\n')[0:]
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rule':
                if gid in self.administration:
                    try:
                        i = int(first_word(all_but_first_word(input)))-1
                        if i > len(self.administration[gid]['rules']):
                            i = len(self.administration[gid]['rules'])
                        elif i < 1:
                            i = 0
                    except:
                        return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})
                    self.administration[gid]['rules'].insert(i, all_but_first_word(all_but_first_word(input)))
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})


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

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})
Beispiel #34
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'})
Beispiel #35
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})
Beispiel #36
0
    def run(self, m):
        input = get_input(m)

        gid = str(m.conversation.id)
        if input:
            target = '0'
            if is_int(input):
                target = input

            elif input.startswith('@'):
                for uid in self.bot.users:
                    if 'username' in self.bot.users[uid] and self.bot.users[uid].username.lower() == input[1:].lower():
                        target = str(uid)
                        break

            else:
                self.bot.send_message(m, self.bot.trans.errors.invalid_syntax, extra={'format': 'HTML'})

        elif m.reply:
            target = str(m.reply.sender.id)

        else:
            target = str(m.sender.id)

        text = ''

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

        if int(target) > 0:
            if target in self.bot.users:
                if 'first_name' in self.bot.users[target] and self.bot.users[target].first_name:
                    user = self.bot.users[target].first_name

                if 'last_name' in self.bot.users[target] and self.bot.users[target].last_name:
                    user += ' ' + self.bot.users[target].last_name

                if 'username' in self.bot.users[target] and self.bot.users[target].username:
                    user += '\n\t     @' + self.bot.users[target].username
                    
                text = self.bot.trans.plugins.info.strings.user_info % (user, target, self.bot.users[target].messages)

            if target in self.bot.tags:
                text += '\n🏷 '
                for tag in self.bot.tags[target]:
                    text += tag + ', '
                text = text[:-2]
        else:
            if target in self.bot.groups:
                if 'title' in self.bot.groups[target] and self.bot.groups[target].title:
                    group = self.bot.groups[target].title

                text = self.bot.trans.plugins.info.strings.group_info % (group, target, self.bot.groups[target].messages)

            if gid in self.bot.tags:
                text += '\n🏷 '
                for tag in self.bot.tags[gid]:
                    text += tag + ', '
                text = text[:-2]

        if int(gid) < 0 and not input:
            text += '\n\n'
            if gid in self.bot.groups:
                if 'title' in self.bot.groups[gid] and self.bot.groups[gid].title:
                    group = self.bot.groups[gid].title

                text += self.bot.trans.plugins.info.strings.group_info % (group, gid, self.bot.groups[gid].messages)

            if gid in self.bot.tags:
                text += '\n🏷 '
                for tag in self.bot.tags[gid]:
                    text += tag + ', '
                text = text[:-2]

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #37
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'})
    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'})
Beispiel #39
0
    def run(self, m):
        gid = str(m.conversation.id)
        target = get_target(self.bot, m, get_input(m))

        text = ''
        name = ''
        username = ''
        description = ''
        tags = ''
        messages = 0
        members = 0
        invite_link = None

        gname = ''
        gusername = ''
        gdescription = ''
        gtags = ''
        gmessages = 0
        gmembers = 0
        ginvite_link = None

        if target and int(target) > 0:
            info = self.bot.bindings.server_request(
                'getUser',  {'user_id': int(target)})
            info_full = self.bot.bindings.server_request(
                'getUserFullInfo',  {'user_id': int(target)})

        else:
            if target and target.startswith('-100'):
                info = self.bot.bindings.server_request(
                    'getSupergroup',  {'supergroup_id': int(target[4:])})
                info_full = self.bot.bindings.server_request(
                    'getSupergroupFullInfo',  {'supergroup_id': int(target[4:])})

        if target and (int(target) == 0 or not (target in self.bot.users or target in self.bot.groups or info)):
            return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

        if target:
            if int(target) > 0:
                if target in self.bot.users:
                    name = get_full_name(self.bot, target, False)

                    if 'username' in self.bot.users[target] and self.bot.users[target].username:
                        username = '******' + self.bot.users[target].username

                    if 'description' in self.bot.users[target]:
                        description = self.bot.users[target]['description']

                    messages = self.bot.users[target].messages

                else:
                    if info:
                        self.bot.users[target] = {
                            'first_name': info['first_name'],
                            'last_name': info['last_name'],
                            'messages': 0
                        }

                if info:
                    name = info['first_name'] + ' ' + info['last_name']

                    if len(info['username']) > 0:
                        username = '******' + info['username']
                        self.bot.users[target]['username'] = username

                if info_full:
                    description = info_full['bio']
                    self.bot.users[target]['description'] = description

                set_data('users/%s/%s' %
                         (self.bot.name, target), self.bot.users[target])

                if target in self.bot.tags:
                    for tag in self.bot.tags[target]:
                        tags += tag + ', '
                    tags = tags[:-2]
            else:
                if target in self.bot.groups:
                    if 'title' in self.bot.groups[target] and self.bot.groups[target].title:
                        name = self.bot.groups[target].title

                    if 'username' in self.bot.groups[target]:
                        username = '******' + self.bot.groups[target]['username']

                    if 'description' in self.bot.groups[target]:
                        description = self.bot.groups[target]['description']

                    if 'member_count' in self.bot.groups[target]:
                        members = self.bot.groups[target]['member_count']

                    if 'invite_link' in self.bot.groups[target]:
                        invite_link = self.bot.groups[target]['invite_link']

                    messages = self.bot.groups[target].messages

                else:
                    if info:
                        self.bot.groups[target] = {
                            'title': info['title'],
                            'messages': 0
                        }

                if info:
                    if len(info['username']) > 0:
                        username = '******' + info['username']
                        self.bot.groups[target]['username'] = info['username']

                if info_full:
                    description = info_full['description']
                    members = info_full['member_count']
                    invite_link = info_full['invite_link']
                    self.bot.groups[target]['description'] = description
                    self.bot.groups[target]['member_count'] = members
                    self.bot.groups[target]['invite_link'] = invite_link

                set_data('groups/%s/%s' %
                         (self.bot.name, target), self.bot.groups[target])

                if target in self.bot.tags:
                    for tag in self.bot.tags[target]:
                        tags += tag + ', '
                    tags = tags[:-2]

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

        if int(gid) < 0 and not get_input(m):
            if gid in self.bot.groups:
                if 'title' in self.bot.groups[gid] and self.bot.groups[gid].title:
                    gname = self.bot.groups[gid].title

                if 'username' in self.bot.groups[gid]:
                    gusername = '******' + self.bot.groups[gid]['username']

                if 'description' in self.bot.groups[gid]:
                    gdescription = self.bot.groups[gid]['description']

                if 'member_count' in self.bot.groups[gid]:
                    gmembers = self.bot.groups[gid]['member_count']

                if 'invite_link' in self.bot.groups[gid]:
                    ginvite_link = self.bot.groups[gid]['invite_link']

                gmessages = self.bot.groups[gid].messages

                if gid.startswith('-100'):
                    info = self.bot.bindings.server_request(
                        'getSupergroup',  {'supergroup_id': int(gid[4:])})
                    info_full = self.bot.bindings.server_request(
                        'getSupergroupFullInfo',  {'supergroup_id': int(gid[4:])})

                    if info:
                        if len(info['username']) > 0:
                            gusername = '******' + info['username']

                        self.bot.groups[gid]['username'] = info['username']

                    if info_full:
                        gdescription = info_full['description']
                        gmembers = info_full['member_count']
                        ginvite_link = info_full['invite_link']
                        self.bot.groups[gid]['description'] = gdescription
                        self.bot.groups[gid]['member_count'] = gmembers
                        self.bot.groups[gid]['invite_link'] = ginvite_link

            if gid in self.bot.tags:
                for tag in self.bot.tags[gid]:
                    gtags += tag + ', '
                gtags = gtags[:-2]

        if len(username) > 0:
            name += '\n\t     ' + username

        if (target and int(target) > 0):
            text = self.bot.trans.plugins.info.strings.user_info % (
                name, target, messages)
        elif (target and int(target) < 0):
            text += self.bot.trans.plugins.info.strings.group_info % (
                name, target, messages)

        if invite_link and len(invite_link) > 0:
            text += '\n🔗 {}'.format(invite_link)

        if len(tags) > 0:
            text += '\n🏷 {}'.format(tags)

        if len(description) > 0:
            text += '\n\n{}'.format(description)

        if int(gid) < 0 and not get_input(m):
            text += '\n\n'
            if len(gusername) > 0:
                gname += '\n\t     ' + gusername
            text += self.bot.trans.plugins.info.strings.group_info % (
                gname, gid, gmessages)

            if ginvite_link and len(ginvite_link) > 0:
                text += '\n🔗 {}'.format(ginvite_link)

            if len(gtags) > 0:
                text += '\n🏷 {}'.format(gtags)

            if len(gdescription) > 0:
                text += '\n\n{}'.format(gdescription)

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Beispiel #40
0
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.pins:
                if self.pins[pin].creator == m.sender.id:
                    pins.append(pin)

            if len(pins) > 0:
                text = self.bot.trans.plugins.pins.strings.pins % len(pins)
                for pin in pins:
                    text += '\n • %s' % pin

            else:
                text = self.bot.trans.plugins.pins.strings.no_pins

            # If the message is too long send an error message instead #
            if len(text) < 4096:
                return self.bot.send_message(m, text, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.unknown,
                                             extra={'format': 'HTML'})

        # Add a pin #
        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'})

            input = input.lower()
            input = sub(r'[^\w\ ]', '',
                        input)  # Removes every special character.
            input = " ".join(
                input.split())  # Removes any duplicated whitespace.
            #input = input.split(' ', 1)[0]
            #input = sub(r'[^\w]','',input)

            if not m.reply:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.needs_reply,
                                             extra={'format': 'HTML'})

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

            if input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.already_pinned % input,
                    extra={'format': 'HTML'})

            if len(input) < 4:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.too_short,
                    extra={'format': 'HTML'})

            if input == self.bot.info.first_name.lower():
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.illegal_pinname,
                    extra={'format': 'HTML'})

            self.pins[input] = {
                'content':
                m.reply.content.replace('<', '&lt;').replace('>', '&gt;'),
                'creator':
                m.sender.id,
                'type':
                m.reply.type
            }

            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.pinned % input,
                extra={'format': 'HTML'})

        # Remove a pin #
        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'})

            input = input.lower()
            input = sub(r'[^\w\ ]', '', input)
            input = " ".join(input.split())
            #input = input.split(' ', 1)[0]

            print(input)

            if not input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.not_found % input,
                    extra={'format': 'HTML'})

            if not m.sender.id == self.pins[input]['creator']:
                if not is_mod(self.bot, m.sender.id, m.conversation.id):
                    return self.bot.send_message(
                        m,
                        self.bot.trans.plugins.pins.strings.not_creator %
                        input,
                        extra={'format': 'HTML'})
            try:
                del (self.pins[input])
            except KeyErrorException:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.unknown,
                                             extra={'format': 'HTML'})

            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.unpinned % input,
                extra={'format': 'HTML'})

        # Check what pin was triggered #
        else:
            # Finds the first 3 pins of the message and sends them. #
            #pins = findall(r"(\w+)", m.content.lower())
            if not randint(0, 4):
                replymessage = False
                pins = m.content.lower()
                #count = 3

                # Checks if the message contains a saved pin
                for pin in self.pins:
                    if pins.find(pin) > -1:
                        pinlength = len(pin)
                        textlength = len(pins)
                        foundpin = pins.find(pin)

                        # Found at first position of sent text and checks if it has a non-alphanumerical char next to the matching word
                        if foundpin == 0:
                            if textlength == pinlength:
                                replymessage = True
                            elif textlength > pinlength and match(
                                    '\W', pins[foundpin + pinlength]):
                                replymessage = True

                        # Ensures that the keyword is between spaces.
                        elif foundpin > 0 and match('\W', pins[foundpin - 1]):
                            if foundpin + pinlength == textlength or match(
                                    '\W',
                                    pins[foundpin +
                                         pinlength]):  # Last or middle word
                                replymessage = True

                        # You can reply with a pin and the message will reply too. #
                        if m.reply:
                            reply = m.reply.id
                        else:
                            reply = m.id

                        if replymessage:
                            self.bot.send_message(m,
                                                  self.pins[pin]['content'],
                                                  self.pins[pin]['type'],
                                                  extra={'format': 'HTML'
                                                         })  #, reply = reply)
Beispiel #41
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})
Beispiel #42
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'})