Esempio n. 1
0
    async def command_stats(self, ctx, *, command: str = None):
        """Shows commands statistics."""

        if command:
            async with self.bot.pgpool.acquire() as conn:
                record = await get_statistics(conn, command)
            if not record:
                return await ctx.send(
                    'There are no statistics for that command.')
            embed = discord.Embed(title=f'Statistics for `{command}`')
            embed.add_field(
                name='Times used', value=utils.commas(record['times_used']))
            embed.add_field(
                name='Last used', value=utils.ago(record['last_used']))
            return await ctx.send(embed=embed)

        select = 'SELECT * FROM command_statistics ORDER BY times_used DESC LIMIT 5'
        async with self.bot.pgpool.acquire() as conn:
            records = await conn.fetch(select)

        medals = [':first_place:', ':second_place:', ':third_place:']
        embed = discord.Embed(title='Most used commands')
        async with self.bot.pgpool.acquire() as conn:
            lu = utils.ago(await last_used(conn))
        embed.set_footer(text=f'Last command usage was {lu}')

        for index, record in enumerate(records):
            medal = medals[index] if index < 3 else ''
            td = utils.ago(record['last_used'])
            used = 'Used {} time(s) (last used {})'.format(
                utils.commas(record['times_used']), td)
            embed.add_field(
                name=medal + record['command_name'], value=used, inline=False)

        await ctx.send(embed=embed)
Esempio n. 2
0
def make_urban_embed(d: UrbanDefinition) -> discord.Embed:
    """ Makes a ``discord.Embed`` from an ``UrbanDefinition``. """
    embed = discord.Embed(title=d.word, description=utils.truncate(d.definition, 2048))
    if d.example:
        embed.add_field(name='Example', value=utils.truncate(d.example, 1024), inline=False)
    embed.add_field(name='\N{THUMBS UP SIGN}', value=utils.commas(d.thumbs_up))
    embed.add_field(name='\N{THUMBS DOWN SIGN}', value=utils.commas(d.thumbs_down))
    return embed
Esempio n. 3
0
    def guild_fields(self, g):
        """ Returns a list of fields to be passed into ``monitor_send`` from a guild. """
        ratio = botcollection.user_to_bot_ratio(g)
        humans = utils.commas(sum(1 for u in g.members if not u.bot))
        bots = utils.commas(sum(1 for u in g.members if u.bot))

        return [
            ('Guild', f'{g.name}\n`{g.id}`'),
            ('Owner', f'{g.owner.mention} {g.owner}\n`{g.owner.id}`'),
            ('Info', f'Created {utils.ago(g.created_at)}'),
            ('Members', f'Members: {len(g.members)} (UTBR: {ratio})\n{humans} human(s), {bots} bot(s)')
        ]
Esempio n. 4
0
 def embed(self) -> Embed:
     """Makes a :class:``discord.Embed`` from an ``UrbanDefinition``."""
     embed = Embed(title=self.word,
                   description=utils.truncate(self.definition, 2048))
     if self.example:
         embed.add_field(name='Example',
                         value=utils.truncate(self.example, 1024),
                         inline=False)
     embed.add_field(name='\N{THUMBS UP SIGN}',
                     value=utils.commas(self.thumbs_up))
     embed.add_field(name='\N{THUMBS DOWN SIGN}',
                     value=utils.commas(self.thumbs_down))
     return embed
Esempio n. 5
0
    async def stats(self, ctx):
        """ Shows participation info about the bot. """
        num_members = len(list(self.bot.get_all_members()))
        num_channels = len(list(self.bot.get_all_channels()))
        num_servers = len(self.bot.guilds)
        uptime = str(datetime.datetime.utcnow() - self.bot.boot_time)[:-7]

        embed = discord.Embed(title='Statistics')
        fields = {
            'Members': utils.commas(num_members),
            'Channels': utils.commas(num_channels),
            'Servers': utils.commas(num_servers),
            'Uptime': uptime,
            'Shards': utils.commas(len(self.bot.shards)),
        }
        for name, value in fields.items():
            embed.add_field(name=name, value=value)
        await ctx.send(embed=embed)
Esempio n. 6
0
    async def mute(self, ctx, member: discord.Member, time: HumanTime):
        """
        Mutes someone for a certain amount of time.

        The "Muted" role must exist on the server in order for this to work.
        The bot can setup the "Muted" role and channel overrides for you
        with the d?mute_setup command.

        d?mute <someone> 5m
            Mutes someone for 5 minutes.
        d?mute <someone> 2h5m
            Mutes someone for 2 hours and 5 minutes.
        d?mute <someone> 5s
            Mutes someone for 5 seconds.
        """
        mute_role = discord.utils.get(ctx.guild.roles, name='Muted')

        if not mute_role:
            await ctx.send('\N{CROSS MARK} I can\'t find the "Muted" role.')
            return

        mute = '\N{SPEAKER WITH CANCELLATION STROKE}'
        sec = utils.commas(time.seconds)
        msg = await ctx.send(
            f'{mute} Muting {member.name}#{member.discriminator}'
            f' (`{member.id}`) for {time.raw} ({sec} seconds).')

        try:
            await member.add_roles(mute_role)
        except discord.Forbidden:
            await msg.edit(content='\N{CROSS MARK} I can\'t do that!'
                           ' I might be too low on the role hierarchy,'
                           ' or I need permissions.'
                           ' Ensure that the my bot role is placed above'
                           ' the "Muted" role.')
            return
        except:
            await msg.edit(content='\N{CROSS MARK} I failed to do that.')
            return

        async def unmute_task():
            await asyncio.sleep(time.seconds)
            await member.remove_roles(mute_role)
            if await self.bot.config_is_set(ctx.guild, 'unmute_announce'):
                await ctx.send(
                    f'\N{SPEAKER} {member.name}#{member.discriminator}'
                    f' (`{member.id}`) has been unmuted.')

        task = self.bot.loop.create_task(unmute_task())
        self.mute_tasks[member] = task

        embed = self._make_action_embed(ctx.author,
                                        member,
                                        title=f'{mute} Member muted')
        embed.add_field(name='Duration', value=f'{time.raw} ({time.seconds}s)')
        await self.bot.send_modlog(ctx.guild, embed=embed)
Esempio n. 7
0
    async def dstats(self, ctx):
        """ Shows detailed stats. """
        desc = """{0} (`{1}`, <@{1}>)\nCreated: {2}""".format(
            ctx.bot.user, ctx.bot.user.id, ctx.bot.user.created_at)
        embed = discord.Embed(title='Detailed stats',
                              description=desc,
                              color=discord.Color.blurple())

        # ram
        process = psutil.Process(os.getpid())
        mem = process.memory_info()
        vmem = psutil.virtual_memory()
        total = round(vmem.total / 10**9, 3)
        avail = round(vmem.available / 10**9, 3)
        mem_gb = round(mem.rss / 10**9, 2)
        mem_mb = round(mem.rss / 10**6, 2)
        ttl = f'Using {round(mem_gb / total * 100, 2)}% of total RAM'
        embed.add_field(
            name='RAM',
            value=
            f'{avail} GB/{total} GB total\n{mem_mb} MB, {mem_gb} GB\n{ttl}')

        # owner
        owner = (await ctx.bot.application_info()).owner
        embed.add_field(name='Owner', value=f'{owner.id}\n<@{owner.id}>')

        # guilds
        embed.add_field(name='Guilds',
                        value=f'{utils.commas(len(ctx.bot.guilds))} total')

        # voice
        clients = ctx.bot.voice_clients
        embed.add_field(name='Voice', value=f'{len(clients)} voice client(s)')

        async with ctx.acquire() as conn:
            record = await conn.fetchrow(
                'SELECT SUM(times_used) FROM command_statistics')
            embed.add_field(name='Commands Ran',
                            value=utils.commas(record['sum']) + ' total')

        await ctx.send(embed=embed)
Esempio n. 8
0
 def cm(v):
     return utils.commas(v)
Esempio n. 9
0
    async def roles(self, ctx):
        """
        Views detailed information about the roles in this server.

        Information is presented in a table-like layout.

        Columns:
            - Role position
                The role's position in the hierarchy. The bottom role is #0.
            - Role name
            - Role color
            - Role ID
            - Role properties
            - Role members

        Role properties:
            Role properties are represented as a sequence of characters.
            Each character has a separate meaning.

            H: This role is hoisted.
            M: This role is managed.
            @: This role is mentionable by everyone.
            D: This role is the default role (@everyone).
            A: This role has the "Administrator" permission.
            E: This role has the "Mention Everyone" permission.
        """
        paginator = commands.Paginator()

        sorted_roles = sorted(
            ctx.guild.roles, key=lambda r: r.position, reverse=True)
        longest_role_name = max(map(lambda r: len(r.name), ctx.guild.roles))

        # add lines
        for role in sorted_roles:
            # compile a list of role properties
            attrs = {
                # role attributes
                'H': role.hoist,
                'M': role.managed,
                '@': role.mentionable,
                'D': role.is_default(),

                # role permissions
                'A': role.permissions.administrator,
                'E': role.permissions.mention_everyone
            }
            properties = ''.join(rep for rep, val in attrs.items() if val)

            # how many members?
            members = utils.commas(len(role.members))

            # get color
            color = 'default' if role.color == discord.Color.default(
            ) else str(role.color)

            fmt = (
                f'{role.position: <2} {role.name: <{longest_role_name}} {color} {role.id: <18} '
                f'{properties: <{len(attrs)}} {members: <4}')
            paginator.add_line(fmt)

        for page in paginator.pages:
            await ctx.send(page)