Пример #1
0
    def run(self, m):
        text = None
        if is_command(self, 1, m.content) or is_command(self, 3, m.content):
            try:
                tag = subprocess.check_output(
                    ['git', 'rev-parse', '--short',
                     'HEAD']).decode('ascii').rstrip('\n')
            except:
                tag = 'latest'

            greeting = self.bot.trans.plugins.about.strings.greeting % self.bot.info.first_name
            version = self.bot.trans.plugins.about.strings.version % tag
            license = self.bot.trans.plugins.about.strings.license
            help = self.bot.trans.plugins.about.strings.help % self.bot.config.prefix
            about = self.bot.trans.plugins.about.strings.about % self.bot.config.prefix
            notice = self.bot.trans.plugins.about.strings.notice
            donations = self.bot.trans.plugins.about.strings.donations % self.bot.config.prefix
            stats = self.bot.trans.plugins.about.strings.stats % (len(
                self.bot.users), len(self.bot.groups))

            if is_command(self, 1, m.content):
                text = '%s\n\n%s\n\n%s\n%s\n\n%s\n%s\n\n%s\n\n%s' % (
                    greeting, notice, help, about, version, donations, license,
                    stats)

            else:
                text = '%s\n\n%s\n\n%s\n%s\n\n%s' % (greeting, notice, help,
                                                     about, donations)

        elif is_command(self, 2, m.content):
            donations_explanation = self.bot.trans.plugins.about.strings.donations_explanation
            supporters_title = self.bot.trans.plugins.about.strings.supporters
            supporters = ''
            for uid in self.bot.users:
                if has_tag(self.bot, uid, 'supporter') or has_tag(
                        self.bot, uid, 'supporter:?'):
                    supporters += '\n • %s' % self.bot.users[uid].first_name
                    if 'last_name' in self.bot.users[uid] and self.bot.users[
                            uid].last_name:
                        supporters += ' %s' % self.bot.users[uid].last_name
                    if 'username' in self.bot.users[uid] and self.bot.users[
                            uid].username:
                        supporters += ' @%s' % self.bot.users[uid].username

                    for tag in has_tag(self.bot, uid, 'supporter:?', True):
                        if ':' in tag:
                            supporters += ' | %s' % tag.split(':')[1]

            if len(supporters) > 0:
                text = '%s\n\n%s%s' % (donations_explanation, supporters_title,
                                       supporters)
            else:
                text = donations_explanation

        self.bot.send_message(m,
                              text,
                              extra={
                                  'format': 'HTML',
                                  'preview': False
                              })
Пример #2
0
    def run(self, m):
        if is_command(self, 1, m.content):
            url = 'http://thecatapi.com/api/images/get'
            params = {
                'format': 'src',
                'api_key': self.bot.config.api_keys.cat_api
            }

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

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

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

            data = send_request(url)
            if data:
                self.bot.send_message(m, data.message, 'photo')
            else:
                return self.bot.send_message(
                    m, self.bot.trans.errors.connection_error)
Пример #3
0
    def run(self, m):
        if has_tag(self.bot, m.conversation.id, 'noanimals'):
            return

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

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

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

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

            data = send_request(url, bot=self.bot)
            if data:
                return self.bot.send_message(m, data.message, 'photo')
            else:
                return self.bot.send_message(m, self.bot.trans.errors.connection_error)
Пример #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'})

        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'})
Пример #5
0
    def run(self, m):
        if has_tag(self.bot, m.conversation.id, 'nonsfw'):
            return self.bot.send_message(
                m,
                self.bot.trans.plugins.config.strings.disabled,
                extra={'format': 'HTML'})

        nsfw = '-1001230470587'
        hentai = '-1001495126561'
        p**n = '-1001409180171'

        if is_command(self, 2, m.content):
            cid = hentai
        elif is_command(self, 3, m.content):
            cid = p**n
        else:
            cid = nsfw

        if self.bot.info.is_bot:
            info = self.bot.conversation_info(cid)

            if info:
                msg = None
                last = info['last_message']['id']
                start = 1
                retries = 100

                while not msg:
                    rid = randint(start, last)
                    while rid in self.invalid_ids:
                        rid = randint(start, last)
                    msg = self.bot.get_message(cid, rid)
                    if not msg and not rid in self.invalid_ids:
                        retries -= 1
                        self.invalid_ids.append(rid)

                    if retries <= 0:
                        msg = self.bot.get_message(cid, last)
                        return self.bot.forward_message(msg, m.conversation.id)

                return self.bot.forward_message(msg, m.conversation.id)

        else:
            history = self.bot.bindings.server_request(
                'getChatHistory', {
                    'chat_id': int(cid),
                    'from_message_id': 0,
                    'offset': 0,
                    'limit': 100
                })

            if history:
                msg = None
                while not msg:
                    index = randint(0, len(history['messages']) - 1)
                    msg = self.bot.get_message(
                        cid, history['messages'][index]['id'])

                return self.bot.forward_message(msg, m.conversation.id)
Пример #6
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'})
Пример #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,
                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
                                  })
Пример #8
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m,
                                         generate_command_help(
                                             self, m.content),
                                         extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

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

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

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

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

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

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

            self.bot.send_message(m,
                                  text,
                                  extra={
                                      'format': 'HTML',
                                      'preview': False
                                  })
Пример #9
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'})
Пример #10
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
                                  })
Пример #11
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'})
Пример #12
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'})
Пример #13
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
Пример #14
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})
Пример #15
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)
    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'})
Пример #17
0
    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'})
Пример #18
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'})
Пример #19
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
                    })
Пример #20
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'})

        if has_tag(self.bot, m.conversation.id, 'nopole'):
            return

        gid = str(m.conversation.id)
        uid = m.sender.id
        date = datetime.now().replace(microsecond=0).isoformat().split('T')[0]

        # Pole ranking
        if is_command(self, 1, m.content):
            if gid in self.bot.poles:
                ranking = DictObject()
                for day in self.bot.poles[gid]:
                    if 'pole' in self.bot.poles[gid][day]:
                        try:
                            ranking[str(self.bot.poles[gid][day].pole)].p += 1
                        except:
                            ranking[str(self.bot.poles[gid][day].pole)] = { 'p': 1, 's': 0, 'f': 0 }

                    if 'subpole' in self.bot.poles[gid][day]:
                        try:
                            ranking[str(self.bot.poles[gid][day].subpole)].s += 1
                        except:
                            ranking[str(self.bot.poles[gid][day].subpole)] = { 'p': 0, 's': 1, 'f': 0 }

                    if 'fail' in self.bot.poles[gid][day]:
                        try:
                            ranking[str(self.bot.poles[gid][day].fail)].f += 1
                        except:
                            ranking[str(self.bot.poles[gid][day].fail)] = { 'p': 0, 's': 0, 'f': 1 }

                text = self.bot.trans.plugins.pole.strings.ranking
                for uid, values in self.order_by_points(ranking):
                    points = str((values.p * 3) + (values.s * 1) + (values.f * 0.5)).rstrip('0').rstrip('.')
                    text += '\n ' + self.bot.trans.plugins.pole.strings.ranking_points % (self.bot.users[uid].first_name, points)

                poles = '\n\n' + self.bot.trans.plugins.pole.strings.poles
                poles_empty = True
                for uid, values in self.order_by_poles(ranking):
                    if values.p:
                        poles_empty = False
                        poles += '\n ' + self.bot.trans.plugins.pole.strings.ranking_poles % (self.bot.users[uid].first_name, values.p)
                if not poles_empty:
                    text += poles

                subpoles = '\n\n' + self.bot.trans.plugins.pole.strings.subpoles
                subpoles_empty = True
                for uid, values in self.order_by_subpoles(ranking):
                    if values.s:
                        subpoles_empty = False
                        subpoles += '\n ' + self.bot.trans.plugins.pole.strings.ranking_subpoles % (self.bot.users[uid].first_name, values.s)
                if not subpoles_empty:
                    text += subpoles

                fails = '\n\n' + self.bot.trans.plugins.pole.strings.fails
                fails_empty = True
                for uid, values in self.order_by_fails(ranking):
                    if values.f:
                        fails_empty = False
                        fails += '\n ' + self.bot.trans.plugins.pole.strings.ranking_fails % (self.bot.users[uid].first_name, values.f)
                if not fails_empty:
                    text += fails

        # Pole
        elif is_command(self, 2, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({
                    date: {
                        'pole': uid
                    }
                })

            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].pole = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date), self.bot.poles[gid][date])
            uid = str(uid)
            user = self.bot.users[uid].first_name
            if 'username' in self.bot.users[uid] and self.bot.users[uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_pole % user

        # Subole
        elif is_command(self, 3, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({
                    date: {
                        'subpole': uid
                    }
                })

            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][date]:
                    uid = str(uid)
                    text = self.bot.trans.plugins.pole.strings.too_soon % self.bot.users[uid].first_name
                    return self.bot.send_message(m, text, extra={'format': 'HTML'})
                elif not 'subpole' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].subpole = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date), self.bot.poles[gid][date])
            uid = str(uid)
            user = self.bot.users[uid].first_name
            if 'username' in self.bot.users[uid] and self.bot.users[uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_subpole % user

        # Fail
        elif is_command(self, 4, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({
                    date: {
                        'fail': uid
                    }
                })
            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()


                if not 'pole' in self.bot.poles[gid][date] or not 'subpole' in self.bot.poles[gid][date]:
                    uid = str(uid)
                    text = self.bot.trans.plugins.pole.strings.too_soon % self.bot.users[uid].first_name
                    return self.bot.send_message(m, text, extra={'format': 'HTML'})
                elif not 'fail' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].fail = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date), self.bot.poles[gid][date])
            uid = str(uid)
            user = self.bot.users[uid].first_name
            if 'username' in self.bot.users[uid] and self.bot.users[uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_fail % user

        if text:
            self.bot.send_message(m, text, extra={'format': 'HTML'})
Пример #21
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={"format": "HTML"})

        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"})
Пример #22
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
Пример #23
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'})
Пример #24
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'})
Пример #25
0
    def run(self, m):
        input = get_input(m)
        uid = str(m.sender.id)
        gid = str(m.conversation.id)
        ok = False

        if m.conversation.id > 0:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.group_only,
                                         extra={'format': 'HTML'})

        # List all administration commands. #
        if is_command(self, 1, m.content):
            text = self.bot.trans.plugins.admin.strings.commands
            for command in self.commands:
                # Adds the command and parameters#
                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>'

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

        # Title #
        if is_command(self, 2, m.content):
            if self.check_permissions(m):
                ok = self.bot.bindings.rename_conversation(
                    m.conversation.id, input)

        # Description #
        elif is_command(self, 3, m.content):
            if self.check_permissions(m):
                ok = self.bot.bindings.change_conversation_description(
                    m.conversation.id, input)

        # Photo #
        elif is_command(self, 4, m.content):
            if self.check_permissions(m):
                if m.reply and m.reply.type == 'photo':
                    photo = self.bot.bindings.get_file(m.reply.content)
                    if photo:
                        ok = self.bot.bindings.change_conversation_photo(
                            m.conversation.id, photo)
                    else:
                        ok = self.bot.bindings.change_conversation_photo(
                            m.conversation.id, m.reply.content)

        # Promote #
        elif is_command(self, 5, m.content):
            if self.check_permissions(m):
                target = get_target(self.bot, m, get_input(m))
                ok = self.bot.bindings.promote_conversation_member(
                    m.conversation.id, target)

        # Kick #
        elif is_command(self, 6, m.content):
            if self.check_permissions(m):
                target = get_target(self.bot, m, get_input(m))
                ok = self.bot.bindings.kick_conversation_member(
                    m.conversation.id, target)

        # Unban #
        elif is_command(self, 7, m.content):
            if self.check_permissions(m):
                target = get_target(self.bot, m, get_input(m))
                ok = self.bot.bindings.unban_conversation_member(
                    m.conversation.id, target)

        # Delete message #
        elif is_command(self, 8, m.content):
            if self.check_permissions(m):
                self.bot.bindings.delete_message(m.conversation.id, m.id)
                if m.reply:
                    ok = self.bot.bindings.delete_message(
                        m.conversation.id, m.reply.id)

        # Pin #
        elif is_command(self, 9, m.content):
            if self.check_permissions(m):
                if m.reply:
                    ok = self.bot.send_message(
                        m,
                        'pinChatMessage',
                        'api',
                        extra={'message_id': m.reply.id})

        # Unpin #
        elif is_command(self, 10, m.content):
            if self.check_permissions(m):
                if m.reply:
                    ok = self.bot.send_message(m, 'unpinChatMessage', 'api')

        # Custom title #
        elif is_command(self, 11, m.content):
            if self.check_permissions(m):
                if m.reply:
                    target = m.reply.sender.id
                else:
                    target = m.sender.id
                ok = self.bot.send_message(m,
                                           'setChatAdministratorCustomTitle',
                                           'api',
                                           extra={
                                               'user_id': target,
                                               'custom_title': input
                                           })

        # Leave #
        elif is_command(self, 12, m.content):
            if not is_admin(self.bot, m.sender.id) and not is_mod(
                    self.bot, m.sender.id, m.conversation.id):
                self.bot.send_message(
                    m,
                    self.bot.trans.errors.permission_required,
                    extra={'format': 'HTML'})
            else:
                ok = self.bot.bindings.kick_conversation_member(
                    m.conversation.id, self.bot.info.id)

        if not ok:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.failed,
                                         extra={'format': 'HTML'})
Пример #26
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'})
Пример #27
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'})
Пример #28
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

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

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

        lat, lon, locality, country = values

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

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

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

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

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

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

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

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

            return self.bot.send_message(m, message, extra={'format': 'HTML'})
Пример #29
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
                                         })
Пример #30
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'})
Пример #31
0
    def run(self, m):
        if str(m.sender.id).startswith('-100'):
            return

        if m.conversation.id > 0:
            return self.bot.send_message(m,
                                         self.bot.trans.errors.group_only,
                                         extra={'format': 'HTML'})

        if has_tag(self.bot, m.conversation.id, 'nopole'):
            return

        gid = str(m.conversation.id)
        uid = m.sender.id
        now = datetime.now().replace(microsecond=0)
        date = now.isoformat().split('T')[0]
        text = None

        # Pole ranking
        if is_command(self, 1, m.content):
            if time_in_range(time(1, 0, 0), time(2, 0, 0), now.time()):
                type = 1
            elif time_in_range(time(12, 0, 0), time(13, 0, 0), now.time()):
                type = 2
            else:
                type = 0

            if gid in self.bot.poles:
                ranking = DictObject()
                for day in self.bot.poles[gid]:
                    if type == 0:
                        if 'pole' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].pole)].p += 1
                            except:
                                ranking[str(self.bot.poles[gid][day].pole)] = {
                                    'p': 1,
                                    's': 0,
                                    'f': 0,
                                    'i': 0
                                }

                        if 'subpole' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].subpole)].s += 1
                            except:
                                ranking[str(
                                    self.bot.poles[gid][day].subpole)] = {
                                        'p': 0,
                                        's': 1,
                                        'f': 0,
                                        'i': 0
                                    }

                        if 'fail' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].fail)].f += 1
                            except:
                                ranking[str(self.bot.poles[gid][day].fail)] = {
                                    'p': 0,
                                    's': 0,
                                    'f': 1,
                                    'i': 0
                                }

                        if 'iron' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].iron)].i += 1
                            except:
                                ranking[str(self.bot.poles[gid][day].iron)] = {
                                    'p': 0,
                                    's': 0,
                                    'f': 0,
                                    'i': 1
                                }

                    if type == 1:
                        if 'canaria' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].canaria)].c += 1
                            except:
                                ranking[str(
                                    self.bot.poles[gid][day].canaria)] = {
                                        'c': 1
                                    }

                    if type == 2:
                        if 'andaluza' in self.bot.poles[gid][day]:
                            try:
                                ranking[str(
                                    self.bot.poles[gid][day].andaluza)].a += 1
                            except:
                                ranking[str(
                                    self.bot.poles[gid][day].andaluza)] = {
                                        'a': 1
                                    }
                text = ''
                if type == 0:
                    text = self.bot.trans.plugins.pole.strings.ranking
                    for uid, values in self.order_by_points(ranking, type):
                        points = str((values.p * 3) + (values.s * 1) +
                                     (values.f * 0.5) +
                                     (values.i * 0.1)).rstrip('0').rstrip('.')
                        text += '\n ' + self.bot.trans.plugins.pole.strings.ranking_points % (
                            self.bot.users[uid].first_name, points)

                    poles = '\n\n' + self.bot.trans.plugins.pole.strings.poles
                    poles_empty = True
                    for uid, values in self.order_by_poles(ranking):
                        if values.p:
                            poles_empty = False
                            poles += '\n ' + self.bot.trans.plugins.pole.strings.ranking_poles % (
                                self.bot.users[uid].first_name, values.p)
                    if not poles_empty:
                        text += poles

                    subpoles = '\n\n' + self.bot.trans.plugins.pole.strings.subpoles
                    subpoles_empty = True
                    for uid, values in self.order_by_subpoles(ranking):
                        if values.s:
                            subpoles_empty = False
                            subpoles += '\n ' + self.bot.trans.plugins.pole.strings.ranking_subpoles % (
                                self.bot.users[uid].first_name, values.s)
                    if not subpoles_empty:
                        text += subpoles

                    fails = '\n\n' + self.bot.trans.plugins.pole.strings.fails
                    fails_empty = True
                    for uid, values in self.order_by_fails(ranking):
                        if values.f:
                            fails_empty = False
                            fails += '\n ' + self.bot.trans.plugins.pole.strings.ranking_fails % (
                                self.bot.users[uid].first_name, values.f)
                    if not fails_empty:
                        text += fails

                    irons = '\n\n' + self.bot.trans.plugins.pole.strings.irons
                    irons_empty = True
                    for uid, values in self.order_by_irons(ranking):
                        if values.i:
                            irons_empty = False
                            irons += '\n ' + self.bot.trans.plugins.pole.strings.ranking_irons % (
                                self.bot.users[uid].first_name, values.i)
                    if not irons_empty:
                        text += irons

                elif type == 1:
                    poles_canarias = '\n\n' + self.bot.trans.plugins.pole.strings.poles_canarias
                    poles_canarias_empty = True
                    for uid, values in self.order_by_poles_canarias(ranking):
                        if values.c:
                            poles_canarias_empty = False
                            poles_canarias += '\n ' + \
                                self.bot.trans.plugins.pole.strings.ranking_poles % (
                                    self.bot.users[uid].first_name, values.c)
                    if not poles_canarias_empty:
                        text += poles_canarias

                elif type == 2:
                    poles_andaluzas = '\n\n' + self.bot.trans.plugins.pole.strings.poles_andaluzas
                    poles_andaluzas_empty = True
                    for uid, values in self.order_by_poles_andaluzas(ranking):
                        if values.a:
                            poles_andaluzas_empty = False
                            poles_andaluzas += '\n ' + \
                                self.bot.trans.plugins.pole.strings.ranking_poles % (
                                    self.bot.users[uid].first_name, values.a)
                    if not poles_andaluzas_empty:
                        text += poles_andaluzas

        # Pole
        elif is_command(self, 2, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'pole': uid}})

            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].pole = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_pole % user

        # Subole
        elif is_command(self, 3, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'subpole': uid}})

            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][date]:
                    uid = str(uid)
                    text = self.bot.trans.plugins.pole.strings.too_soon % self.bot.users[
                        uid].first_name
                    return self.bot.send_message(m,
                                                 text,
                                                 extra={'format': 'HTML'})
                elif not 'subpole' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].subpole = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_subpole % user

        # Fail
        elif is_command(self, 4, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'fail': uid}})
            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][
                        date] or not 'subpole' in self.bot.poles[gid][date]:
                    uid = str(uid)
                    text = self.bot.trans.plugins.pole.strings.too_soon % self.bot.users[
                        uid].first_name
                    return self.bot.send_message(m,
                                                 text,
                                                 extra={'format': 'HTML'})
                elif not 'fail' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].fail = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_fail % user

        # Pole canaria
        elif is_command(self, 5, m.content):
            if self.has_pole(gid, uid, date, 1):
                return

            if not time_in_range(time(1, 0, 0), time(2, 0, 0), now.time()):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'canaria': uid}})
            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'canaria' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].canaria = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_pole_canaria % user

        # Pole andaluza
        elif is_command(self, 6, m.content):
            if self.has_pole(gid, uid, date, 1):
                return

            if not time_in_range(time(12, 0, 0), time(13, 0, 0), now.time()):
                uid = str(uid)
                text = self.bot.trans.plugins.pole.strings.too_soon_for_andaluza % self.bot.users[
                    uid].first_name
                return self.bot.send_message(m, text, extra={'format': 'HTML'})

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'andaluza': uid}})
            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'andaluza' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].andaluza = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_pole_andaluza % user

        # Hierro
        elif is_command(self, 7, m.content):
            if self.has_pole(gid, uid, date):
                return

            if not gid in self.bot.poles:
                self.bot.poles[gid] = DictObject({date: {'iron': uid}})
            else:
                if not date in self.bot.poles[gid]:
                    self.bot.poles[gid][date] = DictObject()

                if not 'pole' in self.bot.poles[gid][
                        date] or not 'subpole' in self.bot.poles[gid][
                            date] or not 'fail' in self.bot.poles[gid][date]:
                    uid = str(uid)
                    text = self.bot.trans.plugins.pole.strings.too_soon % self.bot.users[
                        uid].first_name
                    return self.bot.send_message(m,
                                                 text,
                                                 extra={'format': 'HTML'})
                elif not 'iron' in self.bot.poles[gid][date]:
                    self.bot.poles[gid][date].iron = uid
                else:
                    return
            set_data('poles/%s/%s/%s' % (self.bot.name, gid, date),
                     self.bot.poles[gid][date])
            uid = str(uid)
            user = ''
            if 'first_name' in self.bot.users[uid]:
                user += self.bot.users[uid]['first_name']
            if 'username' in self.bot.users[uid] and self.bot.users[
                    uid].username:
                user = '******' + self.bot.users[uid].username
            text = self.bot.trans.plugins.pole.strings.got_iron % user

        # Pole reset
        elif is_command(self, 8, m.content):
            if has_tag(self.bot, m.conversation.id, 'polereset'):
                if is_trusted(self.bot, m.sender.id, m):
                    delete_data('poles/%s/%s' % (self.bot.name, gid))
                    self.bot.poles.pop(gid, None)
                    text = self.bot.trans.plugins.pole.strings.polereset_done
                else:
                    text = self.bot.trans.errors.admin_required
            else:
                text = self.bot.trans.plugins.config.strings.disabled

        if text:
            self.bot.send_message(m, text, extra={'format': 'HTML'})
Пример #32
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'})
Пример #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 command.command == '^new_chat_member$':
                    text += '\n • ' + \
                        self.bot.trans.plugins.administration.strings.new_chat_member
                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>'

            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
            if len(self.bot.administration) > 0:
                for gid, attr in self.bot.administration.items():
                    if 'public' in self.bot.administration[
                            gid] and self.bot.administration[gid].public:
                        if 'link' in self.bot.administration[
                                gid] and self.bot.config.bindings != 'telegram-cli':
                            text += '\n • <a href="%s">%s</a>' % (
                                self.bot.administration[gid].link,
                                self.bot.groups[gid].title)
                        else:
                            text += '\n • %s' % self.bot.groups[gid].title

                        if self.bot.administration[gid].alias:
                            text += ' /<b>%s</b>/' % attr.alias

            else:
                text = self.bot.trans.plugins.administration.strings.no_groups

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

        # 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.bot.administration:
                if (input in self.bot.administration
                        or compile('^' + input.lower() + '$').search(
                            self.bot.administration[id].alias.lower())
                        or compile('^' + input.lower() + '$').search(
                            self.bot.groups[id].title.lower())):
                    gid_to_join = id
                    break

            if not gid_to_join in self.bot.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>' % self.bot.groups[gid_to_join].title
            if self.bot.administration[gid_to_join].motd:
                text += '\n<i>%s</i>' % self.bot.administration[
                    gid_to_join].motd

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

            # if self.bot.administration[gid_to_join].public:
            #     text += '\n\n%s' % self.bot.trans.plugins.administration.strings.public_group
            # else:
            #     text += '\n\n%s' % self.bot.trans.plugins.administration.strings.private_group

            if not self.bot.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.bot.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.bot.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>' % self.bot.groups[gid].title
            if self.bot.administration[gid].motd:
                text += '\n<i>%s</i>' % self.bot.administration[gid].motd

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

            if not self.bot.administration[gid].rules:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules

            # if self.bot.administration[gid].public:
            #     text += '\n\n%s' % self.bot.trans.plugins.administration.strings.public_group
            # else:
            #     text += '\n\n%s' % self.bot.trans.plugins.administration.strings.private_group

            if is_command(self, 4, m.content):
                if not self.bot.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.bot.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.bot.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.bot.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.bot.administration[gid].rules:
                    text += '\n %s. <i>%s</i>' % (i, rule)
                    i += 1

            if not self.bot.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 is_int(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_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:
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_to_add %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })
                if not gid in self.bot.administration:
                    self.bot.administration[gid] = {
                        'alias': None,
                        'description': None,
                        'link': None,
                        'rules': [],
                        'public': False
                    }
                    set_data('administration/%s/%s' % (self.bot.name, gid),
                             self.bot.administration[gid])
                set_step(self.bot, m.conversation.id, get_plugin_name(self), 1)
            else:
                if first_word(input) == 'add':
                    if not gid in self.bot.administration:
                        self.bot.administration[gid] = {
                            'alias': None,
                            'description': None,
                            'link': None,
                            'rules': [],
                            'public': False
                        }
                        set_data('administration/%s/%s' % (self.bot.name, gid),
                                 self.bot.administration[gid])
                        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.bot.administration:
                        del self.bot.administration[gid]
                        delete_data('administration/%s/%s' %
                                    (self.bot.name, gid))
                        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.bot.administration:
                        self.bot.administration[
                            gid].alias = all_but_first_word(input).lower()
                        set_data(
                            'administration/%s/%s/alias' %
                            (self.bot.name, gid),
                            self.bot.administration[gid].alias)
                        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) == 'motd':
                    if gid in self.bot.administration:
                        self.bot.administration[gid].motd = all_but_first_word(
                            input)
                        set_data(
                            'administration/%s/%s/motd' % (self.bot.name, gid),
                            self.bot.administration[gid].motd)
                        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.bot.administration:
                        self.bot.administration[gid].link = all_but_first_word(
                            input)
                        set_data(
                            'administration/%s/%s/link' % (self.bot.name, gid),
                            self.bot.administration[gid].link)
                        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.bot.administration:
                        self.bot.administration[
                            gid].rules = all_but_first_word(
                                all_but_first_word(input).split('\n')[0:])
                        set_data(
                            'administration/%s/%s/rules' %
                            (self.bot.name, gid),
                            self.bot.administration[gid].rules)
                        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.bot.administration:
                        try:
                            i = int(first_word(all_but_first_word(input))) - 1
                            if i > len(self.bot.administration[gid].rules):
                                i = len(self.bot.administration[gid].rules)
                            elif i < 1:
                                i = 0
                        except:
                            return self.bot.send_message(
                                m,
                                self.bot.trans.errors.unknown,
                                extra={'format': 'HTML'})
                        self.bot.administration[gid].rules.insert(
                            i, all_but_first_word(all_but_first_word(input)))
                        set_data(
                            'administration/%s/%s/rules' %
                            (self.bot.name, gid),
                            self.bot.administration[gid].rules)
                        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) == 'public':
                    if gid in self.bot.administration:
                        if self.bot.trans.plugins.administration.strings.yes.lower(
                        ) in all_but_first_word(input).lower():
                            self.bot.administration[gid].public = True
                        else:
                            self.bot.administration[gid].public = False
                        set_data(
                            'administration/%s/%s/public' %
                            (self.bot.name, gid),
                            self.bot.administration[gid].public)
                        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'})
Пример #34
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'})
Пример #35
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 command['command'] == '^new_chat_member$':
                    text += '\n • ' + self.bot.trans.plugins.administration.strings.new_chat_member
                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>'

            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
            i = 1
            for gid, attr in self.administration.items():
                text += '\n %s. %s (%s)' % (i, self.groups[gid]['title'],
                                            attr['alias'])
                i += 1
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # Send message to another group. #
        if is_command(self, 10, m.content):
            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'})

            id_backup = m.conversation.id
            group_number = int(findall(r"(\w+)", m.content)[1])
            msg_offset = len(str(group_number)) + 1
            text = input[msg_offset:]

            if text and is_int(group_number):
                m.conversation.id = 0

                for gid in self.administration:
                    if group_number == 1:
                        m.conversation.id = int(gid)
                    group_number -= 1

                if m.conversation.id != id_backup and m.conversation.id != 0:
                    text = self.bot.trans.plugins.administration.strings.message_received % m.conversation.title + text
                    return self.bot.send_message(m,
                                                 text,
                                                 extra={'format': 'HTML'})
                    #return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.sent, extra={'format': 'HTML'})
                elif m.conversation.id == id_backup:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.plugins.administration.strings.no_echo,
                        extra={'format': 'HTML'})
                else:
                    m.conversation.id = id_backup
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.send_error,
                        extra={'format': 'HTML'})
            else:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.
                    invalid_syntax,
                    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_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:
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_to_add %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })
                if not gid in self.administration:
                    self.administration[gid] = {
                        'alias': None,
                        'description': None,
                        'link': None,
                        'rules': []
                    }
                    self.administration.store_database()
                set_step(self.bot, m.conversation.id, get_plugin_name(self), 1)
            else:
                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) == 'motd':
                    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'})
Пример #36
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})
Пример #37
0
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m,
                                         generate_command_help(
                                             self, m.content),
                                         extra={'format': 'HTML'})
            # return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

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

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

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

        requestUrl = url + "d.js"

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

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

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

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

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

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

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