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 #2
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 #3
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())
    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'})
    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 #7
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 #8
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 #9
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 #10
0
    def run(self, m):
        if is_command(self, 1, m.content):
            username = get_input(m)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            text = text.rstrip('\n')

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

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

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

            data = send_request(url, params=params)

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

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

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

            text = text.rstrip('\n')

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

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

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

            data = send_request(url, params=params)

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

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

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

        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.bot.plugins = self.bot.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):
            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'})
            target = get_target(self.bot, m, input)
            message = all_but_first_word(input)
            r = deepcopy(m)
            r.conversation.id = target
            return self.bot.send_message(r, message)

        # Run shell commands
        elif is_command(self, 5, 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'})
            code = '$ %s\n\n%s' % (input, subprocess.getoutput(input))
            return self.bot.send_message(
                m,
                '<code class="language-shell">%s</code>' % code,
                extra={'format': 'HTML'})

        # Run python code
        elif is_command(self, 6, 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'})

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

            exec(input)

            code = None
            if cout.getvalue():
                code = '>>>%s\n\n%s' % (input, cout.getvalue())

            if cerr.getvalue():
                code = '>>>%s\n\n%s' % (input, cerr.getvalue())

            if code:
                return self.bot.send_message(
                    m,
                    '<code class="language-python">%s</code>' % code,
                    extra={'format': 'HTML'})

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

        # Change name
        elif is_command(self, 7, m.content):
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
            ok = self.bot.bindings.server_request('setName', {
                'first_name': input,
                'last_name': '☆'
            })

            if not ok:
                text = self.bot.trans.errors.failed

        # Change bio
        elif is_command(self, 8, m.content):
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
            ok = self.bot.bindings.server_request('setBio', {'bio': input})

            if not ok:
                text = self.bot.trans.errors.failed

        # Change photo
        elif is_command(self, 9, m.content):
            ok = False
            if m.reply and m.reply.type == 'photo':
                photo = self.bot.bindings.get_file(m.reply.content)
                if photo:
                    ok = self.bot.bindings.server_request(
                        'setProfilePhoto',
                        {'photo': self.bot.bindings.get_input_file(photo)})
                else:
                    ok = self.bot.bindings.server_request(
                        'setProfilePhoto', {
                            'photo':
                            self.bot.bindings.get_input_file(m.reply.content)
                        })

            if not ok:
                text = self.bot.trans.errors.failed

        # Create webhook
        elif is_command(self, 10,
                        m.content) and self.bot.config.bindings == 'discord':
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})
            self.bot.bindings.create_webhook(m.conversation.id, input)
            text = 'Created webhook: "{}"'.format(input)

        if text:
            self.bot.send_message(m, text, extra={'format': 'HTML'})
    def run(self, m):
        # List #
        if is_command(self, 1, m.content):
            resends = []
            forwards = []
            text = ''
            for gid in self.bot.tags:
                for tag in self.bot.tags[gid]:
                    if 'resend:' in tag:
                        resends.append('{}:{}'.format(gid, tag.split(':')[1]))

                    if 'fwd:' in tag:
                        resends.append('{}:{}'.format(gid, tag.split(':')[1]))

            if len(resends) > 0:
                text += '<b>Resends:</b>'
                text += self.generate_text(resends)

            if len(forwards) > 0:
                text += '\n<b>Forwards:</b>'
                text += self.generate_text(forwards)

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

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

            origin = first_word(input)
            destination = first_word(input, 2)

            if not origin or not destination:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})

        # Remove all resends #
        elif is_command(self, 3, m.content):
            input = get_input(m)
            if not input:
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})

            origin = first_word(input)

            if not is_int(origin):
                return self.bot.send_message(m,
                                             generate_command_help(
                                                 self, m.content),
                                             extra={'format': 'HTML'})

            del_tag(self.bot, origin, 'resend:?')
            del_tag(self.bot, origin, 'fwd:?')
            return self.bot.send_message(m, '✅', extra={'format': 'HTML'})
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m,
                                         generate_command_help(
                                             self, m.content),
                                         extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

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

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

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

        requestUrl = url + "d.js"

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

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

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

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

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

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

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

        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):
            summoner_name = None

            if not input:
                tags = has_tag(self.bot,
                               m.sender.id,
                               'lol:?',
                               return_match=True)
                if tags and len(tags) > 0:
                    summoner_info = tags[0].split(':')[1]
                    if ('/' in summoner_info):
                        self.region = self.regions[summoner_info.split('/')[0]]
                        summoner_name = summoner_info.split('/')[1]

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

            else:
                if first_word(input).lower() in self.regions:
                    self.region = self.regions[first_word(input).lower()]
                    summoner_name = all_but_first_word(input)
                else:
                    self.region = self.regions['euw']
                    summoner_name = input

            summoner = self.summoner_by_name(summoner_name)
            if not summoner or 'status' in summoner and summoner['status'][
                    'status_code'] != 200:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.connection_error,
                    extra={'format': 'HTML'})

            account = self.account_by_puuid(summoner.puuid)
            masteries = self.champion_masteries(summoner.id)
            ranked = self.league_entries(summoner.id)

            if self.latest_version:
                icon_url = "http://ddragon.leagueoflegends.com/cdn/{}/img/profileicon/{}.png".format(
                    self.latest_version, summoner.profileIconId)

            else:
                icon_url = None

            opgg_region = self.region[
                'platform'] if self.region['platform'] != 'kr' else 'www'
            opgg = 'http://{}.op.gg/summoner/userName={}'.format(
                opgg_region, ''.join(summoner_name.split()))

            text = '{} (Lv: {})\n'.format(summoner.name,
                                          summoner.summonerLevel)

            if account and 'gameName' in account:
                text += '{}\n'.format(account.gameName + '#' + account.tagLine)

            if masteries:
                text += '\nMasteries:'
                for mastery in masteries[:5]:
                    text += '\n\t{}: Lv {} ({}k)'.format(
                        self.championIds[str(mastery['championId'])],
                        mastery['championLevel'],
                        int(mastery['championPoints'] / 1000))

            if ranked:
                for queue in ranked:
                    text += '\n\n{}:\n\tLeague: {} {} ({}LP)'.format(
                        self.ranked_queueType(queue['queueType']),
                        self.ranked_tier(queue['tier']), queue['rank'],
                        queue['leaguePoints'])
                    text += '\n\tWins/Losses: {} / {} ({}%)'.format(
                        queue['wins'], queue['losses'],
                        str(
                            int((float(queue['wins']) /
                                 (float(queue['wins']) +
                                  float(queue['losses']))) * 100)).replace(
                                      '.', '\''))

            # text += '\n\n<a href="{}">{}</a>'.format(opgg, 'OP.GG')

            if icon_url:
                return self.bot.send_message(m,
                                             icon_url,
                                             'photo',
                                             extra={
                                                 'caption': text,
                                                 'format': 'HTML',
                                                 'preview': True
                                             })
            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': True
                                         })
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.bot.pins:
                if 'creator' in self.bot.pins[pin] and self.bot.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,
                                             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 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.bot.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.already_pinned % input,
                    extra={'format': 'HTML'})

            if m.reply.type == 'text' and m.reply.content.startswith(
                    self.bot.config.prefix):
                pin_type = 'command'
            else:
                pin_type = m.reply.type

            self.bot.pins[input] = {
                'content':
                m.reply.content.replace('<', '&lt;').replace('>', '&gt;'),
                'creator':
                m.sender.id,
                'type':
                pin_type
            }
            set_data('pins/%s/%s' % (self.bot.name, input),
                     self.bot.pins[input])
            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,
                                             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 input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not input in self.bot.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.bot.pins[input].creator:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.not_creator % input,
                    extra={'format': 'HTML'})

            delete_data('pins/%s/%s' % (self.bot.name, input))
            del self.bot.pins[input]
            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.bot.pins:
                    # You can reply with a pin and the message will reply too. #
                    if m.reply:
                        reply = m.reply.id
                    else:
                        reply = m.id

                    if 'content' in self.bot.pins[
                            pin] and 'type' in self.bot.pins[pin]:
                        if (self.bot.pins[pin].type == 'command'):
                            m.content = self.bot.pins[pin].content
                            self.bot.inbox.put(m)
                            return self.bot.on_message_receive(m)

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

                        count -= 1

                if count == 0:
                    return