Пример #1
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)) &
            (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) &
            (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)
Пример #2
0
    def on_profile_command(self, event, args):
        """Displays your profile for the world to see!"""
        mariadb = self.bot.plugins.get("mariadb_funcs")
        if args.userID:
            user = args.userID
            user = re.sub("[<@!>]", '', user)
        else:
            user = event.msg.author.id
        if mariadb.check_user_exists(user):
            usrSettings = mariadb.get_user_settings(user)
            userID = usrSettings[0]
            userObj = self.state.users.get(userID)
            userPFPLink = userObj.get_avatar_url()
            userGoBy = usrSettings[1]
            userDesc = usrSettings[2]
            userTimezone = usrSettings[3]
            userIntFacts = usrSettings[4]

            if userObj.presence is not UNSET:
                usrState = userObj.presence.status
            else:
                usrState = "offline"

            profileEmbed = MessageEmbed()
            profileEmbed.title = "The amazing profile of {0}#{1} who is currently **{2}**!".format(
                userObj.username, userObj.discriminator, usrState)
            profileEmbed.set_thumbnail(url=userPFPLink)

            color = random.randint(0, 0xFFFFFF)
            profileEmbed.color = color

            if userDesc == None:
                profileEmbed.description = """This user hasn't set a description!
                Please run `@Who Am I#1225 adjustprofile blurb`"""
            else:
                profileEmbed.description = userDesc

            if userGoBy != None:
                profileEmbed.add_field(name="Howdy! Call me...",
                                       value="```{}```".format(userGoBy),
                                       inline=True)

            if userTimezone != None:
                profileEmbed.add_field(name="My timezone is...",
                                       value="```{}```".format(userTimezone),
                                       inline=True)

            if userIntFacts != None:
                profileEmbed.add_field(
                    name="Here is an interesting fact about me!",
                    value="```{}```".format(userIntFacts),
                    inline=True)

            event.msg.reply(embed=profileEmbed)

        else:
            event.msg.reply(
                ":no_good: This user does not have a profile!",
                "They can make one by running `@Who Am I#1225 setup`")
Пример #3
0
    def list_settings(self, event):
        settings_msg = """
        __**Prefix**__: {prefix}
        __**Referee Role**__: {rr}
        __**Games Category**__: {gc}
        __**Spectator Roles**__: {sr}
        __**Game Logs**__: {gl}
        """
        settings = Guild.using_id(event.guild.id)

        games_category = None
        if settings.games_category:
            games_category = event.guild.channels.get(settings.games_category)

        log_channel = None
        if settings.log_channel:
            log_channel = event.guild.channels.get(settings.log_channel)

        spectator_roles = []
        if len(settings.spectator_roles) > 0:
            for x in settings.spectator_roles:
                spectator_roles.append('<@&{}>'.format(x))
        embed = MessageEmbed()
        # embed.color = 0xFF0000
        embed.add_field(
            name='General Settings',
            value=settings_msg.format(
                prefix=settings.prefix,
                rr='{}'.format('`None`' if settings.referee_role ==
                               None else '<@&' + str(settings.referee_role) +
                               '>'),
                gc='{} (`{}`)'.format(games_category.name, games_category.id)
                if settings.games_category else '`None`',
                sr='{}'.format('`None`' if len(spectator_roles) ==
                               0 else ', '.join(spectator_roles)),
                gl='({}) {channel}'.format(
                    '<{}>'.format(
                        YES_EMOJI if settings.logs_enabled else NO_EMOJI),
                    channel='{} (`{}`)'.format(log_channel.name,
                                               log_channel.id)
                    if settings.log_channel else '`None`')))
        embed.add_field(name='Enabled Games',
                        value='{}'.format(''.join(
                            settings.enabled_games_emotes())),
                        inline=True)
        embed.add_field(name='Disabled Games',
                        value='{}'.format(''.join(
                            settings.disabled_games_emotes())),
                        inline=True)
        embed.set_footer(
            text='Go get help with settings, do {}help settings'.format(
                settings.prefix),
            icon=self.state.me.get_avatar_url())
        embed.set_thumbnail(url=event.guild.get_icon_url('png'))
        return event.msg.reply('', embed=embed)
Пример #4
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)
Пример #5
0
 def log_action(self, action: str, content: str, target=None, **kwargs):
     embed = MessageEmbed()
     embed.title = action + ("  | " +
                             str(target.user)) if target is not None else ""
     embed.color = 0x6832E3
     if target is not None:
         embed.description = content.format(t=target.user, **kwargs)
         embed.set_thumbnail(url=target.user.avatar_url)
     else:
         embed.description = content.format(**kwargs)
     embed.timestamp = datetime.utcnow().isoformat()
     self.client.api.channels_messages_create(
         self.config["BOT_LOGGING_CHANNEL"], " ", embed=embed)
Пример #6
0
    def jeopardy_command(self, event, args):
        self.log.info('{} executed !jeopardy with args: {}'.format(
            event.author, args))

        if not args.random:
            return

        jservice_base_url = 'http://jservice.io/{}'
        jservice_random = '/api/random'
        jeopardy_response = requests.get(
            jservice_base_url.format(jservice_random)).json()[0]

        from pprint import pprint
        pprint(jeopardy_response)

        jeopardy_q = jeopardy_response['question'].replace('&', 'and')
        jeopardy_a = self.clean_html(jeopardy_response['answer'])
        jeopardy_id = jeopardy_response['id']
        jeopardy_amount = '${}'.format(jeopardy_response['value'])
        jeopardy_category = jeopardy_response['category']['title']

        jeopardy_q = '\n'.join([
            ' '.join(jeopardy_q.split()[s:s + 6])
            for s in range(0, len(jeopardy_q.split()), 6)
        ])

        self.log.info('amount: {}'.format(jeopardy_amount))

        img2txt_url = 'http://api.img4me.com/?text={}&font=impact&size=35&fcolor={}&bcolor=060CE9'
        question_color = 'FFFFFF'
        amount_color = 'D49516'
        question_value = requests.get(
            img2txt_url.format(jeopardy_q, question_color)).text
        amount_value = requests.get(
            img2txt_url.format(jeopardy_amount, amount_color)).text

        embed = MessageEmbed()
        embed.set_author(
            name='Jeopardy!',
            url='http://jservice.io/',
            icon_url=
            'http://jservice.io/assets/trebek-503ecf6eafde622b2c3e2dfebb13cc30.png'
        )
        embed.title = 'Category: {}'.format(jeopardy_category)
        embed.timestamp = pendulum.now().in_tz('America/New_York').isoformat()
        embed.set_thumbnail(url=amount_value)
        embed.set_image(url=question_value)
        embed.set_footer(text='Powered by jservice.io')
        embed.color = '13931798'  # dark yellow (hex: #D49516)

        event.msg.reply(embed=embed)
Пример #7
0
    def server(self, event, guild_id=None):
        guild = self.state.guilds.get(guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('Invalid server')

        content = []
        content.append('**\u276F Server Information**')
        content.append('Owner: {} ({})'.format(guild.owner, guild.owner.id))

        created_at = to_datetime(guild.id)
        content.append('Created: {} ({})'.format(
            humanize.naturaltime(datetime.utcnow() - created_at),
            created_at.isoformat(),
        ))

        content.append('Members: {:,}'.format(len(guild.members)))
        if guild.features:
            content.append('Features: {}'.format(', '.join(guild.features)))

        content.append('\n**\u276F Counts**')
        text_count = sum(1 for c in list(guild.channels.values())
                         if not c.is_voice)
        voice_count = len(guild.channels) - text_count
        content.append('Roles: {}'.format(len(guild.roles)))
        content.append('Text: {}'.format(text_count))
        content.append('Voice: {}'.format(voice_count))

        content.append('\n**\u276F Members**')
        status_counts = defaultdict(int)
        for member in list(guild.members.values()):
            if not member.user.presence:
                status = Status.OFFLINE
            else:
                status = member.user.presence.status
            status_counts[status] += 1

        for status, count in sorted(list(status_counts.items()),
                                    key=lambda i: str(i[0]),
                                    reverse=True):
            content.append('<{}> - {}'.format(STATUS_EMOJI[status], count))

        embed = MessageEmbed()
        if guild.icon:
            embed.set_thumbnail(url=guild.icon_url)
            # TODO: Fix whatever caused me to need to do this
            try:
                embed.color = get_dominant_colors_guild(guild)
            except:
                embed.color = 0x7289DA
        embed.description = '\n'.join(content)
        event.msg.reply('', embed=embed)
Пример #8
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)
Пример #9
0
 def generate_page(self, page_number, guide):
     guide = self.config.guides[guide]
     max_page_number = len(guide["pages"])
     title = "{title} ({page}/{max_pages})".format(
         title=guide["title"], page=page_number, max_pages=max_page_number)
     description = guide["description"]
     embed = MessageEmbed()
     embed.title = title
     embed.description = description
     if page_number > max_page_number:
         embed.add_field(
             name="what??",
             value=
             "how did you get here? report this bug to brxxn#0632 or Dabbit Prime#0896."
         )
         return embed
     page = guide["pages"][page_number - 1]
     if page.get("color") is not None:
         embed.color = int(page["color"], 16)
     if page.get("image") is not None:
         embed.set_thumbnail(
             url=
             "https://cdn.discordapp.com/attachments/471128155214577670/504390962496143370/suffer.jpg"
         )
     table_of_contents_field = None
     if "table_of_contents" in page:
         if page["table_of_contents"]:
             # Generate TOC
             table_of_contents = ""
             index = 0
             for item in guide["pages"]:
                 index = index + 1
                 table_of_contents = table_of_contents + "{page}. {title} - {description}\n".format(
                     page=str(index),
                     title=str(item["title"]),
                     description=str(item["description"]))
             table_of_contents_field = {
                 "title": "Table of Contents",
                 "content": table_of_contents
             }
     embed.add_field(name=page["title"], value=page["description"])
     if table_of_contents_field is not None:
         embed.add_field(name=table_of_contents_field["title"],
                         value=table_of_contents_field["content"])
     for field in page["fields"]:
         embed.add_field(name=field["name"], value=field["value"])
     return embed
Пример #10
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
Пример #11
0
    def on_info_command(self, event):
        """Displays some info about the bot, or me!"""
        infoEmbed = MessageEmbed()
        github = "https://github.com/One-Nub/Who-Am-I"
        myPfpImg = "https://i.lensdump.com/i/WDsOXb.png"
        botPfpImg = "https://i.lensdump.com/i/WDs4G5.png"
        botInvite = ("https://discordapp.com/api/oauth2/authorize?client_id=" +
                     "592796597209792542&permissions=380096&scope=bot")

        infoEmbed.title = "Welcome to **Who Am I**!"
        infoEmbed.url = github
        infoEmbed.color = 0x8DD0E1
        infoEmbed.description = (
            "Hey there! This bot was created for the June 2019 " +
            "Discord Hackathon!")
        infoEmbed.set_thumbnail(url=botPfpImg)
        infoEmbed.set_author(name="Nub#8399", icon_url=myPfpImg)
        infoEmbed.timestamp = datetime.utcnow().isoformat()

        infoEmbed.add_field(
            name="What is/was this Hackathon?",
            value=
            "This was a week where developers, such as myself, would create"
            " either a bot of some sort, "
            "or something creative (art, music, etc...), "
            "and we would then submit our creations by the end of the week!",
            inline=False)

        infoEmbed.add_field(
            name="So what does this bot do?",
            value=
            "This bot is meant to make it easier to learn about people and share"
            "info about yourself!"
            "\nThis is done by letting users give info to the bot"
            "& then displaying that info with a simple command!",
            inline=False)

        infoEmbed.add_field(name="View my github here!",
                            value=github,
                            inline=False)
        infoEmbed.add_field(name="Invite me here!",
                            value="[Invite me!]({})".format(botInvite),
                            inline=False)
        event.msg.reply(embed=infoEmbed)
Пример #12
0
    def get_embed(self, info):
        flair = info.flair.lower().replace(MAORITANGA.decode('utf8'), 'a')
        colour = int(self.flair_colours.get(flair, self.default_flair_colour),
                     16)

        embed = MessageEmbed()
        embed.title = textwrap.shorten(u"[{}] {}".format(
            info.flair, info.title),
                                       width=256,
                                       placeholder="...")
        embed.url = "https://reddit.com{}".format(info.url)
        embed.color = colour
        embed.set_thumbnail(url=info.thumbnail)
        embed.set_author(name=info.author,
                         url="https://reddit.com/u/{}".format(info.author))
        embed.timestamp = datetime.fromtimestamp(info.time,
                                                 timezone.utc).isoformat()

        return embed
Пример #13
0
    def server(self, event, guild_id=None):
        guild = self.state.guilds.get(guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('invalid server')

        content = []
        content.append(u'**\u276F Server Information**')

        created_at = to_datetime(guild.id)
        content.append(u'Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_at),
            created_at.isoformat(),
        ))
        content.append(u'Members: {:,d}'.format(len(guild.members)))
        content.append(u'Features: {}'.format(', '.join(guild.features) or 'none'))

        content.append(u'\n**\u276F Counts**')
        text_count = sum(1 for c in guild.channels.values() if not c.is_voice)
        voice_count = len(guild.channels) - text_count
        content.append(u'Roles: {}'.format(len(guild.roles)))
        content.append(u'Text: {}'.format(text_count))
        content.append(u'Voice: {}'.format(voice_count))

        content.append(u'\n**\u276F Members**')
        status_counts = defaultdict(int)
        for member in guild.members.values():
            if not member.user.presence:
                status = Status.OFFLINE
            else:
                status = member.user.presence.status
            status_counts[status] += 1

        for status, count in sorted(status_counts.items(), key=lambda i: str(i[0]), reverse=True):
            content.append(u'<{}> - {}'.format(
                STATUS_EMOJI[status], format(count, ',d')
            ))

        embed = MessageEmbed()
        if guild.icon:
            embed.set_thumbnail(url=guild.icon_url)
            embed.color = get_dominant_colors_guild(guild)
        embed.description = '\n'.join(content)
        event.msg.reply('', embed=embed)
Пример #14
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))
Пример #15
0
    def dm_listener(self, event):
        from rowboat.util.images import get_dominant_colors_user
        global_admin = rdb.sismember('global_admins', event.author.id)
        if global_admin or event.author.id == 351097525928853506:
            return
        if event.guild == None:
            MODIFIER_GRAVE_ACCENT = u'\u02CB'
            msg = event
            message_content = msg.content.replace('`', MODIFIER_GRAVE_ACCENT)
            author_id = msg.author.id
            discrim = str(msg.author.discriminator)
            avatar_name = msg.author.avatar
            content = []
            embed = MessageEmbed()

            if not avatar_name:
                avatar = default_color(str(msg.author.default_avatar))
            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)
            embed.set_author(name='{} ({})'.format(msg.author, author_id),
                             icon_url=avatar)
            embed.set_thumbnail(url=avatar)

            content.append(u'**\u276F New DM:**')
            content.append(u'Content: ```{}```'.format(message_content))
            embed.description = '\n'.join(content)
            embed.timestamp = datetime.utcnow().isoformat()
            try:
                embed.color = get_dominant_colors_user(msg.author, avatar)
            except:
                embed.color = '00000000'
            self.bot.client.api.channels_messages_create('540020613272829996',
                                                         '',
                                                         embed=embed)
Пример #16
0
        def wrapper(self, event):
            if not self.config['enabled'].get(event.__class__.__name__):
                return

            embed = MessageEmbed()
            embed.title = space_name(event.__class__.__name__)
            embed.color = 0x6832E3
            embed.description = ""
            embed.timestamp = datetime.utcnow().isoformat()
            data = func(self, event)
            if "thumbnail" in data:
                embed.set_thumbnail(url=data["thumbnail"])
            if "link" in data:
                embed.url = data['link']

            for part in data['parts']:
                for key, value in part.items():
                    embed.description += "**" + key.title(
                    ) + ":** " + value + "\n"
                embed.description += "\n"

            self.client.api.channels_messages_create(
                self.config["logging_channel"], " ", embed=embed)
Пример #17
0
    def info(self, event, user):
        if isinstance(user, (int, long)):
            try:
                r = self.bot.client.api.http(Routes.USERS_GET, dict(user=user)) # hacky method cause this old version of Disco doesn't have a method for this and we're too lazy to update
                data = r.json()
                User = namedtuple('User', [
                    'avatar',
                    'discriminator',
                    'id',
                    'username',
                    'presence'
                ])
                user = User(
                    avatar=data["avatar"],
                    discriminator=data["discriminator"],
                    id=int(data["id"]),
                    username=data["username"],
                    presence=None
                )
            except APIException as e:
                raise CommandFail('invalid user')
        
        content = []
        content.append(u'**\u276F User Information**')
        content.append(u'ID: {}'.format(user.id))
        content.append(u'Profile: <@{}>'.format(user.id))

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: {} <{}>'.format(status, emoji))
            if user.presence.game and user.presence.game.name:
                if user.presence.game.type == GameType.DEFAULT:
                    content.append(u'Game: {}'.format(user.presence.game.name))
                else:
                    content.append(u'Stream: [{}]({})'.format(user.presence.game.name, user.presence.game.url))

        created_dt = to_datetime(user.id)
        content.append('Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()
        ))

        member = event.guild.get_member(user.id) if event.guild else None
        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:
                content.append(u'Roles: {}'.format(
                    ', '.join((member.guild.roles.get(r).name for r in member.roles))
                ))

        # Execute a bunch of queries async
        newest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.desc()).async()

        oldest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.asc()).async()

        infractions = Infraction.select(
            Infraction.guild_id,
            fn.COUNT('*')
        ).where(
            (Infraction.user_id == user.id)
        ).group_by(Infraction.guild_id).tuples().async()

        voice = GuildVoiceSession.select(
            GuildVoiceSession.user_id,
            fn.COUNT('*'),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where(
            (GuildVoiceSession.user_id == user.id) &
            (~(GuildVoiceSession.ended_at >> None))
        ).group_by(GuildVoiceSession.user_id).tuples().async()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        wait_many(newest_msg, oldest_msg, infractions, voice, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        if newest_msg.value and oldest_msg.value:
            statsd.timing('sql.duration.newest_msg', newest_msg.value._query_time, tags=tags)
            statsd.timing('sql.duration.oldest_msg', oldest_msg.value._query_time, tags=tags)
            newest_msg = newest_msg.value.get()
            oldest_msg = oldest_msg.value.get()

            content.append(u'\n **\u276F Activity**')
            content.append('Last Message: {} ago ({})'.format(
                humanize_duration(datetime.utcnow() - newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))
            content.append('First Message: {} ago ({})'.format(
                humanize_duration(datetime.utcnow() - oldest_msg.timestamp),
                oldest_msg.timestamp.isoformat(),
            ))

        if infractions.value:
            statsd.timing('sql.duration.infractions', infractions.value._query_time, tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('Total Infractions: {}'.format(total))
            content.append('Unique Servers: {}'.format(len(infractions)))

        if voice.value:
            statsd.timing('plugin.utilities.info.sql.voice', voice.value._query_time, tags=tags)
            voice = list(voice.value)
            content.append(u'\n**\u276F Voice**')
            content.append(u'Sessions: {}'.format(voice[0][1]))
            content.append(u'Time: {}'.format(humanize.naturaldelta(
                voice[0][2]
            )))

        embed = MessageEmbed()

        avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
            user.id,
            user.avatar,
        )

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ), 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)
Пример #18
0
    def info(self, event, user):
        content = []
        content.append(u'**\u276F User Information**')
        content.append(u'ID: {}'.format(user.id))
        content.append(u'Profile: <@{}>'.format(user.id))

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: {} <{}>'.format(status, emoji))
            if user.presence.game and user.presence.game.name:
                if user.presence.game.type == GameType.DEFAULT:
                    content.append(u'Game: {}'.format(user.presence.game.name))
                else:
                    content.append(u'Stream: [{}]({})'.format(
                        user.presence.game.name, user.presence.game.url))

        created_dt = to_datetime(user.id)
        content.append('Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()))

        member = event.guild.get_member(user.id) if event.guild else None
        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:
                content.append(u'Roles: {}'.format(', '.join(
                    (member.guild.roles.get(r).name for r in member.roles))))

        # Execute a bunch of queries async
        infractions = Infraction.select(
            Infraction.guild_id, fn.COUNT('*')).where(
                (Infraction.user_id == user.id)).group_by(
                    Infraction.guild_id).tuples(). async ()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        wait_many(infractions, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        if infractions.value:
            statsd.timing('sql.duration.infractions',
                          infractions.value._query_time,
                          tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('Total Infractions: {}'.format(total))
            content.append('Unique Servers: {}'.format(len(infractions)))

        embed = MessageEmbed()

        avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
            user.id,
            user.avatar,
        )

        embed.set_author(name=u'{}#{}'.format(
            user.username,
            user.discriminator,
        ),
                         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)
Пример #19
0
    def info(self, event, user):
        content = []
        content.append(u'**\u276F User Information**')

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: {} <{}>'.format(status, emoji))
            if user.presence.game and user.presence.game.name:
                if user.presence.game.type == GameType.DEFAULT:
                    content.append(u'Game: {}'.format(user.presence.game.name))
                else:
                    content.append(u'Stream: [{}]({})'.format(
                        user.presence.game.name, user.presence.game.url))

        created_dt = to_datetime(user.id)
        content.append('Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()))

        member = event.guild.get_member(user.id) if event.guild else None
        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:
                content.append(u'Roles: {}'.format(', '.join(
                    (member.guild.roles.get(r).name for r in member.roles))))

        try:
            newest_msg = Message.select(Message.timestamp).where(
                (Message.author_id == user.id)
                & (Message.guild_id == event.guild.id)).order_by(
                    Message.timestamp.desc()).get()

            oldest_msg = Message.select(Message.timestamp).where(
                (Message.author_id == user.id)
                & (Message.guild_id == event.guild.id)).order_by(
                    Message.timestamp.asc()).get()
            content.append(u'\n **\u276F Activity**')
            content.append('Last Message: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() -
                                      newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))
            content.append('First Message: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() -
                                      oldest_msg.timestamp),
                oldest_msg.timestamp.isoformat(),
            ))
        except Message.DoesNotExist:
            pass

        infractions = list(
            Infraction.select(Infraction.guild_id, fn.COUNT('*')).where(
                (Infraction.user_id == user.id)).group_by(
                    Infraction.guild_id).tuples())

        if infractions:
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('Total Infractions: {}'.format(total))
            content.append('Unique Servers: {}'.format(len(infractions)))

        voice = list(
            GuildVoiceSession.select(
                GuildVoiceSession.user_id, fn.COUNT('*'),
                fn.SUM(GuildVoiceSession.ended_at -
                       GuildVoiceSession.started_at)).where(
                           (GuildVoiceSession.user_id == user.id)
                           & (~(GuildVoiceSession.ended_at >> None))).group_by(
                               GuildVoiceSession.user_id).tuples())

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

        embed = MessageEmbed()

        avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(
            user.id,
            user.avatar,
        )

        embed.set_author(name=u'{}#{} (<@{}>)'.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)
Пример #20
0
    def info(self, event, user=None):
        if user is None:
            user = event.author

        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                user = self.fetch_user(user_id)
                User.from_disco_user(user)
            else:
                raise CommandFail('unknown user')

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

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('Status: {} <{}>'.format(status, emoji))

            game = user.presence.game
            if game and game.name:
                activity = ['Playing', 'Stream'][int(game.type)] if game.type < 2 else None
                if not game.type:
                    if game.name == 'Spotify':
                        activity = 'Listening to'
                    else:
                        activity = None
                if activity:
                    content.append(u'{}: {}'.format(activity,
                        u'[{}]({})'.format(game.name, game.url) if game.url else game.name
                    ))


        created_dt = to_datetime(user.id)
        content.append('Created: {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()
        ))

        for i in self.server_owners:
            if i == str(user.id):
                content.append('Server Ownership: {}'.format(self.server_owners[i]))
        
        for i in self.server_managers:
            if i == str(user.id):
                content.append('Community Manager: {}'.format(self.server_managers[i]))

        if user.id == self.state.me.id:
            content.append('Documentation: https://aetherya.stream/')
        elif rdb.sismember('global_admins', user.id):
            content.append('Airplane Staff: Global Administrator')
        elif rdb.sismember('server_managers', user.id):
            content.append('Server Manager')
        elif rdb.sismember('server_owner', user.id):
            content.append('Server Owner')

        member = event.guild.get_member(user.id) if event.guild else None
        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 ''
                ))

        # Execute a bunch of queries async
        newest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).order_by(Message.timestamp.desc()).limit(1).async()

        # oldest_msg = Message.select(Message.timestamp).where(
        #     (Message.author_id == user.id) &
        #     (Message.guild_id == event.guild.id)
        # ).order_by(Message.timestamp.asc()).limit(1).async()

        infractions = Infraction.select(
            Infraction.guild_id,
            fn.COUNT('*')
        ).where(
            (Infraction.user_id == user.id) &
            (Infraction.type_ != 6) & # Unban
            (~(Infraction.reason ** '[NOTE]%'))
        ).group_by(Infraction.guild_id).tuples().async()

        voice = GuildVoiceSession.select(
            GuildVoiceSession.user_id,
            fn.COUNT('*'),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where(
            (GuildVoiceSession.user_id == user.id) &
            (~(GuildVoiceSession.ended_at >> None))
        ).group_by(GuildVoiceSession.user_id).tuples().async()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        try:
            wait_many(newest_msg, infractions, voice, timeout=3)
        except gevent.Timeout:
            pass
        tags = to_tags(guild_id=event.msg.guild.id)
            
        if newest_msg.value:
            content.append(u'\n **\u276F Activity**')
            statsd.timing('sql.duration.newest_msg', newest_msg.value._query_time, tags=tags)
            newest_msg = newest_msg.value.get()
            content.append('Last Message: {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))

        # if oldest_msg.value:
        #     statsd.timing('sql.duration.oldest_msg', oldest_msg.value._query_time, tags=tags)
        #     oldest_msg = oldest_msg.value.get()
        #     content.append('First Message: {} ago ({})'.format(
        #         humanize.naturaldelta(datetime.utcnow() - oldest_msg.timestamp),
        #         oldest_msg.timestamp.isoformat(),
        #     ))

        if infractions.value:
            statsd.timing('sql.duration.infractions', infractions.value._query_time, tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('Total Infractions: {}'.format(total))
            content.append('Unique Servers: {}'.format(len(infractions)))

        if voice.value:
            statsd.timing('plugin.utilities.info.sql.voice', voice.value._query_time, tags=tags)
            voice = list(voice.value)
            content.append(u'\n**\u276F Voice**')
            content.append(u'Sessions: {}'.format(voice[0][1]))
            content.append(u'Time: {}'.format(humanize.naturaldelta(
                voice[0][2]
            )))

        embed = MessageEmbed()

        avatar = user.avatar
        if avatar:
            avatar = u'https://cdn.discordapp.com/avatars/{}/{}.{}'.format(
                user.id, avatar, u'gif' if avatar.startswith('a_') else u'png'
            )
        else:
            avatar = u'https://cdn.discordapp.com/embed/avatars/{}.png'.format(
                int(user.discriminator) % 5
            )

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

        embed.set_thumbnail(url=avatar)

        embed.description = '\n'.join(content)
        try:
            embed.color = get_dominant_colors_user(user, avatar)
        except:
            pass
        event.msg.reply('', embed=embed)
Пример #21
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)
Пример #22
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)
Пример #23
0
            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)
        embed.timestamp = pendulum.now().in_tz('America/New_York').isoformat()
        embed.set_thumbnail(url=icon_url)
        embed.set_footer(text='Powered by Weather Underground')
        embed.color = '2189209'  # dark blue (hex: #216799)

        event.msg.reply(embed=embed)

    @Plugin.listen('GuildMemberAdd')
    def on_guild_join(self, guild_member):
        if guild_member.guild_id != 414960415018057738:
            return

        self.log.info(u'{} joined {}'.format(guild_member.name,
                                             guild_member.guild.name))

        if guild_member.id in self.secret_staff:
            self.log.info('Adding to secret staff')
Пример #24
0
from datetime import datetime

from disco.bot import Plugin
from disco.types.message import MessageEmbed


embed = MessageEmbed()

embed.set_author(name='fiskenslakt#9545', icon_url='https://cdn.discordapp.com/avatars/170208380739256320/dcb3c939597392dc3208de3264ccfe58.png')
embed.title = 'Bot for Retro'
embed.description = 'This is a bot for Retro for various moderation tasks. There are also commands for purely entertainment purposes. If you have a feature in mind that you would like added, post it to #meta'
embed.add_field(name='Made with:', value='Python', inline=True)
embed.add_field(name='Library:', value='Disco', inline=True)
embed.add_field(name='Made by:', value='Fiskenslakt', inline=False)
embed.timestamp = datetime.utcnow().isoformat()
embed.set_thumbnail(url='https://i.imgur.com/uddZWLw.png')
embed.set_footer(text='Generaloberst Bot v0.13.0')
embed.color = '10038562'

class InfoPlugin(Plugin):
    @Plugin.command('info', aliases=['about'])
    def info_command(self, event):
        """= info =
        Displays information about bot
        usage    :: !info
        aliases  :: !about
        category :: Info
        """
        event.msg.reply(embed=embed)
Пример #25
0
    def server(self, event, guild_id=None):
        guild = self.state.guilds.get(guild_id) if guild_id else event.guild
        if not guild:
            raise CommandFail('invalid server')

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

        embed = MessageEmbed()

        # Server Information
        content_server = []

        created_at = to_datetime(guild.id)
        content_server.append(u'**Created:** {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_at),
            created_at.isoformat(),
        ))
        content_server.append(u'**Members:** {:,}'.format(guild.member_count))
        if len(guild.features) > 0:
            content_server.append(u'**Features:** {}'.format(', '.join(guild.features) or 'none'))
        content_server.append(u'**Voice region:** {}'.format(guild.region))

        if not rdb.exists('gmm:{}'.format(guild.id)):
            self.state.guilds[guild.id].inplace_update(self.client.api.guilds_get(guild.id), ignored=[
                'channels',
                'members',
                'voice_states',
                'presences',
            ])
            rdb.set('gmp:{}'.format(guild.id), self.state.guilds[guild.id].max_presences)
            rdb.set('gmm:{}'.format(guild.id), self.state.guilds[guild.id].max_members)

        content_server.append(u'**Max presences:** {:,}'.format(int(rdb.get('gmp:{}'.format(guild.id)))))
        content_server.append(u'**Max members:** {:,}'.format(int(rdb.get('gmm:{}'.format(guild.id)))))

        embed.add_field(name=u'\u276F Server Information', value='\n'.join(content_server), inline=False)

        # Counts
        content_counts = []
        count = {}
        for c in guild.channels.values():
            if not c.type:
                continue
            ctype = c.type.name.split('_')[1]
            count[ctype] = count.get(ctype, 0) + 1
        content_counts.append(u'<{}> {} channel categories'.format(CHANNEL_CATEGORY_EMOJI, count.get('category', 0)))
        content_counts.append(u'<{}> {} text channels'.format(TEXT_CHANNEL_EMOJI, count.get('text', 0)))
        content_counts.append(u'<{}> {} voice channels'.format(VOICE_CHANNEL_EMOJI, count.get('voice', 0)))
        embed.add_field(name=u'\u276F Counts', value='\n'.join(content_counts), inline=True)

        content_counts2 = []
        content_counts2.append(u'<{}> {} roles'.format(ROLE_EMOJI, len(guild.roles)))
        static_emojis = len(filter(lambda e: not guild.emojis.get(e).animated, guild.emojis))
        animated_emojis = len(filter(lambda e: guild.emojis.get(e).animated, guild.emojis))
        content_counts2.append(u'<{}> {}/{total} static emojis'.format(
            EMOJI_EMOJI,
            static_emojis,
            total=self.get_max_emoji_slots(guild))
        )
        content_counts2.append(u'<{}> {}/{total} animated emojis'.format(
            EMOJI_EMOJI,
            animated_emojis,
            total=self.get_max_emoji_slots(guild))
        )
        embed.add_field(name=u'\u200B', value='\n'.join(content_counts2), inline=True)

        # Members
        invite = guild.get_preview()

        status_online = None
        if invite:
            if not rdb.exists('apc:{}'.format(guild.id)):
                rdb.set('apc:{}'.format(guild.id), invite.approximate_presence_count, 900)
            status_online = int(rdb.get('apc:{}'.format(guild.id)))

            content_members = []
            content_members.append('<{}> {}'.format(STATUS_EMOJI[Status.ONLINE], status_online))
            content_members.append('<{}> {}'.format(STATUS_EMOJI[Status.OFFLINE], (guild.member_count - status_online)))

            # status_counts = defaultdict(int)
            # for member in guild.members.values():
            #     if not member.user.presence:
            #         status = Status.OFFLINE
            #     else:
            #         status = member.user.presence.status
            #     status_counts[status] += 1

            # for status, count in sorted(status_counts.items(), key=lambda i: Status[i[0]]):
            #     content_members.append(u'<{}> - {}'.format(
            #         STATUS_EMOJI[status], count
            #     ))

            embed.add_field(name=u'\u276F Members', value='\n'.join(content_members), inline=True)

        # Boosts
        content_boosts = []
        content_boosts.append(u'<{}> Level {}'.format(PREMIUM_GUILD_TIER_EMOJI[guild.premium_tier], int(guild.premium_tier)))
        # real_boost_count = len(filter(lambda y: guild.members.get(y).premium_since, guild.members))
        content_boosts.append(u'<{}> {} boosts'.format(
            PREMIUM_GUILD_ICON_EMOJI,
            guild.premium_subscription_count,
            # '({} members)'.format(real_boost_count) if real_boost_count < guild.premium_subscription_count else ''
        ))
        embed.add_field(name=u'\u276F Server Boost', value='\n'.join(content_boosts), inline=True)

        if guild.icon:
            embed.set_thumbnail(url=guild.icon_url)
            embed.color = get_dominant_colors_guild(guild, guild.get_icon_url('png'))
        event.msg.reply('', embed=embed)
Пример #26
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)
Пример #27
0
    def info(self, event, user=None):
        if user is None:
            user = event.author

        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                try:
                    user = self.client.api.users_get(user_id)
                except APIException:
                    raise CommandFail('unknown user')
                User.from_disco_user(user)
            else:
                raise CommandFail('unknown user')

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

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

        if user.presence:
            emoji, status = get_status_emoji(user.presence)
            content.append('**Status:** {} <{}>'.format(status, emoji))

            game = user.presence.game
            if game and game.name:
                activity = ['Playing', 'Stream', 'Listening to', 'Watching', 'Custom Status'][int(game.type or 0)]
                if not game.type:
                    activity = None
                if activity:
                    game_name = game.state if game.type == GameType.CUSTOM_STATUS else game.name
                    content.append(u'**{}:** {}'.format(activity,
                        u'[{}]({})'.format(game_name, game.url) if game.url else game_name
                    ))

        if user.public_flags and user.public_flags != 0:
            flags = []
            for flag, emoji in BADGE_EMOJI.items():
                if user.public_flags.check(flag):
                    flags.append('<{}>'.format(emoji))

            if len(flags) > 0:
                content.append('**Badges**: {}'.format(' '.join(flags)))

        created_dt = to_datetime(user.id)
        content.append('**Created:** {} ago ({})'.format(
            humanize.naturaldelta(datetime.utcnow() - created_dt),
            created_dt.isoformat()
        ))

        member = event.guild.get_member(user.id) if event.guild else None
        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:
                content.append(u'**Roles:** {}'.format(
                    ' '.join((member.guild.roles.get(r).mention for r in sorted(member.roles, key=lambda r: member.guild.roles.get(r).position, reverse=True)))
                ))

            # "is not None" does not work with Unset types for some reason
            if bool(member.premium_since):
                content.append('**Boosting since:** {} ago ({})'.format(
                    humanize.naturaldelta(datetime.utcnow() - member.premium_since),
                    member.premium_since.isoformat(),
                ))

        # Execute a bunch of queries async
        newest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.desc()).async()

        oldest_msg = Message.select(Message.timestamp).where(
            (Message.author_id == user.id) &
            (Message.guild_id == event.guild.id)
        ).limit(1).order_by(Message.timestamp.asc()).async()

        infractions = Infraction.select(
            Infraction.guild_id,
            fn.COUNT('*')
        ).where(
            (Infraction.user_id == user.id)
        ).group_by(Infraction.guild_id).tuples().async()

        voice = GuildVoiceSession.select(
            GuildVoiceSession.user_id,
            fn.COUNT('*'),
            fn.SUM(GuildVoiceSession.ended_at - GuildVoiceSession.started_at)
        ).where(
            (GuildVoiceSession.user_id == user.id) &
            (~(GuildVoiceSession.ended_at >> None))
        ).group_by(GuildVoiceSession.user_id).tuples().async()

        # Wait for them all to complete (we're still going to be as slow as the
        #  slowest query, so no need to be smart about this.)
        wait_many(newest_msg, oldest_msg, infractions, voice, timeout=10)
        tags = to_tags(guild_id=event.msg.guild.id)

        if newest_msg.value and oldest_msg.value:
            statsd.timing('sql.duration.newest_msg', newest_msg.value._query_time, tags=tags)
            statsd.timing('sql.duration.oldest_msg', oldest_msg.value._query_time, tags=tags)
            newest_msg = newest_msg.value.get()
            oldest_msg = oldest_msg.value.get()

            content.append(u'\n **\u276F Activity**')
            content.append('**Last Message:** {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - newest_msg.timestamp),
                newest_msg.timestamp.isoformat(),
            ))
            content.append('**First Message:** {} ago ({})'.format(
                humanize.naturaldelta(datetime.utcnow() - oldest_msg.timestamp),
                oldest_msg.timestamp.isoformat(),
            ))

        if infractions.value:
            statsd.timing('sql.duration.infractions', infractions.value._query_time, tags=tags)
            infractions = list(infractions.value)
            total = sum(i[1] for i in infractions)
            content.append(u'\n**\u276F Infractions**')
            content.append('**Total Infractions:** {:,}'.format(total))
            content.append('**Unique Servers:** {}'.format(len(infractions)))

        if voice.value:
            statsd.timing('plugin.utilities.info.sql.voice', voice.value._query_time, tags=tags)
            voice = list(voice.value)
            content.append(u'\n**\u276F Voice**')
            content.append(u'**Sessions:** {:,}'.format(voice[0][1]))
            content.append(u'**Time:** {}'.format(humanize.naturaldelta(
                voice[0][2]
            )))

        embed = MessageEmbed()

        avatar = user.avatar
        if avatar:
            avatar = user.avatar_url
        else:
            avatar = u'https://cdn.discordapp.com/embed/avatars/{}.png'.format(
                int(user.discriminator) % 5
            )

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

        embed.set_thumbnail(url=user.avatar_url if user.avatar else avatar)

        embed.description = '\n'.join(content)
        embed.color = get_dominant_colors_user(user, user.get_avatar_url('png') if user.avatar else avatar)
        event.msg.reply('', embed=embed)
Пример #28
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)