Ejemplo n.º 1
0
Archivo: base.py Proyecto: Ryonez/mee6
    def embed(self):
        e = MessageEmbed()
        e.color = self.color
        e.title = self.stream_title
        e.url = self.stream_url

        author = MessageEmbedAuthor()
        author.name = self.display_name
        author.url = self.stream_url
        author.icon_url = self.avatar
        e.author = author

        thumbnail = MessageEmbedThumbnail()
        thumbnail.url = self.avatar
        thumbnail.proxy_url = self.avatar
        thumbnail.width, thumbnail.height = 100, 100
        e.thumbnail = thumbnail

        image = MessageEmbedImage()
        image.url = self.stream_preview + '?rand={}'.format(randint(0, 999999))
        e.image = image

        footer = MessageEmbedFooter()
        footer.text = self.platform_name
        e.footer = footer

        if self.stream_game:
            game_field = MessageEmbedField()
            game_field.name = 'Played Game'
            game_field.value = self.stream_game
            game_field.inline = True
            e.fields.append(game_field)

        if self.stream_viewers_count or self.stream_viewers_count == 0:
            viewers_field = MessageEmbedField()
            viewers_field.name = 'Viewers'
            viewers_field.value = str(self.stream_viewers_count)
            viewers_field.inline = True
            e.fields.append(viewers_field)

        return e
Ejemplo n.º 2
0
    def info(self, event, user: User = None):
        if not user:
            user = event.author
        else:
            if not isinstance(user, DiscoUser):
                try:
                    user = self.state.guilds[event.guild.id].members[user].user
                except KeyError:
                    try:
                        user = self.state.users[user]
                    except KeyError:
                        try:
                            user = self.bot.client.api.users_get(user)
                        except APIException:
                            return event.msg.reply(
                                ':eyes: User not found').after(3).delete()

        self.client.api.channels_typing(event.channel.id)

        content = []
        content.append('**\u276F User Information**')
        content.append('Profile: <@{}>'.format(user.id))

        created_dt = to_datetime(user.id)
        content.append('Created: <t:{0}:R> (<t:{0}:f>)'.format(
            int(created_dt.replace(tzinfo=pytz.UTC).timestamp())))

        member = event.guild.get_member(user.id) if event.guild else None

        if user.public_flags:
            badges = ''
            user_badges = list(UserFlags(user.public_flags))
            for badge in user_badges:
                badges += '<{}> '.format(BADGE_EMOJI[badge])

            content.append('Badges: {}'.format(badges))

        if member:
            content.append('\n**\u276F Member Information**')

            if member.nick:
                content.append('Nickname: {}'.format(member.nick))

            content.append('Joined: <t:{0}:R> (<t:{0}:f>)'.format(
                int(member.joined_at.replace(tzinfo=pytz.UTC).timestamp())))

            content.append('Messages: {}'.format(
                int(
                    Message.select(fn.Count(
                        Message.id)).where((Message.author_id == user.id)
                                           & (Message.guild_id == event.guild.
                                              id)).tuples()[0][0])))

            if member.roles:
                content.append('Roles: {}'.format(', '.join(
                    ('<@&{}>'.format(r) for r in member.roles))))

        # Execute a bunch of queries
        newest_msg = Message.select(fn.MAX(Message.id)).where(
            (Message.author_id == user.id)
            & (Message.guild_id == event.guild.id)).tuples()[0][0]

        infractions = Infraction.select(Infraction.id).where(
            (Infraction.user_id == user.id)
            & (Infraction.guild_id == event.guild.id)).tuples()

        if newest_msg:
            content.append('\n **\u276F Activity**')
            content.append('Last Message: <t:{0}:R> (<t:{0}:f>)'.format(
                int((to_datetime(newest_msg).replace(
                    tzinfo=pytz.UTC)).timestamp())))
            # content.append('First Message: {} ({})'.format(
            #    humanize.naturaltime(datetime.utcnow() - to_datetime(oldest_msg)),
            #    to_datetime(oldest_msg).strftime("%b %d %Y %H:%M:%S"),
            # ))

        if len(infractions) > 0:
            content.append('\n**\u276F Infractions**')
            total = len(infractions)
            content.append('Total Infractions: **{:,}**'.format(total))

        embed = MessageEmbed()

        try:
            avatar = User.with_id(user.id).get_avatar_url()
        except APIException:
            avatar = user.get_avatar_url(
            )  # This fails if the user has never been seen by speedboat.

        embed.set_author(name='{} ({})'.format(
            str(user),
            user.id,
        ),
                         icon_url=avatar)

        embed.set_thumbnail(url=avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, avatar)
        event.msg.reply('', embed=embed)
Ejemplo n.º 3
0
    def on_tags_info(self, event, name):
        try:
            tag = Tag.select(Tag, User).join(
                User, on=(User.user_id == Tag.author_id).alias(
                    'author')).where((Tag.name == S(name))
                                     & (Tag.guild_id == event.guild.id)).get()
        except Tag.DoesNotExist:
            raise CommandFail('no tag exists by that name')

        content = tag.content
        source = self.source_re.search(content)
        if source:
            source = source.group(1).lower()
            url = self.remote_url.format(source)
            r = requests.get(url)
            r = self.import_parser.search(r.content)
            r = r.group(1).decode('utf8').strip('`\n') if r else ''
            data = {'here': '@here', 'everyone': '@everyone'}
            r = self.replace_variables(r, data)
            if not (r and content == r):
                source = None
                content = self.source_re.sub('', content)
                Tag.update(content=content).where((Tag.name == tag.name) & (
                    Tag.guild_id == tag.guild_id)).execute()

        embed = MessageEmbed()
        embed.title = tag.name
        embed.description = clamp(content, 2048)
        embed.add_field(name='Author', value=unicode(tag.author), inline=True)
        embed.add_field(name='Times Used',
                        value=str(tag.times_used),
                        inline=True)
        embed.add_field(
            name='Imported',
            inline=True,
            value='No' if not source else
            ('Yes: [{source}]'
             '(https://github.com/Xenthys/RawgoatTags/blob/master/tags/{source}.md)'
             ).format(source=source))
        embed.timestamp = tag.created_at.isoformat()
        event.msg.reply(embed=embed)
Ejemplo n.º 4
0
    def update_messages(self, only_current_player = False):
        player_list = self.print_player_list()
        for player in ([self.current_turn] if only_current_player else self.players):
            embed = MessageEmbed()
            embed.description = self.log_message
            embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/{}.png?v=1".format(self.pile.top_card.emoji_id))
            embed.set_author(name="Uno", icon_url="https://cdn.discordapp.com/emojis/{}.png?v=1".format(
                bot_config.uno_emojis['uno'].split(':')[1]))
            embed.set_footer(text=player.user,
                             icon_url=player.user.avatar_url)

            embed.add_field(name="Players", value=player_list)
            embed.add_field(name="Pile", value= "<:" + bot_config.uno_emojis['uno'] + ">" + str(self.pile.top_card) + "\n\n")
            if len(self.current_turn.queue) > 0:
                embed.add_field(name="Play?", value= ''.join(str(x) for x in self.current_turn.queue) + "\n\n")
            elif self.current_turn.choosingColor:
                embed.add_field(name="Choose Color", value="{}Red {}Yellow {}Green {}Blue\n\n".format("1⃣","2⃣","3⃣","4⃣"))
            rows = ceil(len(player.hand) / 12)
            emotes = [
                "<:blank:594342155565400114>",
                "\U000025c0",
                "1⃣",
                "2⃣",
                "3⃣",
                "4⃣",
                "5⃣",
                "6⃣",
                "\U000025b6",
            ]
            emojis = []

            if not player.turnOver:
                start = max(0, min(player.page * 6, len(player.hand) - 6))
                end = start + 5
                legalCards = player.getLegalCards()

                index = 0
                for card in player.hand:
                    if index < (start - 1):
                        emojis.append(emotes[0])
                    elif index < start:
                        emojis.append(emotes[1])
                    elif index <= end:
                        emojis.append(emotes[index-start+2])
                    elif index <= (end + 1):
                        emojis.append(emotes[8])
                    else:
                        emojis.append(emotes[0])
                    index += 1
            else:
                for card in player.hand:
                    emojis.append(emotes[0])

            embed.add_field(name=player.user.username + "'s Hand",
                            value=''.join(emojis[0:12]) + "\n" + self.print_hand_menu(player, 0))
            for x in range(ceil(len(player.hand) / 12)):
                if x == 0:
                    continue
                embed.add_field(name=''.join(emojis[(12 * x):(12 * (x + 1))]),
                                value=self.print_hand_menu(player, x))

            if player.hint != "":
                embed.add_field(name="Hint", value=player.hint)
            player.message.edit('', embed=embed)
Ejemplo n.º 5
0
    def on_resume(self, event):
        embed = MessageEmbed()
        embed.set_footer(text='Aetherya {}'.format('Production' if ENV ==
                                                   'prod' else 'Testing'))
        embed.timestamp = datetime.utcnow().isoformat()
        embed.color = 0xffb347
        embed.add_field(name='Gateway Server',
                        value=event.trace[0],
                        inline=False)
        embed.add_field(name='Session Server',
                        value=event.trace[1],
                        inline=False)
        embed.add_field(name='Replayed Events',
                        value=str(self.client.gw.replayed_events))

        self.client.api.channels_messages_create(AETHERYA_CONTROL_CHANNEL,
                                                 embed=embed)
Ejemplo n.º 6
0
def build_embed():
    return MessageEmbed()
Ejemplo n.º 7
0
    def msgstats(self, event, user):
        # Query for the basic aggregate message statistics
        message_stats = Message.select(
            fn.Count('*'),
            fn.Sum(fn.char_length(Message.content)),
            fn.Sum(fn.array_length(Message.emojis, 1)),
            fn.Sum(fn.array_length(Message.mentions, 1)),
            fn.Sum(fn.array_length(Message.attachments, 1)),
        ).where((Message.author_id == user.id)).tuples(). async ()

        reactions_given = Reaction.select(
            fn.Count('*'),
            Reaction.emoji_id,
            Reaction.emoji_name,
        ).join(Message, on=(Message.id == Reaction.message_id)).where(
            (Reaction.user_id == user.id)).group_by(
                Reaction.emoji_id, Reaction.emoji_name).order_by(
                    fn.Count('*').desc()).tuples(). async ()

        # Query for most used emoji
        emojis = Message.raw(
            '''
            SELECT gm.emoji_id, gm.name, count(*)
            FROM (
                SELECT unnest(emojis) as id
                FROM messages
                WHERE author_id=%s
            ) q
            JOIN guild_emojis gm ON gm.emoji_id=q.id
            GROUP BY 1, 2
            ORDER BY 3 DESC
            LIMIT 1
        ''', (user.id, )).tuples(). async ()

        deleted = Message.select(
            fn.Count('*')).where((Message.author_id == user.id)
                                 & (Message.deleted == 1)).tuples(). async ()

        wait_many(message_stats, reactions_given, emojis, deleted, timeout=10)

        # If we hit an exception executing the core query, throw an exception
        if message_stats.exception:
            message_stats.get()

        q = message_stats.value[0]
        embed = MessageEmbed()
        embed.fields.append(
            MessageEmbedField(name='Total Messages Sent',
                              value=q[0] or '0',
                              inline=True))
        embed.fields.append(
            MessageEmbedField(name='Total Characters Sent',
                              value=q[1] or '0',
                              inline=True))

        if deleted.value:
            embed.fields.append(
                MessageEmbedField(name='Total Deleted Messages',
                                  value=deleted.value[0][0],
                                  inline=True))
        embed.fields.append(
            MessageEmbedField(name='Total Custom Emojis',
                              value=q[2] or '0',
                              inline=True))
        embed.fields.append(
            MessageEmbedField(name='Total Mentions',
                              value=q[3] or '0',
                              inline=True))
        embed.fields.append(
            MessageEmbedField(name='Total Attachments',
                              value=q[4] or '0',
                              inline=True))

        if reactions_given.value:
            reactions_given = reactions_given.value

            embed.fields.append(
                MessageEmbedField(name='Total Reactions',
                                  value=sum(i[0] for i in reactions_given),
                                  inline=True))

            emoji = (reactions_given[0][2]
                     if not reactions_given[0][1] else '<:{}:{}>'.format(
                         reactions_given[0][2], reactions_given[0][1]))
            embed.fields.append(
                MessageEmbedField(name='Most Used Reaction',
                                  value=u'{} (used {} times)'.format(
                                      emoji,
                                      reactions_given[0][0],
                                  ),
                                  inline=True))

        if emojis.value:
            emojis = list(emojis.value)

            if emojis:
                embed.add_field(
                    name='Most Used Emoji',
                    value=u'<:{1}:{0}> (`{1}`, used {2} times)'.format(
                        *emojis[0]))

        embed.thumbnail = MessageEmbedThumbnail(url=user.avatar_url)
        embed.color = get_dominant_colors_user(user)
        event.msg.reply('', embed=embed)
Ejemplo n.º 8
0
    def get_embed(self, star, msg, config):
        # Create the 'header' (non-embed) text
        stars = ':star:'

        if len(star.stars) > 1:
            if len(star.stars) >= config.star_color_max:
                stars = ':star2:'
            stars = stars + ' {}'.format(len(star.stars))

        content = '{} <#{}> ({})'.format(
            stars,
            msg.channel_id,
            msg.id
        )

        # Generate embed section
        embed = MessageEmbed()
        embed.description = msg.content

        if msg.attachments:
            attach = list(msg.attachments.values())[0]
            if attach.url.lower().endswith(('png', 'jpeg', 'jpg', 'gif', 'webp')):
                embed.set_image(url=attach.url)

        if msg.embeds:
            if msg.embeds[0].image.url:
                embed.set_image(url=msg.embeds[0].image.url)
            elif msg.embeds[0].thumbnail.url:
                embed.set_image(url=msg.embeds[0].thumbnail.url)

        author = msg.guild.get_member(msg.author)
        if author:
            embed.set_author(
                name=author.name,
                icon_url=author.user.avatar_url
            )
        else:
            embed.set_author(
                name=msg.author.username,
                icon_url=msg.author.avatar_url)

        embed.timestamp = msg.timestamp.isoformat()
        embed.color = config.get_color(len(star.stars))

        return content, embed
Ejemplo n.º 9
0
 def on_red(self, event, character):
     try:
         dbref = db.reference('references/{}'.format(character.lower()))
         data = dbref.get()
         if data:
             embed = MessageEmbed()
             embed.set_author(name=data.get('owner', 'Unknown owner'),
                              url=data.get('ownerURL'),
                              icon_url=data.get('ownerAvatar'))
             embed.title = data.get('name', 'Unnamed')
             if data.get('description'):
                 embed.description = data['description']
             embed.color = data['color']
             if data.get('image'):
                 embed.set_image(url=data['image'])
             if data.get('thumbnail'):
                 embed.set_thumbnail(url=data['thumbnail'])
             event.msg.reply(embed=embed)
         else:
             event.msg.reply("Not found")
     except Exception as e:
         event.msg.reply(str(e))
Ejemplo n.º 10
0
    def help(self, event):
        embed = MessageEmbed()
        embed.title = "Bepis Boi's commands"
        embed.description = """Here are my commands:\n
***Shibe Commands***
**catch** | Find a random shibe, and add it to your inventory.
**inv** [#] | Look at your collection of shibes, always stored in stacks.
**show** <ID> | Show off your shibes, how cute they are.
**trade** <@> <ID> | Move your shibe into anther person's inventory.
**release** <ID> | Send your shibe off, into the wild.
**redeem** <ABC> | Redeem a code, and earn a shibe created from our great shibe admins.

***Shop Commands***
**bepis** [@] | Admire your bepis, or make fun of someone else's.
**sell** <ID> | Sell one of your shibes. Don't worry, they're in good hands.
**shop** [#] | Look at our large inventory of shibes, you know you want too.
**buy *shibe*** <ID> | Buy a shibe from our shop. It's worth every bepis.
**donate** <@> <#> | Feeling charitable? Donate bepis to someone else.
**flip** <#> | Flip a coin. You win, double your bet. Lose, lose your bet.
**ticket** <#> | Buy a certain amount of tickets, the more the merrier."""
        embed.set_footer(text="<>: required, []: optional, @: mention, "
                              "#: number, ID: shop ID / inventory ID, ABC: text")
        embed.color = 0x000080
        event.msg.reply(embed=embed)

        embed = MessageEmbed()
        embed.title = "Bepis Boi's commands"

        embed.description = """Here are my commands:\n
***Fun Commands***
*The following commands don't take any arguments, and show images / videos.*
**disrespect, tarnation, anthem, drincc, pat, politics, soviet, stop,
approved, extreme, no, blank, shibe, gethapp.**

***Extra Commands***
**invite** | Create an invite link, and share it with your friends to earn bepis.
**battle** <@> <ID> | Challenge someone to a duel, pick shibes, winner get's the loser's shibe.
**ping** | Pong.
**help** | You're looking at it.
**role** <ABC> | Add a sweet role to your account, so people know they're not alone.
**unrole** <ABC> | Remove a previously added role from your account, yw.
**source** | I had to prove the battle cmd wasn't rigged some how.

***Shibe Manager***
*The following commands require the Shibe Manager role*
**set *shibe*** <@> <#> <ABC> | Set a certain amount of a shibe to someone.
**set *bepis*** <@> <#> | Ste a certain amount of bepis to someone.
**reload** <catch/shrine> | When a new image is added, reload the bot's img cache.
**gencode** <ABC> | Create a code that can be redeemed, for whatever shibe is supplied.
"""
        embed.set_footer(text="<>: required, []: optional, @: mention, "
                              "#: number, ID: shop ID / inventory ID, ABC: text")
        embed.color = 0x000080
        event.msg.reply(embed=embed)
Ejemplo n.º 11
0
 def on_message_create(self, event):
     if event.author.id != self.config.bug_bot_user_id:
         return
     action = None
     # Bot Log - covers almost all events
     if event.channel.id == self.config.channels['bot-log']:
         # Try to find an event/action match for the message
         for act in self.exp:
             if act == 'denied':
                 continue
             match = self.exp[act].match(event.message.content)
             if match:
                 if act == 'approved':
                     link = match.group(1)
                     report_id = int(match.group(2))
                 else:
                     report_id = int(match.group(1))
                 action = act
                 break
     # Denied Bugs - only denied tickets
     elif event.channel.id == self.config.channels['denied-bugs']:
         try:
             report_id = int(self.exp['denied'].search(event.message.content).group(0))
         except AttributeError as e:
             # Couldn't extract the report ID from the message
             handle_exception(event, self.bot, e)
         else:
             action = 'denied'
     # Approval Queue - to track new tickets
     elif event.channel.id == self.config.channels['bug-approval-queue']:
         search = re.findall(r'(?<=Report\sID:\s\*{2})[0-9]+', event.message.content)
         if search:
             # Get the last ID in case the report includes the format above
             report_id = int(search[-1])
             self.reports.insert_one({'report_id': report_id, 'subs': {}, 'queue_msg': event.message.id})
     # Check if we need to send a DM update
     if action is not None:
         report = self.reports.find_one({'report_id': report_id})
         if report is not None:
             if len(report['subs']) > 0:
                 action_scope = Scope[action.upper()]
                 # Linkify the report ID
                 if action == 'approved':
                     report_str = f'report [**#{report_id}**]({link})'
                 elif action == 'denied':
                     report_str = f'report **#{report_id}**'
                 else:
                     link = self._build_jump_link(event.guild.id, self.config.channels['bug-approval-queue'],
                                                  report['queue_msg'])
                     report_str = f'report [**#{report_id}**]({link})'
                 em = MessageEmbed()
                 em.title = f'{SCOPE_DATA[action][0]} (#{report_id})'
                 desc = SCOPE_DATA[action][1].format(report=report_str)
                 em.description = desc[0].upper() + desc[1:]
                 em.color = '7506394'
                 uc = 0
                 for k, v in report['subs'].items():
                     if action_scope & Scope(v):
                         dm = self.bot.client.api.users_me_dms_create(int(k))
                         try:
                             dm.send_message(embed=em)
                         except APIException:
                             # Closed DMs
                             pass
                         else:
                             uc += 1
                 if uc > 0:
                     log_to_bot_log(self.bot,
                                    f':pager: `{action.upper()}` notification for **#{report_id}** sent to {uc} user(s)')
             if action in ['approved', 'denied']:
                 self.reports.delete_one({'report_id': report_id})
Ejemplo n.º 12
0
    def send_post(self, config, channel, data):
        if config.mode is FormatMode.PLAIN:
            channel.send_message('**{}**\n{}'.format(
                data['title'],
                'https://reddit.com{}'.format(data['permalink'])))
        else:
            embed = MessageEmbed()

            if 'nsfw' in data and data['nsfw']:
                if not config.nsfw:
                    return
                embed.color = 0xff6961
            else:
                embed.color = 0xaecfc8

            # Limit title to 256 characters nicely
            if len(data['title']) > 256:
                embed.title = data['title'][:253] + '...'
            else:
                embed.title = data['title']

            embed.url = u'https://reddit.com{}'.format(data['permalink'])
            embed.set_author(name=data['author'],
                             url=u'https://reddit.com/u/{}'.format(
                                 data['author']))

            image = None

            if data.get('media'):
                if 'oembed' in data['media']:
                    image = data['media']['oembed']['thumbnail_url']
            elif data.get('preview'):
                if 'images' in data['preview']:
                    image = data['preview']['images'][0]['source']['url']

            if 'selftext' in data and data['selftext']:
                # TODO better place for validation
                sz = min(64, max(config.text_length, 1900))
                embed.description = data['selftext'][:sz]
                if len(data['selftext']) > sz:
                    embed.description += u'...'
                if image:
                    embed.set_thumbnail(url=image)
            elif image:
                embed.set_image(url=image)

            if config.include_stats:
                embed.set_footer(text=emoji.emojize(
                    '{} upvotes | {} downvotes | {} comments'.format(
                        data['ups'], data['downs'], data['num_comments'])))

            channel.send_message('', embed=embed)
Ejemplo n.º 13
0
 def lookup_help_session(self, event, identifier):
     try:
         session_id = ObjectId(identifier)
     except InvalidId:
         event.msg.reply('That identifier is in the wrong format')
     else:
         session = self.helpme.find_one({'_id': ObjectId(identifier)})
         if session:
             em = MessageEmbed()
             em.title = f'DTesters HelpMe Session ({identifier})'
             em.description = 'Details for the session are below'
             em.color = '7506394'
             helpee_user = self.get_user(session['helpee_id'])
             mentor_user = self.get_user(session['mentor_id'])
             helpee_name = str(
                 helpee_user) if helpee_user else session['helpee_id']
             mentor_name = str(
                 mentor_user) if mentor_user else session['mentor_id']
             if mentor_name == 0:
                 mentor_name = '<UNASSIGNED>'
             active = 'Yes' if session['active'] else 'No'
             em.add_field(name='Helpee', value=helpee_name, inline=True)
             em.add_field(name='Mentor', value=mentor_name, inline=True)
             em.add_field(name='Active', value=active, inline=True)
             em.add_field(name='Query', value=f'```{session["query"]}```')
             history = []
             for entry in session['history']:
                 tstr = datetime.utcfromtimestamp(
                     entry[0]).strftime('%Y-%m-%d %H:%M:%S')
                 actor = 0
                 if entry[2] != 0:
                     actor = self.get_user(entry[2])
                     if actor:
                         actor = str(actor)
                     else:
                         actor = entry[2]
                 history_map = {
                     'received': 'HelpMe used',
                     'declined': '{} declined',
                     'assigned': 'Assigned to {}',
                     'waiting': 'Posted in mentor channel',
                     'complete': '{} completed the request',
                     'escalated': '{} escalated to the mods'
                 }
                 hmsg = history_map.get(entry[1],
                                        'Unknown event').format(actor)
                 history.append(f'{tstr} - {hmsg}')
             em.add_field(name='History', value='\n'.join(history))
             event.msg.reply(embed=em)
         else:
             event.msg.reply(
                 'Unable to find a session with that identifier')
Ejemplo n.º 14
0
 def build_help_embed(self, helpee_mention, query, identifier):
     em = MessageEmbed()
     em.title = 'HelpMe Request'
     desc = '\n'.join(self.config.helpme_embed_desc)
     em.description = desc.format(self.build_emoji('complete'),
                                  self.build_emoji('decline'),
                                  self.build_emoji('escalate'))
     em.color = '7506394'
     em.set_footer(text=f'ID: {identifier}')
     em.add_field(name='Helpee', value=helpee_mention)
     em.add_field(name='Query', value=f'```{query}```')
     return em
Ejemplo n.º 15
0
    def generate_message(self, twitch, new_state):
        embed = MessageEmbed()
        embed.title = u'{}'.format(new_state['status'])
        embed.url = 'https://twitch.tv/{}'.format(new_state['name'])
        embed.color = 0x6441A4
        embed.set_image(url=new_state['preview'])
        embed.add_field(name='Game', value=new_state['game'], inline=True)
        embed.add_field(name='Viewers', value=new_state['viewers'], inline=True)

        if twitch.notification_type == NotificationType.HERE:
            msg = u'@here {} is now live!'.format(new_state['name'])
        elif twitch.notification_type == NotificationType.EVERYONE:
            msg = u'@everyone {} is now live!'.format(new_state['name'])
        elif twitch.notification_type == NotificationType.ROLE:
            msg = u'<@&{}> {} is now live!'.format(twitch.notification_target, new_state['name'])
        else:
            msg = u'{} is now live!'.format(new_state['name'])

        return msg, embed
Ejemplo n.º 16
0
    def stars_stats(self, event, user=None):
        if user:
            try:
                given_stars = list(StarboardEntry.select(
                    fn.COUNT('*'),
                ).join(Message).where(
                    (~ (StarboardEntry.star_message_id >> None)) &
                    (StarboardEntry.stars.contains(user.id)) &
                    (Message.guild_id == event.guild.id)
                ).tuples())[0][0]

                recieved_stars_posts, recieved_stars_total = list(StarboardEntry.select(
                    fn.COUNT('*'),
                    fn.SUM(fn.array_length(StarboardEntry.stars, 1)),
                ).join(Message).where(
                    (~ (StarboardEntry.star_message_id >> None)) &
                    (Message.author_id == user.id) &
                    (Message.guild_id == event.guild.id)
                ).tuples())[0]
            except:
                return event.msg.reply(':warning: failed to crunch the numbers on that user')

            embed = MessageEmbed()
            embed.color = 0xffd700
            embed.title = user.username
            embed.set_thumbnail(url=user.avatar_url)
            embed.add_field(name='Total Stars Given', value=str(given_stars), inline=True)
            embed.add_field(name='Total Posts w/ Stars', value=str(recieved_stars_posts), inline=True)
            embed.add_field(name='Total Stars Recieved', value=str(recieved_stars_total), inline=True)
            # embed.add_field(name='Star Rank', value='#{}'.format(recieved_stars_rank), inline=True)
            return event.msg.reply('', embed=embed)

        total_starred_posts, total_stars = list(StarboardEntry.select(
            fn.COUNT('*'),
            fn.SUM(fn.array_length(StarboardEntry.stars, 1)),
        ).join(Message).where(
            (~ (StarboardEntry.star_message_id >> None)) &
            (StarboardEntry.blocked == 0) &
            (Message.guild_id == event.guild.id)
        ).tuples())[0]

        top_users = list(StarboardEntry.select(fn.SUM(fn.array_length(StarboardEntry.stars, 1)), User.user_id).join(
            Message,
        ).join(
            User,
            on=(Message.author_id == User.user_id),
        ).where(
            (~ (StarboardEntry.star_message_id >> None)) &
            (fn.array_length(StarboardEntry.stars, 1) > 0) &
            (StarboardEntry.blocked == 0) &
            (Message.guild_id == event.guild.id)
        ).group_by(User).order_by(fn.SUM(fn.array_length(StarboardEntry.stars, 1)).desc()).limit(5).tuples())

        embed = MessageEmbed()
        embed.color = 0xffd700
        embed.title = 'Star Stats'
        embed.add_field(name='Total Stars Given', value=total_stars, inline=True)
        embed.add_field(name='Total Starred Posts', value=total_starred_posts, inline=True)
        embed.add_field(name='Top Star Recievers', value='\n'.join(
            '{}. <@{}> ({})'.format(idx + 1, row[1], row[0]) for idx, row in enumerate(top_users)
        ))
        event.msg.reply('', embed=embed)
Ejemplo n.º 17
0
 def create_message(self):
     msgcontent = "**Word**: " + " ".join(
         self.word_to_emote(self.word_current))
     embed = MessageEmbed()
     embed.set_image(url=self.get_hangman_image(self.failed_attempts))
     return self.game_channel.send_message(msgcontent, embed=embed)
Ejemplo n.º 18
0
    def CHANNEL_UPDATE(event):
        sleep(1)

        # Retrieve the audit log object
        # (We just have to hope that it is the right object)
        data = event.guild.get_audit_log_entries(limit=1)[0]

        field_count = 2
        embed = MessageEmbed()
        embed.title = "Channel Updated"
        embed.color = Colour.YELLOW

        # Create static fields
        embed.add_field(name="Channel:", value=event.channel.name, inline=True)
        embed.add_field(name="User:"******"<@{}>".format(data.user_id),
                        inline=True)

        # Filter through all changes
        for change in data.changes:
            print(change.to_dict())
            # Ensure we don't exceed the field limit
            if field_count < 25:

                # Setting deleted
                if change.old_value and not change.new_value:
                    embed.add_field(
                        name="{}:".format(change.key),
                        value="Unset from: `{c.old_value}`".format(c=change),
                        inline=True)

                #Setting modified
                elif change.new_value and change.old_value:
                    embed.add_field(
                        name="{}:".format(change.key),
                        value="From: `{c.old_value}`\nTo: `{c.new_value}`".
                        format(c=change),
                        inline=True)

                # Setting created
                elif change.new_value and not change.old_value:
                    embed.add_field(
                        name="{}:".format(change.key),
                        value="Set to: `{c.new_value}`".format(c=change),
                        inline=True)
            else:
                break
        return embed
Ejemplo n.º 19
0
 def update_msg(self):
     msgcontent = "**Word**: " + " ".join(
         self.word_to_emote(self.word_current))
     embed = MessageEmbed()
     embed.set_image(url=self.get_hangman_image(self.failed_attempts))
     self.main_msg.edit(msgcontent, embed=embed)
Ejemplo n.º 20
0
def get_parking_qut():
    """Replies with an embed object containing QUT parking information"""
    url = "https://paseweb.parkassist.com/sites/qut/status/v2/zones.json"  # URL that has the parking info
    embed = MessageEmbed()  # Create a discord embed object

    # Specify the name, logo, url and description of the parking bot response
    embed.set_author(
        name='QUT Parking Bot',
        icon_url=
        'https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/QUTLogo.svg/1200px-'
        + 'QUTLogo.svg.png')
    embed.url = 'https://paseweb.parkassist.com/en/sites/qut/embedded_widgets/available_spaces'
    embed.description = 'This is scraped from the parkassist website. Only Gardens Point is supported at the moment.'

    response = requests.get(url)  # Fetch the parking info

    if response.status_code == 200:  # If we got an ok response parse the JSON
        parking = json.loads(response.text)
        p = 0
        freeway = 0
        szc = 0

        # This bit of hackery is needed because the parking json segments each level into a separate zone
        for zone in parking["response"]:
            if zone["id"] in [1, 2]:
                p += zone["counts"]["available"]
            elif zone["id"] in [3]:
                freeway += zone["counts"]["available"]
            elif zone["id"] in [4, 5, 6, 7, 8, 9]:
                szc += zone["counts"]["available"]

        # Add each zone to the parking bot response
        embed.add_field(name='P Block (GP)',
                        value='{} parks available.'.format(p),
                        inline=True)
        embed.add_field(name='Under Freeway (GP)',
                        value='{} parks available.'.format(freeway),
                        inline=True)
        embed.add_field(name='S/Z/C Block (GP)',
                        value='{} parks available.'.format(szc),
                        inline=True)
        embed.add_field(
            name="Last update from QUT:",
            value=parking["response"][0]["counts"]["timestamp"][11:19],
            inline=False)

    else:  # If we didn't get an OK response then something went wrong
        embed.add_field(
            name='Data Not Available',
            value='Something went wrong while fetching the parking data. This '
            'is most likely a problem with the server the data '
            'comes from.',
            inline=False)

    # Add some more info to the end of the parking bot response
    embed.add_field(
        name='More Info',
        value='For more info about costs and restrictions see this web page: '
        +
        "https://www.qut.edu.au/about/services-and-facilities/all-services/parking",
        inline=False)

    return embed  # return the embed object so the parent function can send a response
Ejemplo n.º 21
0
def handle_exception(event, bot, exception):
    # catch everything and extract all info we can from the func arguments so we see what exactly was going on
    print("Exception caught, extracting information")

    print("====EXCEPTION====")
    print(exception)

    print("====STACKTRACE====")
    print(traceback.format_exc())

    print("====ORIGINAL MESSAGE====")
    print(event.msg.content)

    print("====SENDER====")
    print(event.msg.author)

    print("====Channel====")
    print("{} ({})".format(event.msg.channel.name, event.msg.channel.id))

    embed = MessageEmbed()
    embed.title = "Exception caught"
    embed.add_field(name="Original message",
                    value=Utils.trim_message(event.msg.content, 1024))
    embed.add_field(name="Channel",
                    value="{} ({})".format(event.msg.channel.name,
                                           event.msg.channel.id))
    embed.add_field(name="Sender", value=str(event.msg.author))
    embed.add_field(name="Exception", value=str(exception))
    parts = Pages.paginate(str(traceback.format_exc()), max_chars=1024)
    if len(parts) > 4:
        embed.add_field(
            name="Stacktrace",
            value=
            "Something went incredibly wrong, stacktrace is over 4096 chars!")
    else:
        for part in parts:
            embed.add_field(name="Stacktrace", value=part)
    embed.timestamp = datetime.utcnow().isoformat()
    embed.color = int('ff0000', 16)
    log_to_bot_log(bot, embed=embed)
Ejemplo n.º 22
0
    def on_ready(self, event):
        embed = MessageEmbed()
        embed.set_footer(text='Aetherya {}'.format('Production' if ENV ==
                                                   'prod' else 'Testing'))
        embed.timestamp = datetime.utcnow().isoformat()
        embed.color = 0x779ecb

        reconnects = self.client.gw.reconnects
        self.log.info('Started session %s', event.session_id)
        if reconnects:
            embed.title = 'Reconnected'
            embed.color = 0xffb347
        else:
            embed.title = 'Connected'
            embed.color = 0x77dd77

        embed.add_field(name='Gateway Server',
                        value=event.trace[0],
                        inline=False)
        embed.add_field(name='Session Server',
                        value=event.trace[1],
                        inline=False)

        self.client.api.channels_messages_create(AETHERYA_CONTROL_CHANNEL,
                                                 embed=embed)
Ejemplo n.º 23
0
    def info(self, event, user=None):

        if not user:
            user = event.author
        else:
            if not isinstance(user, DiscoUser):
                try:
                    user = self.state.guilds[event.guild.id].members[user].user
                except KeyError:
                    try:
                        user = self.state.users[user]
                    except KeyError:
                        try:
                            user = self.bot.client.api.users_get(user)
                        except APIException:
                            return event.msg.reply(
                                'User not found :eyes:').after(3).delete()

        self.client.api.channels_typing(event.channel.id)

        content = []
        content.append('**\u276F User Information**')
        content.append('Profile: <@{}>'.format(user.id))

        created_dt = to_datetime(user.id)
        content.append('Created: {} ({})'.format(
            humanize.naturaltime(datetime.utcnow() - created_dt),
            created_dt.strftime("%b %d %Y %H:%M:%S")))

        member = event.guild.get_member(user.id) if event.guild else None

        if user.presence:  #I couldn't get this to work w/o it lol
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: <{}> {}'.format(emoji, status))
            if user.presence.game and user.presence.game.name:
                if user.presence.game.type == ActivityTypes.DEFAULT:
                    content.append('{}'.format(user.presence.game.name))
                if user.presence.game.type == ActivityTypes.CUSTOM:
                    content.append('Custom Status: {}'.format(
                        user.presence.game.state))
                if user.presence.game.type == ActivityTypes.LISTENING:
                    content.append('Listening to {} on Spotify'.format(
                        user.presence.game.details)
                                   )  #In the embed, details is the songname.
                if user.presence.game.type == ActivityTypes.STREAMING:
                    content.append('Streaming: [{}]({})'.format(
                        user.presence.game.name, user.presence.game.url))

        if user.public_flags:
            badges = ''
            user_badges = list(UserFlags(user.public_flags))
            for badge in user_badges:
                badges += '<{}> '.format(BADGE_EMOJI[badge])

            content.append('Badges: {}'.format(badges))

        if member:
            content.append('\n**\u276F Member Information**')

            if member.nick:
                content.append('Nickname: {}'.format(member.nick))

            content.append('Joined: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - member.joined_at),
                member.joined_at.strftime("%b %d %Y %H:%M:%S"),
            ))

            if member.roles:
                content.append('Roles: {}'.format(', '.join(
                    ('<@&{}>'.format(member.guild.roles.get(r).id)
                     for r in member.roles))))

        # Execute a bunch of queries
        newest_msg = Message.select(fn.MAX(Message.id)).where(
            (Message.author_id == user.id)
            & (Message.guild_id == event.guild.id)).tuples()[0][0]

        oldest_msg = Message.select(fn.MIN(Message.id)).where(
            (Message.author_id == user.id)
            & (Message.guild_id == event.guild.id)).tuples()[0][0]  #Slow Query

        voice = GuildVoiceSession.select(
            fn.COUNT(GuildVoiceSession.user_id),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where((GuildVoiceSession.user_id == user.id)
                & (~(GuildVoiceSession.ended_at >> None))
                & (GuildVoiceSession.guild_id == event.guild.id)).tuples()[0]

        infractions = Infraction.select(Infraction.id).where(
            (Infraction.user_id == user.id)
            & (Infraction.guild_id == event.guild.id)).tuples()

        if newest_msg and oldest_msg:
            content.append('\n **\u276F Activity**')
            content.append('Last Message: {} ({})'.format(
                humanize.naturaltime(datetime.utcnow() -
                                     to_datetime(newest_msg)),
                to_datetime(newest_msg).strftime("%b %d %Y %H:%M:%S"),
            ))
            content.append('First Message: {} ({})'.format(
                humanize.naturaltime(datetime.utcnow() -
                                     to_datetime(oldest_msg)),
                to_datetime(oldest_msg).strftime("%b %d %Y %H:%M:%S"),
            ))

        if len(infractions) > 0:
            content.append('\n**\u276F Infractions**')
            total = len(infractions)
            content.append('Total Infractions: **{:,}**'.format(total))

        if voice[0]:
            content.append('\n**\u276F Voice**')
            content.append('Sessions: `{:,}`'.format(voice[0]))
            content.append('Time: `{}`'.format(
                str(humanize.naturaldelta(voice[1])).title()))

        embed = MessageEmbed()

        try:
            avatar = User.with_id(user.id).get_avatar_url()
        except:
            avatar = user.get_avatar_url(
            )  # This fails if the user has never been seen by speedboat.

        embed.set_author(name='{}#{} ({})'.format(
            user.username,
            user.discriminator,
            user.id,
        ),
                         icon_url=avatar)

        embed.set_thumbnail(url=avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, avatar)
        event.msg.reply('', embed=embed)
Ejemplo n.º 24
0
    def command_info(self, event):

        if Perms.integer(event.msg.member) <= 4:
            return event.msg.reply("This command has been temporarily" + 
            " disabled due to a bug within Disco. Please refrain from " +
            "attempting to use this command while the bug is being fixed.")


        # Check if we received multiple arguments
        if len(event.args) == 1:
            cmd = event.args[0]

        elif len(event.args) >= 2:
            cmd = event.args[0] + " " + event.args[1]

        else:
            cmd = "cmd info"



        # Ensure that supplied command is valid
        if cmd not in cmd_list.keys():
            return event.msg.reply(Util.invalid_arg.format(cmd))


        cmd = cmd_list[cmd]


        me = self.state.me
        me_member = event.guild.get_member(me)


        # Ensure the plugin is enabled in the guild
        if event.guild:
            guilds = PluginConfig.load("guild_list")
            g_id = str(event.guild.id)

            # Ensure guild has been enabled
            if g_id in guilds:

                # Ensure the plugin doesn't bypass enabled
                if not cmd.plugin.bypass_enabled:

                    # Check if the plugin is not enabled
                    if cmd.plugin.name not in guilds[g_id]:
                        return event.msg.reply(
                            Util.plugin_not_enabled.format(
                                cmd.plugin.name
                            )
                        )


        # Get command data
        plugin = cmd.plugin


        cmd_config = plugin.commands_config[str(cmd.group)][cmd.name]


        config = GuildConfig.load(event.guild.id)


        try:
            cmd_level = config["cmd_lvls"][plugin.name][str(cmd.group)][cmd.name]
        except KeyError:
            cmd_level = cmd_config["default_level"]


        try:
            bypass_user_perms = config["permissions"]["bypass_user_perms"]
        except KeyError:
            bypass_user_perms = cmd_config["bypass_user_perms"]


        user_level = Perms.integer(event.msg.member)



        user_perms = filter_perms(
            event.channel.get_permissions(event.msg.member),
            cmd_config["user_perms"]
        )

        bot_perms = filter_perms(
            event.channel.get_permissions(me_member),
            cmd_config["bot_perms"]
        )


        # Cycle through command triggers making the alias list
        cmd_aliases = []
        for name in cmd.triggers:
            cmd_aliases.append(name)
        cmd_aliases.remove(cmd.name)

        variables = {

            # Constants or config values
            "pre": Config.load()["bot"]["commands_prefix"],
            "max_perm_int": max_permission_int,
            "perm_levels": perm_ints,
            "emoji": custom_emojis,

            # User variables
            "user_discrim": event.msg.author.discriminator,
            "user_username": event.msg.author.username,
            "user_nickname": event.msg.member.name,
            "user_id": event.msg.author.id,

            # Bot variables
            "bot_nickname": me_member.name,
            "bot_username": me.username,
            "bot_id": me.id,

            # Miscellanious information we may want to display
            "cmd_total": len(plugin.commands),  #TODO: Make this works
            "plg_name": plugin.name
        }


        # Format data nicely in an embed
        embed = MessageEmbed()

        embed.title = "{bot_nickname} Help:".format(**variables)
        embed.color = 0x00aa00
        embed.set_footer(
            text="Requested by: {user_username}#{user_discrim} ({user_id})".format(
                **variables
            )
        )

        # Command description
        embed.add_field(
            name="Command Description:",
            value=" ".join(
                cmd_config["info"]
            ).format(
                **variables
            ).replace(
                "& &",
                ""
            ),
            inline=False
        )

        # Command syntax
        embed.add_field(
            name="Command Syntax:",
            value="```" + " ".join(
                cmd_config["syntax"]
            ).format(
                **variables
            ).replace(
                "& &",
                ""
            ) + "```",
            inline=False
        )

        # Check if user permissions are bypassed
        if not bypass_user_perms:

            # Ensure that the permissions didn't return `None`
            if user_perms:

                # Permissions that the user needs to have
                embed.add_field(
                    name="Required User Permissions:",
                    value="Green indicates that the permission requirement is met, red indicates it is not met.\n```diff\n{}\n```".format(user_perms),
                    inline=False
                )

        # Check if we are adding bot permissions
        if user_level >= 1:

            # Ensure that the permissions didn't return `None`
            if bot_perms:
                embed.add_field(
                    name="Required Bot Permissions:",
                    value="Green indicates that the permission requirement is met, red indicates it is not met.\n```diff\n{}\n```".format(bot_perms),
                    inline=False
                )

        # Can the command be ran in Direct Messages
        embed.add_field(
            name="Allowed in DMs:",
            value=cmd_config["allow_DMs"],
            inline=True
        )

        # Whether or not the requestee can run the command
        embed.add_field(
            name="Can Requestee Run It:",
            value=(user_level >= cmd_level),
            inline=True
        )

        # Whether or not this command is bypassing user permissions
        embed.add_field(
            name="Bypasses User Permissions:",
            value=bypass_user_perms,
            inline=True
        )

        # The internal permission level that the bot requires for the user
        embed.add_field(
            name="Permission Level:",
            value=cmd_level,
            inline=True
        )

        # Check if there are actully any aliases before adding it
        if len(cmd_aliases):

            # A list of aliases that the command has
            embed.add_field(
                name="Aliases:",
                value=", ".join(cmd_aliases),
                inline=True
            )

        # Alert user what plugin the command comes from
        embed.add_field(
            name="Plugin Name:",
            value=plugin.name,
            inline=True
        )


        # Respond with the embed
        return event.msg.reply(embed=embed)
Ejemplo n.º 25
0
    def get_history(self, member, show_mods: bool):
        infractions = Infraction.find(Infraction.user == member.id)
        total_warns = len([i for i in infractions if i.type == "warn"])
        active_warns = total_warns % self.config['warns_to_strike']
        active_strikes = len([i for i in infractions if i.type == "strike"]) \
                         + total_warns // self.config['warns_to_strike']

        embed = MessageEmbed()
        embed.title = member.name + "'s History"
        embed.description = f"""__**Details:**__
        
        Total Warnings: **{active_warns} / {self.config['warns_to_strike']}**
        Total Strikes: **{active_strikes} / {self.config['strike_to_ban']}**
        Strikes from Warnings: **{total_warns // self.config['warns_to_strike']}**
        Account Creation date: **{to_datetime(member.id)}**
        """
        embed.set_thumbnail(url=member.user.get_avatar_url())
        embed.color = 0x6832E3
        embeds = [embed]
        if infractions:
            embed.description += """
            __**Infractions**__
            """

            infraction_base = """
            ICIN: **{}**
            Type: **{}**
            Reason: ***{}***
            Date: **{}**
            {}"""

            for i, infraction in enumerate(infractions):
                new_infraction = infraction_base.format(
                    i, infraction.type, infraction.reason or "",
                    datetime.utcfromtimestamp(infraction.date),
                    f"Moderator: <@{infraction.moderator}>"
                    if show_mods else "")
                if len(embeds[-1].description + new_infraction) >= 2048:
                    next_embed = MessageEmbed()
                    next_embed.color = 0x6832E3
                    next_embed.description = new_infraction
                    embeds.append(next_embed)
                else:
                    embeds[-1].description += new_infraction

        return embeds
Ejemplo n.º 26
0
            display_state = weather['display_location']['state_name']
            display_city = weather['display_location']['city']
            forecast_url = weather['forecast_url']
            icon_url = weather['icon_url']
            precip = weather['precip_today_string']
            temp_c = weather['temp_c']
            temp_f = weather['temp_f']
            condition = weather['weather']
            wind_dir = weather['wind_dir']
            wind_mph = weather['wind_mph']
            wind_kph = weather['wind_kph']
        except KeyError, e:
            self.log.error('Invalid query')
            return

        embed = MessageEmbed()
        embed.set_author(
            name='Wunderground',
            url='http://www.wunderground.com',
            icon_url='http://icons.wxug.com/graphics/wu2/logo_130x80.png')
        embed.title = '{}, {}'.format(display_state, display_city)
        embed.url = forecast_url
        embed.description = condition
        embed.add_field(name='Temperature',
                        value='{}° F ({}° C)'.format(temp_f, temp_c),
                        inline=True)
        embed.add_field(name='Precipitation', value=precip, inline=True)
        embed.add_field(name='Wind',
                        value='From the {} at {}mph ({}kph)'.format(
                            wind_dir, wind_mph, wind_kph),
                        inline=True)
Ejemplo n.º 27
0
    def show_help(self, event, name: str = None):
        """Explain commands or list them

        The help commands provides an easy way for you to learn about a certain command, or list available ones.

        If you want to access a specific command, type `]help <name>`, For example, `]help ban`.

        If you want to display a list all command categories, simply type `]help` with nothing else.

        If you want to list all commands in a category, simply type `]help <Name>`, For example, `]help Mod`

        Tip: commands will always be all lower case, command categories are Titled.
        """

        if not name:
            embed = MessageEmbed()
            embed.color = 0x00FFFF
            embed.title = "List Command Categories"
            embed.description = "If you want to see how to use the help command, type `]help help`, otherwise, " \
                                "below are the available command categories."
            for plugin in self.bot.plugins.values():
                name, desc = plugin.__doc__.split(' | ')
                embed.add_field(name=name, value=desc, inline=False)
            event.msg.reply(embed=embed)
        elif name.title() == name:
            for plugin in self.bot.plugins.values():
                if name in plugin.__doc__:
                    break
            else:
                return event.msg.reply(
                    "Sorry, but I could not find the category '{0}'".format(
                        name))

            embed = MessageEmbed()
            embed.color = 0x00FFFF
            embed.title = plugin.__doc__

            for func in plugin.meta_funcs:
                if hasattr(func, 'docs'):
                    embed.add_field(name=func.docs[0],
                                    value=func.docs[1],
                                    inline=False)

            event.msg.reply(embed=embed)
        else:
            for plugin in self.bot.plugins.values():
                for func in plugin.meta_funcs:
                    if hasattr(func, 'docs') and func.docs[0] == name:
                        embed = MessageEmbed()
                        embed.title = func.docs[1]
                        embed.color = 0x00FFFF
                        embed.description = func.docs[2]
                        return event.msg.reply(embed=embed)
            event.msg.reply(
                "Sorry, but I could not find the command '{0}'".format(name))
Ejemplo n.º 28
0
    def server(self, event, guild_id=None):
        guild: Guild = self.state.guilds.get(
            guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('Invalid server')

        embed = MessageEmbed()
        embed.set_author(
            MessageEmbedAuthor(name=guild.name, icon_url=guild.icon_url()))

        # General Abouts
        about_field = MessageEmbedField()
        about_field.name = '**\u276F About**'
        about_text = 'Created by {} ({}) — <t:{}:R>'.format(
            guild.owner, guild.owner.id,
            int(to_datetime(guild.id).replace(tzinfo=pytz.UTC).timestamp()))
        about_text += '\nMembers: {:,}/{:,}'.format(
            guild.approximate_presence_count, guild.member_count)
        about_text += '\nRegion: {}'.format(guild.region)
        about_field.value = about_text
        embed.add_field(about_field)

        # General Counts
        counts_field = MessageEmbedField()
        counts_field.name = '\n**\u276F Counts**'
        text_count = sum(1 for c in list(guild.channels.values())
                         if not c.is_voice and not c.is_thread)
        voice_count = len(guild.channels) - text_count

        counts_field.value = 'Roles: {:,}\nText: {:,}\nVoice: {:,}'.format(
            len(guild.roles), text_count, voice_count)
        embed.add_field(counts_field)

        # Security
        security_field = MessageEmbedField()
        security_field.name = '\n**\u276F Security**'
        security_field.value = 'Verification: {}\nExplicit Content: {}'.format(
            guild.verification_level, guild.explicit_content_filter)
        embed.add_field(security_field)

        # Features
        features_field = MessageEmbedField()
        features_field.name = '\n**\u276F Features**'
        features_field.value = 'Features: {}'.format(', '.join(guild.features))
        embed.add_field(features_field)

        if guild.icon:
            embed.color = get_dominant_colors_guild(guild)
        event.msg.reply('', embed=embed)
Ejemplo n.º 29
0
    def on_commands_info(self, event, mid):
        cmd = Command.select(Command, Message, Channel).join(
            Message,
            on=(Command.message_id == Message.id).alias('message')).join(
                Channel,
                on=(Channel.channel_id == Message.channel_id).alias('channel')
            ).join(
                User,
                on=(User.user_id == Message.author_id).alias('author')).where(
                    Command.message_id == mid).order_by(
                        Message.timestamp.desc(), ).get()

        embed = MessageEmbed()
        embed.title = '{}.{} ({})'.format(cmd.plugin, cmd.command,
                                          cmd.message.id)
        embed.set_author(name=unicode(cmd.message.author),
                         icon_url=cmd.message.author.get_avatar_url())
        embed.color = 0x77dd77 if cmd.success else 0xff6961

        if not cmd.success:
            embed.description = u'```{}```'.format(cmd.traceback)

        embed.add_field(name='Message', value=cmd.message.content)
        embed.add_field(
            name='Channel',
            value=u'{} `{}`'.format(cmd.message.channel.name,
                                    cmd.message.channel.channel_id))
        embed.add_field(name='Guild', value=unicode(cmd.message.guild_id))
        event.msg.reply(embed=embed)
Ejemplo n.º 30
0
    def infraction_info(self, event, infraction):
        try:
            user = User.alias()
            actor = User.alias()

            infraction = Infraction.select(Infraction, user, actor).join(
                user, on=((Infraction.user_id == user.user_id).alias('user'))
            ).switch(Infraction).join(
                actor,
                on=((Infraction.actor_id == actor.user_id).alias('actor')
                    )).where((Infraction.id == infraction)
                             & (Infraction.guild_id == event.guild.id)).get()
        except Infraction.DoesNotExist:
            raise CommandFail(
                'cannot find an infraction with ID `{}`'.format(infraction))

        type_ = {i.index: i for i in Infraction.Types.attrs}[infraction.type_]
        embed = MessageEmbed()

        if type_ in (Infraction.Types.MUTE, Infraction.Types.TEMPMUTE,
                     Infraction.Types.TEMPROLE):
            embed.color = 0xfdfd96
        elif type_ in (Infraction.Types.KICK, Infraction.Types.SOFTBAN):
            embed.color = 0xffb347
        else:
            embed.color = 0xff6961

        embed.title = str(type_).title()
        embed.set_thumbnail(url=infraction.user.get_avatar_url())
        embed.add_field(name='User',
                        value=unicode(infraction.user),
                        inline=True)
        embed.add_field(name='Moderator',
                        value=unicode(infraction.actor),
                        inline=True)
        embed.add_field(name='Active',
                        value='yes' if infraction.active else 'no',
                        inline=True)
        if infraction.active and infraction.expires_at:
            embed.add_field(name='Expires',
                            value=humanize.naturaldelta(infraction.expires_at -
                                                        datetime.utcnow()))
        embed.add_field(name='Reason',
                        value=infraction.reason or '_No Reason Given',
                        inline=False)
        embed.timestamp = infraction.created_at.isoformat()
        event.msg.reply('', embed=embed)
Ejemplo n.º 31
0
    def messageinfo(self, event, mid):
        try:
            msg = Message.select(Message).where(
                    (Message.id == mid)
                ).get()
        except Message.DoesNotExist:
            raise CommandFail('the id specified does not exist in our message database.')
        message_content = msg.content
        author_id = msg.author.id
        guild_id = msg.guild_id
        channel_id = msg.channel_id
        deleted = msg.deleted
        num_edits = msg.num_edits
        if num_edits > 0:
            num_edits_bool = True
        else:
            num_edits_bool = False
        discrim = str(msg.author.discriminator)
        # if len(str(cached_name[1])) != 4:
        #     while len(str(temp_str)) < 4:
        #         temp_str = '0' + str(temp_str)
        cached_name = str(msg.author.username) + '#' + str(discrim)
        avatar_name = msg.author.avatar 
        content = []
        embed = MessageEmbed()
        member = event.guild.get_member(author_id)
        
        if not avatar_name:
            if member:
                avatar = default_color(str(member.user.default_avatar))
            else:
                avatar = None   
        elif avatar_name.startswith('a_'):
            avatar = u'https://cdn.discordapp.com/avatars/{}/{}.gif'.format(author_id, avatar_name)
        else:
            avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(author_id, avatar_name)
        if member:
            embed.set_author(name='{} ({})'.format(member.user, member.id), icon_url=avatar)
            embed.set_thumbnail(url=avatar)
        else:
            if avatar:
                embed.set_author(name='{} ({})'.format(cached_name, author_id), icon_url=avatar)
                embed.set_thumbnail(url=avatar)
            else:
                embed.set_author(name='{} ({})'.format(cached_name, author_id))

        # embed.title = "Message Content:"
        content.append(u'**\u276F Message Information:**')
        content.append(u'In channel: <#{}>'.format(channel_id))
        content.append(u'Edited: **{}**'.format(num_edits_bool))
        if deleted:
            content.append(u'Deleted: **{}**'.format(deleted))
        content.append(u'Content: ```{}```'.format(message_content))
        if member:
            content.append(u'\n**\u276F Member Information**')

            if member.nick:
                content.append(u'Nickname: {}'.format(member.nick))

            content.append('Joined: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - member.joined_at),
                member.joined_at.isoformat(),
            ))

            if member.roles:
                roles = []
                for r in member.roles:
                    roles.append(member.guild.roles.get(r))
                roles = sorted(roles, key=lambda r: r.position, reverse=True)
                total = len(member.roles)
                roles = roles[:20]
                content.append(u'Roles ({}): {}{}'.format(
                    total, ' '.join(r.mention for r in roles),
                    ' (+{})'.format(total-20) if total > 20 else ''
                ))
                
        embed.description = '\n'.join(content)
        # embed.url = 'https://discordapp.com/channels/{}/{}/{}'.format(guild_id, channel_id, mid)
        embed.timestamp = datetime.utcnow().isoformat()
        if not event.author.avatar:
            auth_avatar = default_color(str(member.user.default_avatar))
        elif event.author.avatar.startswith('a_'):
            auth_avatar = u'https://cdn.discordapp.com/avatars/{}/{}.gif'.format(event.author.id, event.author.avatar)
        else:
            auth_avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(event.author.id, event.author.avatar)
        embed.set_footer(text='Requested by {}#{} ({})'.format(event.author.username, event.author.discriminator, event.author.id), icon_url=auth_avatar)
        try:
            embed.color = get_dominant_colors_user(member.user, avatar)
        except:
            embed.color = '00000000'
        event.msg.reply('', embed=embed)