示例#1
0
文件: dimond.py 项目: Itamai/DimBot
 async def server(self, ctx: commands.Context, s: discord.Guild = None):
     """Shows info of a server"""
     if not s:
         if ctx.guild:
             s = ctx.guild
         else:
             await ctx.reply(
                 'You must specify a server if you are sending this command in PM!'
             )
             return
     emb = missile.Embed(s.name)
     if s.description:
         emb.description = s.description
     emb.add_field(name='❄ ID', value=s.id)
     emb.add_field(name='Owner ID', value=s.owner_id)
     emb.add_field(name='Created at', value=s.created_at)
     emb.add_field(name='Member count', value=s.member_count)
     emb.add_field(name='Region', value=s.region)
     if s.features:  # https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features
         emb.add_field(name='Features', value=',\n'.join(s.features))
     emb.add_field(name='Max members', value=s.max_members)
     emb.add_field(name='Max presences', value=s.max_presences)
     if s.me.guild_permissions.manage_webhooks:
         emb.add_field(name='Webhooks', value=len(await s.webhooks()))
     if s.me.guild_permissions.manage_guild:
         emb.add_field(name='Integrations',
                       value=len(await s.integrations()))
         emb.add_field(name='Invites', value=len(await s.invites()))
     emb.set_thumbnail(url=s.icon_url)
     await ctx.reply(embed=emb)
示例#2
0
async def botinfo(ctx):
    """Displays bot info"""
    from platform import python_version
    embed = missile.Embed(sponsor_txt)
    embed.add_field('Guild count', str(len(bot.guilds)))
    embed.add_field('Uptime', datetime.now() - bot.boot_time)
    embed.add_field('Python', python_version())
    embed.add_field('Discord.py', discord.__version__)
    embed.add_field('Codename', 'みずはら')
    embed.add_field('Devblog',
                    '[Instagram](https://www.instagram.com/techdim)')
    embed.add_field('Source code',
                    '[GitHub](https://github.com/TCLRainbow/DimBot)')
    embed.add_field('Discord server', '[6PjhjCD](https://discord.gg/6PjhjCD)')
    process = psutil.Process()
    with process.oneshot():
        embed.add_field('CPU usage %', psutil.cpu_percent(percpu=True))
        embed.add_field(
            'Process RAM usage / available (MiB)',
            f'{process.memory_info()[0] / 1024 ** 2:.1f} / {psutil.virtual_memory().available / 1024 ** 2:.1f}'
        )
    emoji = choice(
        tuple(e for e in bot.get_cog('Hamilton').guild.emojis
              if e.name.startswith('sayu')))
    embed.set_footer(text='Mood: ' + emoji.name[4:])
    embed.set_author(
        name='Click here to let me join your server! [Open Beta]',
        url=
        'https://discord.com/api/oauth2/authorize?client_id=574617418924687419&permissions=8&scope=bot'
    )
    embed.set_image(url=emoji.url)
    await ctx.send(embed=embed)
示例#3
0
async def ainvk(ctx: commands.Context):
    if ctx.command.qualified_name.startswith('arccore'):
        return
    emb = missile.Embed(description=ctx.message.content)
    emb.add_field('By', ctx.author.mention)
    emb.add_field('In', ctx.guild.id if ctx.guild else 'DM')
    await bot.get_cog('Hamilton').bot_test.send(embed=emb)
示例#4
0
文件: dimond.py 项目: Itamai/DimBot
 async def user(self, ctx, u: discord.User = None):
     """Shows user info"""
     # https://discordpy.readthedocs.io/en/latest/api.html#discord.User
     u = u if u else ctx.author
     desc = f"Send `{self.bot.default_prefix}info f [user]` for flag details,\n`{self.bot.default_prefix}info p " \
            "[user|channel] [channel]` for permission details"
     emb = missile.Embed(str(u), desc, thumbnail=u.avatar_url)
     if u.avatar:
         emb.set_footer(text='Avatar hash: ' + u.avatar)
     emb.add_field(name='❄ ID', value=u.id)
     emb.add_field(name='Is bot?', value=u.bot)
     emb.add_field(name='Public flags', value=u.public_flags.value)
     emb.add_field(name='Created at', value=u.created_at)
     member: Optional[discord.Member] = None
     # A hacky way to try getting data that can only be accessed as a Member
     for g in self.bot.guilds:
         m = g.get_member(u.id)
         if m:
             member = m
             if m.voice:  # Searches whether the 'member' is in a VC
                 break  # A user can only be in 1 VC
     # TODO: Use user.mutual_guilds to check status&activities instead when d.py 1.7 is released
     if member:  # Data that can only be accessed as a Member
         emb.add_field(name='Number of activities',
                       value=str(len(member.activities))
                       if member.activities else '0')
         stat = str(member.status)
         if member.desktop_status != discord.Status.offline:
             stat += ' 💻'
         if member.mobile_status != discord.Status.offline:
             stat += ' 📱'
         if member.web_status != discord.Status.offline:
             stat += ' 🌐'
         emb.add_field(name='Status', value=stat)
         if member.voice:
             v_state = str(member.voice.channel.id)
             if member.voice.self_mute:
                 v_state += ' **Muted**'
             if member.voice.self_deaf:
                 v_state += ' **Deaf**'
             if member.voice.self_stream:
                 v_state += ' **Streaming**'
             emb.add_field(name='Voice channel ❄ ID', value=v_state)
     # Guild specific data
     if ctx.guild:
         member = ctx.guild.get_member(u.id)
         if member:
             emb.add_field(name='Joined at', value=member.joined_at)
             emb.add_field(name='Pending member?', value=member.pending)
             emb.add_field(name='Nitro boosting server since',
                           value=member.premium_since)
             if len(member.roles) > 1:
                 emb.add_field(name='Roles',
                               value=' '.join([
                                   role.mention for role in member.roles[1:]
                               ][::-1]))
             emb.colour = member.color
     emb.set_author(name=member.display_name if member else u.name,
                    icon_url=u.default_avatar_url)
     await ctx.reply(embed=emb)
示例#5
0
文件: dimond.py 项目: Itamai/DimBot
 async def vc(self, ctx: commands.Context, ch: discord.VoiceChannel):
     """Shows info of a voice channel. PM the command if the channel is not in that server."""
     emb = missile.Embed(ch.name)
     if not ctx.guild:
         emb.add_field(name='Server ❄ID', value=ch.guild.id)
     emb.add_field(name='Bit rate (kbps)', value=ch.bitrate // 1000)
     emb.add_field(name='Created at', value=ch.created_at)
     await ctx.reply(embed=emb)
示例#6
0
文件: DimBot.py 项目: Itamai/DimBot
async def colour(ctx: commands.Context, c: discord.Colour = None):
    if not c:
        c = discord.Colour.random()
    value = f'{c.value:X}'
    emb = missile.Embed(f'#{value.zfill(6)}', color=c)
    emb.add_field('R', c.r)
    emb.add_field('G', c.g)
    emb.add_field('B', c.b)
    await ctx.reply(embed=emb)
示例#7
0
    async def rss_process(self, rowid, row):
        """The main algorithm for RSS feed detector"""
        self.logger.info(f"RSS {rowid}: Checking RSS...")
        async with self.bot.session.get(
                row[0]) as response:  # Sends a GET request to the URL
            self.logger.debug(f"RSS {rowid}: Fetching response...")
            text = await response.text()
        self.logger.debug(f"RSS {rowid}: Parsing response...")
        feed = feedparser.parse(text).entries[
            0]  # Converts RSS response to library objects and read the first entry
        if feed.published_parsed:
            pubtime = mktime(
                feed.published_parsed
            )  # Converts the feed's publish timestamp to an integer
        else:
            pubtime = 0  # Some endpoints have no publish time, wtf

        # A feed with a new title and the publish timestamp is newer than database's record
        if row[1] != feed.title and (pubtime > row[2] or pubtime == 0):
            self.logger.info(
                f'RSS {rowid}: Detected news: {feed.title}  Old: {row[1]}')
            if 'description' in feed:
                content = BeautifulSoup(
                    feed.description, 'html.parser'
                )  # HTML Parser for extracting RSS feed content
                # Limits the content size to prevent spam
                description = content.get_text()
                if len(description) > 500:
                    description = description[:497] + '...'
            else:
                description = ''  # Some feeds have no descriptions
            # Fetch channels that subscribed to this RSS URL
            async with self.bot.sql.get_rss_subscriptions_cursor(
                    self.bot.db, url=row[0]) as rss_subs:
                # Constructs base Embed object
                self.logger.debug(f"RSS {rowid}: Begin reading RssSub")
                emb = missile.Embed(feed.title, description, url=feed.link)
                async for rss_sub in rss_subs:
                    local_emb = emb.copy()
                    if rss_sub[2]:
                        local_emb.url = self.bot.ip + 'b64d?s=' + missile.encode(
                            emb.url)
                    channel = self.bot.get_channel(rss_sub[0])
                    self.logger.debug(f"RSS {rowid}: RssSub channel {channel}")
                    local_emb.set_footer(
                        text=f"{rss_sub[1]} | {feed.published}"
                    )  # Adds channel-specific footer
                    self.bot.loop.create_task(channel.send(embed=local_emb))
            self.logger.info(f"RSS {rowid}: Dispatched Discord message tasks")
            # Updates the database with the new feed
            await self.bot.sql.update_rss_data(self.bot.db,
                                               title=feed.title,
                                               time=pubtime,
                                               id=rowid)
            self.logger.debug(f"RSS {rowid}: Updated DB")
        self.logger.info(f"RSS {rowid}: Done")
示例#8
0
文件: dimond.py 项目: Itamai/DimBot
 async def webhook(self, ctx: commands.Context, name):
     """Shows info of a webhook"""
     for webhook in await ctx.guild.webhooks():
         if webhook.name == name:
             emb = missile.Embed(f'❄ ID: {webhook.id}')
             emb.add_field(name='Created at', value=webhook.created_at)
             emb.add_field(name='Channel', value=webhook.channel.mention)
             emb.add_field(name='Type', value=webhook.type)
             await ctx.reply(embed=emb)
             return
     await ctx.reply(f"Webhook user '{name}' not found.")
示例#9
0
文件: dimond.py 项目: Itamai/DimBot
 async def server_invite(self, ctx: commands.Context):
     """Lists invite codes of a server"""
     emb = missile.Embed(description='')
     for inv in await ctx.guild.invites():
         to_be_added = f"[{inv.code}]({inv.url}) "
         if len(emb.description + to_be_added) < 2045:
             emb.description += to_be_added
         else:
             emb.title = 'So many invites lmfao'
             emb.description += '...'
             break
     await ctx.reply(embed=emb)
示例#10
0
文件: DimBot.py 项目: Itamai/DimBot
async def on_message_delete(msg: discord.Message):
    """Event handler when a message has been deleted"""
    if msg.author == msg.guild.me or msg.content.startswith(
            await missile.prefix_process(bot, msg)):
        return
    # Stores the deleted message for snipe command
    content = msg.content if msg.content else msg.embeds[0].title
    bot.snipe = missile.Embed(
        msg.author.display_name, content,
        msg.embeds[0].colour if msg.embeds else discord.Colour.random(),
        msg.guild.icon_url)
    bot.snipe.set_author(name=msg.guild.name, icon_url=msg.author.avatar_url)
示例#11
0
 async def get_embed(self):
     emb = missile.Embed(
         f'WhoPing record ({self.index + 1}/{len(self.pings)})',
         self.pings[self.index][2])
     user = await self.ctx.bot.ensure_user(self.pings[self.index][1])
     emb.add_field('Pinged by', user.mention)
     emb.add_field('Time', self.pings[self.index][3][5:-7])
     if not self.in_guild:
         emb.add_field('Server',
                       self.ctx.bot.get_guild(self.pings[self.index][4]))
     emb.set_footer(text=self.pings[self.index][0])
     return emb
示例#12
0
async def colour(ctx: commands.Context, c: discord.Colour = None):
    """`colour [c]`
    `c` can be an integer, a 6-digit hexadecimal number (optionally with a # prepending it),
    or even `rgb(<r>, <g>, <b>)` which is a CSS representation. If `c` is not supplied,
    randomly generates a HSV color with max saturation.
    """
    if not c:
        c = discord.Colour.random()
    value = f'{c.value:X}'
    emb = missile.Embed(f'#{value.zfill(6)}', color=c)
    emb.add_field('R', c.r)
    emb.add_field('G', c.g)
    emb.add_field('B', c.b)
    await ctx.reply(embed=emb)
示例#13
0
文件: DimBot.py 项目: Itamai/DimBot
async def botinfo(ctx):
    """Displays bot information"""
    from platform import python_version
    embed = missile.Embed(sponsor_txt)
    embed.add_field('Guild count', len(bot.guilds))
    embed.add_field('Uptime', datetime.now() - bot.boot_time)
    embed.add_field('Python', python_version())
    embed.add_field('Discord.py', discord.__version__)
    embed.add_field('Codename', '뾆')
    embed.add_field('Devblog',
                    '[Instagram](https://www.instagram.com/techdim)')
    embed.add_field('Source code',
                    '[GitHub](https://github.com/TCLRainbow/DimBot)')
    embed.add_field('Discord server', '[6PjhjCD](https://discord.gg/6PjhjCD)')
    await ctx.send(embed=embed)
示例#14
0
文件: dimond.py 项目: Itamai/DimBot
 async def emoji(self, ctx: commands.Context,
                 e: Union[discord.Emoji, discord.PartialEmoji]):
     """Shows info of a custom(non-Unicode) emoji"""
     emb = missile.Embed(e.name)
     # noinspection PyTypeChecker
     emb.set_author(name=e)
     emb.set_thumbnail(url=e.url)
     emb.add_field(name='❄ ID', value=e.id)
     emb.add_field(name='Created at', value=e.created_at)
     if isinstance(e, discord.Emoji):
         emb.add_field(name='Server ID', value=e.guild_id)
         if e.user:
             emb.add_field(name='Creator', value=e.user)
         if e.roles:
             emb.add_field(name='Usable roles',
                           value=''.join(r.mention for r in e.roles))
     await ctx.reply(embed=emb)
示例#15
0
文件: raceline.py 项目: Itamai/DimBot
    async def rss_process(self, rowid, row):
        """The main algorithm for RSS feed detector"""
        cursor = self.bot.get_cursor(
        )  # Each thread requires an instance of cursor
        self.logger.info(f"{rowid}: Checking RSS...")
        async with self.bot.session.get(
                row['url']) as response:  # Sends a GET request to the URL
            self.logger.debug(f"{rowid}: Fetching response...")
            text = await response.text()
        self.logger.debug(f"{rowid}: Parsing response...")
        feed = feedparser.parse(text).entries[
            0]  # Converts RSS response to library objects and read the first entry
        pubtime = mktime(
            feed.published_parsed
        )  # Converts the feed's publish timestamp to an integer

        # A feed with a new title and the publish timestamp is newer than database's record
        if row['newstitle'] != feed.title and pubtime > row['time']:
            self.logger.info(
                f'{rowid}: Detected news: {feed.title}  Old: {row["newstitle"]}'
            )
            content = BeautifulSoup(
                feed.description,
                'html.parser')  # HTML Parser for extracting RSS feed content
            rss_sub = cursor.execute(
                'SELECT rssChID, footer FROM RssSub WHERE url = ?',
                (row['url'], )).fetchall(
                )  # Fetch channels that subscribed to this RSS URL
            # Limits the content size to prevent spam
            description = (content.get_text()[:497] + '...') if len(
                content.get_text()) > 500 else content.get_text()
            # Constructs base Embed object
            emb = missile.Embed(feed.title, description, url=feed.link)
            for row in rss_sub:
                local_emb = emb.copy()
                channel = self.bot.get_channel(row['rssChID'])
                local_emb.set_footer(text=f"{row['footer']} | {feed.published}"
                                     )  # Adds channel-specific footer
                self.bot.loop.create_task(channel.send(embed=local_emb))
            self.logger.info(f"{rowid}: Sent Discord")
            cursor.execute(
                'UPDATE RssData SET newstitle = ?, time = ? WHERE ROWID = ?',
                (feed.title, pubtime,
                 rowid))  # Updates the database with the new feed
        self.logger.info(f"{rowid}: Done")
示例#16
0
 async def webhook(self,
                   ctx: commands.Context,
                   name,
                   channel: discord.TextChannel = None):
     """`info webhook <name> [channel]`
     name: The webhook's name
     In some cases you will encounter duplicate webhook names in different channels.
     Specify `channel` to filter it."""
     for webhook in await ctx.guild.webhooks():
         if webhook.name == name and (channel is None
                                      or webhook.channel == channel):
             emb = missile.Embed(f'❄ ID: {webhook.id}')
             emb.add_field(name='Created at', value=webhook.created_at)
             emb.add_field(name='Channel', value=webhook.channel.mention)
             emb.add_field(name='Type', value=webhook.type)
             await ctx.reply(embed=emb)
             return
     await ctx.reply(f"Webhook user '{name}' not found.")
示例#17
0
文件: dimond.py 项目: Itamai/DimBot
 async def invite(self, ctx: commands.Context, inv: discord.Invite):
     """Shows info of an invite."""
     emb = missile.Embed(inv.code, url=inv.url)
     emb.add_field(name='Server ID', value=inv.guild.id)
     emb.add_field(name='Channel', value=inv.channel.mention)
     if inv.guild in self.bot.guilds and inv.guild.me.guild_permissions.manage_guild:
         for i in await inv.guild.invites():
             if i.code == inv.code:
                 emb.add_field(name='Uses', value=i.uses)
                 emb.add_field(name='Created at', value=i.created_at)
                 if inv.inviter:
                     emb.add_field(name='Inviter', value=i.inviter.mention)
                 emb.add_field(name='Expires in', value=i.max_age)
                 emb.add_field(name='Max uses', value=i.max_uses)
                 emb.add_field(name='Revoked', value=i.revoked)
                 emb.add_field(name='Only grants temporary membership',
                               value=i.temporary)
     await ctx.reply(embed=emb)
示例#18
0
 async def swordfight(self, ctx: Context, user: discord.User = None):
     """pp swordfight [user]
     user: Your opponent. If you didn't specify a user as your opponent,
     bot randomly picks a user that has a pp registered, **INCLUDING YOURSELF**"""
     if not user:
         user = self.bot.get_user(random.choice(list(self.organs.keys())))
     my = self.get_pp(ctx, ctx.author.id).check_lock(True)
     his = self.get_pp(ctx, user.id).check_lock(ctx.author == user)
     content = ''
     if my.stun:
         stun_msg = 'Focusing energy on your muscle, your hand is slowly moving.'
         my.stun -= 1
         if not my.stun:
             stun_msg += '\nWith a masculine roar, you are wielding your light saber again.'
         await ctx.reply(stun_msg)
         return
     if his.sesami_oil:
         his.sesami_oil = False
         await ctx.reply('Your opponent instantly deflects your attack.')
         return
     xp = my.size - his.size
     my.score += xp
     if my.viagra > 1:
         my.viagra -= 1
     elif my.viagra == 1:
         my.viagra = -1
         my.size //= 2
         content = f"{ctx.author} ran out of ammo!"
     if my.size > his.size:
         title = "VICTORY"
         gain_msg = f"You gained **{xp}** score!"
     elif my.size == his.size:
         title = "TIE"
         gain_msg = ''
     else:
         title = "LOST"
         gain_msg = f"You lost **{-xp}** score!"
     await ctx.send(
         content=content,
         embed=missile.Embed(
             title, f"**{ctx.author.name}'s pp:**\n{my.draw()}\n"
             f"**{user.name}'s pp:**\n{his.draw()}\n\n{gain_msg}"))
示例#19
0
 async def flags(self, ctx, u: discord.User = None):
     """`info flags [u]`
     u: The user to inspect. Defaults to the command sender."""
     # https://discordpy.readthedocs.io/en/latest/api.html#discord.PublicUserFlags
     u = u if u else ctx.author
     bin_value = f'{u.public_flags.value:b}'
     hex_value = f'{u.public_flags.value:X}'
     emb = missile.Embed(
         u.name + "'s public flags",
         f"{u.public_flags.value}, 0b{bin_value.zfill(18)}, 0x{hex_value.zfill(5)}"
     )
     emb.add_field(name='Verified bot developer',
                   value=u.public_flags.verified_bot_developer)  # 2^17
     emb.add_field(name='Verified bot',
                   value=u.public_flags.verified_bot)  # 2^16
     if u.public_flags.bug_hunter_level_2:
         emb.add_field(name='Bug hunter', value='**Level 2**')  # 2^14
     else:
         emb.add_field(name='Bug hunter',
                       value=u.public_flags.bug_hunter)  # 2^3
     emb.add_field(name='Discord system',
                   value=u.public_flags.system)  # 2^12
     emb.add_field(name='Team User', value=u.public_flags.team_user)  # 2^10
     emb.add_field(name='Early supporter',
                   value=u.public_flags.early_supporter)  # 2^9
     if u.public_flags.hypesquad_balance:
         emb.add_field(name='HypeSquad', value='Balance')  # 2^8
     elif u.public_flags.hypesquad_brilliance:
         emb.add_field(name='HypeSquad', value='Brilliance')  # 2^7
     elif u.public_flags.hypesquad_bravery:
         emb.add_field(name='HypeSquad', value='Bravery')  # 2^6
     else:
         emb.add_field(name='HypeSquad',
                       value=u.public_flags.hypesquad)  # 2^2
     emb.add_field(name='Discord partner',
                   value=u.public_flags.partner)  # 2^1
     emb.add_field(name='Discord employee',
                   value=u.public_flags.staff)  # 2^0
     await ctx.reply(embed=emb)
示例#20
0
 async def info(self, ctx: Context, user: discord.User = None):
     """pp info [user]
     user: The target to check. Defaults to command sender."""
     user = user if user else ctx.author
     pp = self.get_pp(ctx, user.id)
     await ctx.reply(embed=missile.Embed(f'pp size: {pp.size}', pp.draw()))
示例#21
0
文件: bitbay.py 项目: Itamai/DimBot
 async def info(self, ctx: Context, user: discord.User = None):
     """Shows the pp info"""
     user = user if user else ctx.author
     pp = self.get_pp(ctx, user.id)
     await ctx.reply(embed=missile.Embed(f'pp size: {pp.size}', pp.draw()))
示例#22
0
    async def permissions(self,
                          ctx,
                          arg1: Union[discord.Member, discord.TextChannel,
                                      discord.VoiceChannel,
                                      discord.CategoryChannel,
                                      discord.StageChannel, None] = None,
                          arg2: Union[discord.TextChannel,
                                      discord.VoiceChannel,
                                      discord.CategoryChannel,
                                      discord.StageChannel, None] = None):
        """`info permissions [arg1] [arg2]`
        arg1 can be either a Member or a Channel
        arg2 can only be a Channel.
        You can have the following combinations:
        ```info p Member
        info p Channel
        info p Member Channel```
        *Note:* Channel can only be TextChannel, VoiceChannel, Category or StageChannel."""
        if arg1:
            if type(arg1) == discord.Member:
                mem = arg1
                if arg2:
                    channel = arg2
                else:
                    channel = None
            else:
                channel = arg1
                mem = ctx.author
        else:
            mem = ctx.author
            channel = None
        if channel:  # If no channel specified, then  check permission server-wise
            perm = channel.permissions_for(mem)
            title = channel.name
        else:  # Check permission of the member in that channel
            perm = mem.guild_permissions
            title = 'the server'

        # https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions
        bin_value = f'{perm.value:b}'
        hex_value = f'{perm.value:X}'
        emb = missile.Embed(
            f'Permissions for {mem.name} in {title}',
            f"{perm.value}, 0b{bin_value.zfill(30)}, 0x{hex_value.zfill(8)}")
        emb.add_field(name='Manage webhooks',
                      value=perm.manage_webhooks)  # 2^29
        emb.add_field(name='Manage permissions and roles',
                      value=perm.manage_permissions)  # 2^28
        emb.add_field(name='Manage nicknames',
                      value=perm.manage_nicknames)  # 2^27
        emb.add_field(name='Change nickname',
                      value=perm.change_nickname)  # 2^26
        emb.add_field(name='Use voice activation',
                      value=perm.use_voice_activation)  # 2^25
        emb.add_field(name='Move members to voice channels',
                      value=perm.move_members)  # 2^24
        emb.add_field(name='Deaf members', value=perm.deafen_members)  # 2^23
        emb.add_field(name='Mute members', value=perm.mute_members)  # 2^22
        emb.add_field(name='Speak', value=perm.speak)  # 2^21
        emb.add_field(name='Connect to voice channels',
                      value=perm.connect)  # 2^20
        emb.add_field(name='View server insights',
                      value=perm.view_guild_insights)  # 2^19
        emb.add_field(name='Use external emojis',
                      value=perm.external_emojis)  # 2^18
        emb.add_field(name='Mention everyone',
                      value=perm.mention_everyone)  # 2^17
        emb.add_field(name='Read message history',
                      value=perm.read_message_history)  # 2^16
        emb.add_field(name='Attach files', value=perm.attach_files)  # 2^15
        emb.add_field(name='Embed links', value=perm.embed_links)  # 2^14
        emb.add_field(name='Manage messages',
                      value=perm.manage_messages)  # 2^13
        emb.add_field(name='Send Text-to-Speech',
                      value=perm.send_tts_messages)  # 2^12
        emb.add_field(name='Send messages', value=perm.send_messages)  # 2^11
        emb.add_field(name='View channel and read messages',
                      value=perm.read_messages)  # 2^10
        emb.add_field(name='Stream', value=perm.stream)  # 2^9
        emb.add_field(name='Priority speaker',
                      value=perm.priority_speaker)  # 2^8
        emb.add_field(name='View audit log', value=perm.view_audit_log)  # 2^7
        emb.add_field(name='Add reactions', value=perm.add_reactions)  # 2^6
        await ctx.reply(
            content=f"Manage server: **{perm.manage_guild}** "  # 2^5
            f"Manage channels: **{perm.manage_channels}** "  # 2^4
            f"Administrator: **{perm.administrator}** "  # 2^3
            f"Ban members: **{perm.ban_members}** "  # 2^2
            f"Kick members: **{perm.kick_members}** "  # 2^1
            f"Create invites: **{perm.create_instant_invite}**",
            embed=emb)  # 2^0
示例#23
0
 async def slap(self, ctx: Context, user: discord.User):
     """pp slap <user>
     user: The user to slap"""
     pp = self.get_pp(ctx, ctx.author.id)
     await ctx.send(embed=missile.Embed(description=pp.draw(),
                                        thumbnail=user.avatar_url))
示例#24
0
文件: dimond.py 项目: Itamai/DimBot
    async def permissions(self, ctx, *args):
        """Shows a user's permission server/channel wise"""
        # TODO: Maybe first arg use Union[User, TextCh, VC, Category, None],
        #  second arg use Optional[TextCh, VC, Category]

        # If cmd has no args, evaluates sender's perms server-wise
        if len(args) == 0:
            mem = ctx.author
            channel = None
        else:
            # Process the first argument. If cmd only has 1 arg, its either member or channel
            # So first attempt to process member.
            try:
                mem = await commands.MemberConverter().convert(ctx, args[0])
            except commands.MemberNotFound:
                mem = ctx.author
            # Then attempt to process channel. If above failed, args[0] should be a channel so these converters should
            # work. If above succeed, these converters should fail.
            # If 2 args, then first arg must be a Member, which processed above. So 2nd arg should be a channel.
            ch_wanna_be = args[0] if len(args) == 1 else args[1]
            try:
                channel = await commands.TextChannelConverter().convert(
                    ctx, ch_wanna_be)
            except commands.ChannelNotFound:
                try:
                    channel = await commands.VoiceChannelConverter().convert(
                        ctx, ch_wanna_be)
                except commands.ChannelNotFound:
                    try:
                        channel = await commands.CategoryChannelConverter(
                        ).convert(ctx, ch_wanna_be)
                    except commands.ChannelNotFound:
                        channel = None
        if channel:  # If no channel specified, then  check permission server-wise
            perm = channel.permissions_for(mem)
            title = channel.name
        else:  # Check permission of the member in that channel
            perm = mem.guild_permissions
            title = 'the server'

        # https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions
        bin_value = f'{perm.value:b}'
        hex_value = f'{perm.value:X}'
        emb = missile.Embed(
            f'Permissions for {mem.name} in {title}',
            f"{perm.value}, 0b{bin_value.zfill(30)}, 0x{hex_value.zfill(8)}")
        emb.add_field(name='Manage webhooks',
                      value=perm.manage_webhooks)  # 2^29
        emb.add_field(name='Manage permissions and roles',
                      value=perm.manage_permissions)  # 2^28
        emb.add_field(name='Manage nicknames',
                      value=perm.manage_nicknames)  # 2^27
        emb.add_field(name='Change nickname',
                      value=perm.change_nickname)  # 2^26
        emb.add_field(name='Use voice activation',
                      value=perm.use_voice_activation)  # 2^25
        emb.add_field(name='Move members to voice channels',
                      value=perm.move_members)  # 2^24
        emb.add_field(name='Deaf members', value=perm.deafen_members)  # 2^23
        emb.add_field(name='Mute members', value=perm.mute_members)  # 2^22
        emb.add_field(name='Speak', value=perm.speak)  # 2^21
        emb.add_field(name='Connect to voice channels',
                      value=perm.connect)  # 2^20
        emb.add_field(name='View server insights',
                      value=perm.view_guild_insights)  # 2^19
        emb.add_field(name='Use external emojis',
                      value=perm.external_emojis)  # 2^18
        emb.add_field(name='Mention everyone',
                      value=perm.mention_everyone)  # 2^17
        emb.add_field(name='Read message history',
                      value=perm.read_message_history)  # 2^16
        emb.add_field(name='Attach files', value=perm.attach_files)  # 2^15
        emb.add_field(name='Embed links', value=perm.embed_links)  # 2^14
        emb.add_field(name='Manage messages',
                      value=perm.manage_messages)  # 2^13
        emb.add_field(name='Send Text-to-Speech',
                      value=perm.send_tts_messages)  # 2^12
        emb.add_field(name='Send messages', value=perm.send_messages)  # 2^11
        emb.add_field(name='View channel and read messages',
                      value=perm.read_messages)  # 2^10
        emb.add_field(name='Stream', value=perm.stream)  # 2^9
        emb.add_field(name='Priority speaker',
                      value=perm.priority_speaker)  # 2^8
        emb.add_field(name='View audit log', value=perm.view_audit_log)  # 2^7
        emb.add_field(name='Add reactions', value=perm.add_reactions)  # 2^6
        await ctx.reply(
            content=f"Manage server: **{perm.manage_guild}** "  # 2^5
            f"Manage channels: **{perm.manage_channels}** "  # 2^4
            f"Administrator: **{perm.administrator}** "  # 2^3
            f"Ban members: **{perm.ban_members}** "  # 2^2
            f"Kick members: **{perm.kick_members}** "  # 2^1
            f"Create invites: **{perm.create_instant_invite}**",
            embed=emb)  # 2^0
示例#25
0
 def pp_embed(user: discord.User, pp: PP):
     return missile.Embed(user.display_name + "'s pp", pp.draw())