Пример #1
0
    async def snapshot_role(ctx, role: discord.Role, group: RoleGroup = None):
        """Adds role to the internal database"""
        if role.is_bot_managed() or role.is_integration() or role.is_premium_subscriber():
            logger.info(f"Skipping role '{role}' as it's system role")
            raise commands.BadArgument(f"Role '{role}' is a system role")

        if not utils.can_manage_role(ctx.guild.me, role):
            logger.info(f"Skipping role '{role}' as bot cannot manage it")
            raise commands.BadArgument(f"Bot cannot manage role '{role}'")

        if await Role.exists(name=role.name):
            logger.info(f"Skipping role '{role}' as it already exists")
            raise commands.BadArgument(f"Role '{role}' already exists in DB")

        group = group or (await RoleGroup.get_or_create(name=utils.snapshot_role_group))[0]
        number = await db_utils.get_max_number(Role)
        await db_utils.reshuffle(Role, number)
        db_role = Role(name=role.name,
                       color=role.color.value,
                       number=number,
                       archived=False,
                       assignable=False,
                       mentionable=role.mentionable,
                       group=group)
        await db_role.save()
Пример #2
0
    async def deauthorise(self, ctx, authorised_role: discord.Role, giveable_role: discord.Role):
        """Deauthorise one role to give another role

        In order to deauthorise, your highest role must be strictly above the `authorised_role` (except for the owner).
        """
        gld = ctx.guild
        server_dict = await self.config.guild(gld).roles()

        author_max_role = max(r for r in ctx.author.roles)
        authorised_id = authorised_role.id
        giveable_id = giveable_role.id

        if authorised_role.is_default():  # Role to be de-authorised should not be @everyone.
            notice = self.AUTHORISE_NO_EVERYONE
        elif giveable_role.is_default():  # Same goes for role to be given.
            notice = self.AUTHORISE_NOT_DEFAULT
        elif authorised_role >= author_max_role and ctx.author != gld.owner:  # Hierarchical role order check.
            notice = self.AUTHORISE_NO_HIGHER
        elif giveable_id not in server_dict:
            notice = self.AUTHORISE_EMPTY.format(giveable_role.name)
        elif authorised_id not in server_dict[giveable_id]:
            notice = self.AUTHORISE_MISMATCH.format(authorised_role.name, giveable_role.name)
        else:  # Role de-authorisation is valid.
            server_dict[giveable_id].remove(authorised_id)
            await self.config.guild(gld).roles.set(server_dict)
            notice = self.DEAUTHORISE_SUCCESS.format(authorised_role.name, giveable_role.name)
        await ctx.send(notice)
Пример #3
0
def get_overwrites(arg: discord.Role, arg2: discord.PermissionOverwrite):
    return {
        "role_name": arg.name,
        "is_default": arg.is_default(),
        "is_bot": arg.is_bot_managed(),
        "is_boost": arg.is_premium_subscriber(),
    }
Пример #4
0
    async def authorise(self, ctx, authorised_role: discord.Role, giveable_role: discord.Role):
        """Authorise one role to give another role

        Allows all members with the role `authorised_role` to give the role `giveable_role` to everyone.
        In order to authorise, your highest role must be strictly above the `authorised_role` (except for the owner).
        """
        gld = ctx.guild
        server_dict = await self.config.guild(gld).roles()

        author_max_role = max(r for r in ctx.author.roles)
        authorised_id = authorised_role.id
        giveable_id = giveable_role.id

        if authorised_role.is_default():  # Role to be authorised should not be @everyone.
            notice = self.AUTHORISE_NO_EVERYONE
        elif giveable_role.is_default():  # Same goes for role to be given.
            notice = self.AUTHORISE_NOT_DEFAULT
        elif authorised_role >= author_max_role and ctx.author != gld.owner:  # Hierarchical role order check.
            notice = self.AUTHORISE_NO_HIGHER
        # Check if "pair" already exists.
        elif giveable_id in server_dict and authorised_id in server_dict[giveable_id]:
            notice = self.AUTHORISE_EXISTS
        else:  # Role authorisation is valid.
            server_dict.setdefault(giveable_id, []).append(authorised_id)
            await self.config.guild(gld).roles.set(server_dict)
            notice = self.AUTHORISE_SUCCESS.format(authorised_role.name, giveable_role.name)
        await ctx.send(notice)
Пример #5
0
 async def srecolor(self, ctx, *, roleName: discord.Role, hexColor):
     """Edit Event Role color/colour"""
     try:
         roleName.edit(colour=discord.Colour(int(f"0x{hexColor}", 16)))
     except:
         ctx.send("Oops, that didn't work... Maybe something was typed weird?")
     else:
         await ctx.message.add_reaction("✅")
Пример #6
0
 async def srename(self, ctx, roleName: discord.Role, *, newName):
     """Edit Event Role name"""
     try:
         roleName.edit(name=newName)
     except:
         ctx.send("Oops, that didn't work... Maybe something was typed weird?")
     else:
         await ctx.message.add_reaction("✅")
Пример #7
0
    async def manage_roles_check(
        self,
        ctx: commands.Context,
        action: str,
        role: discord.Role = None,
        verbosity=Verbosity.ALL,
        error_title="default"
    ) -> int:  # verbose toggle e.g. in multi-role changes
        """
        Error checking to see if whatever action can be performed.

        Verbosity:
          0: Nothing
          1: Manage Roles barf embed
          2: Everything

        Returns:
          0: Humanity is fine
          Anything else: Alien invasion
        """

        error_title = f"Couldn't {action} the role!" if error_title == "default" else error_title
        if not ctx.me.guild_permissions.manage_roles:  # was originally gonna separate this all out but given discord rate-limits are stupid you can't work on the assumption that you"ve retained permissions
            if verbosity > Verbosity.SILENT:
                await self.bot.DefaultEmbedResponses.error_embed(
                    self.bot,
                    ctx,
                    error_title,
                    desc="Please give me **Manage Roles** permissions")
            return 3
        if role:
            if role.managed or role.is_bot_managed(
            ) or role.is_premium_subscriber() or role.is_integration(
            ) or role.is_default():
                """
                Basically checks if the role is a nitro booster role, or is an integration-managed role.
                """
                if verbosity == Verbosity.ALL:
                    await self.bot.DefaultEmbedResponses.error_embed(
                        self.bot,
                        ctx,
                        error_title,
                        desc=f"A user cannot {action} this role")
                return 2
            if ctx.me.top_role < role:
                if verbosity == Verbosity.ALL:
                    await self.bot.DefaultEmbedResponses.error_embed(
                        self.bot,
                        ctx,
                        error_title,
                        desc=f"I can't add roles higher than me to members :sob:"
                        if action == "add" else
                        "I can't remove roles higher than me from members :sob:"
                    )
                return 1
        return 0
Пример #8
0
 async def roleinfo(self, ctx, role: discord.Role):
     embed = (discord.Embed(color=discord.Color.blurple()).set_author(
         name=f'Role Information: {str(role)}',
         icon_url=ctx.author.avatar_url))
     embed.add_field(name='Creation Date:',
                     value=role.created_at).add_field(
                         name='Mentionable', value=role.mentionable)
     embed.add_field(name='Managed By Integration',
                     value=role.is_integration()).add_field(
                         name='Managed By Bot', value=role.is_bot_managed())
     embed.add_field(name='Role Position',
                     value=role.position).add_field(name='Role ID',
                                                    value=f'`{role.id}`')
     await ctx.send(embed=embed)
Пример #9
0
 async def role(self, ctx, *, role: discord.Role):
     query = f"""http://www.colourlovers.com/img/{hex(role.colour.value).replace("0x", "")}/100/100/"""
     embed = discord.Embed(
         colour=0x202225,
         title=f"Information about {role.name} (ID {role.id}!)")
     embed.set_thumbnail(
         url=query.replace("/img/0/100/100/", "/img/8B99A4/100/100/"))
     embed.add_field(
         name="Permissions",
         value=
         f"[{role.permissions.value}](https://discordapi.com/permissions.html#{role.permissions.value})",
         inline=True)
     embed.add_field(name="Hoisted", value=role.hoist, inline=True)
     embed.add_field(name="Position",
                     value=f"{role.position}/{len(ctx.guild.roles)}",
                     inline=True)
     embed.add_field(name="Mentionable",
                     value=role.mentionable,
                     inline=True)
     embed.add_field(name="Managed by 3rd party",
                     value=role.managed,
                     inline=True)
     embed.add_field(name="Is Managed",
                     value=role.is_bot_managed(),
                     inline=True)
     embed.add_field(name="Is the Boost Role",
                     value=role.is_premium_subscriber(),
                     inline=True)
     embed.add_field(name="Is an Integration",
                     value=role.is_integration(),
                     inline=True)
     embed.set_footer(text=f"Role created at {role.created_at}.")
     member_count = 0
     members = ""
     for member in role.members:
         if member_count == 0:
             members += f"<@{member.id}>"
         else:
             members += f", <@{member.id}>"
         member_count += 1
     try:
         embed.add_field(name=f"Role Members ({len(role.members)})",
                         value=members,
                         inline=False)
     except discord.errors.HTTPException:
         embed.add_field(name=f"Role Members ({len(role.members)})",
                         value="There was too much to put here.",
                         inline=False)
     await ctx.send(embed=embed)
Пример #10
0
    async def role(self, ctx, *, role: discord.Role):
        '''Display info on a role.\n
        **Example:```yml\n♤role Tau\n♤role 657766595321528349```**
        '''
        buffer = utils.display_color(role.color)

        perms = sorted((perm, value) for perm, value in iter(role.permissions))
        plen = len(max(perms, key=lambda p: len(p[0]))[0])

        half = len(perms) // 2
        fields = [''] * 2
        for i, tup in enumerate(perms):
            perm, value = tup
            tog = utils.Emoji.on if value else utils.Emoji.off
            align = ' ' * (plen - len(perm))
            fields[i > half] += f'**`{perm}{align}`** {tog}\n'

        plural = 's' if len(role.members) != 1 else ''
        mention = role.mention if not role.is_default() else '@everyone'
        embed = Embed(
            description=f'**{mention}\n`{len(role.members)} member{plural}`**',
            color=role.color)
        embed.add_field(name='Permissions', value=fields[0])
        embed.add_field(name='\u200b', value=fields[1])
        embed.set_image(url='attachment://unknown.png')
        embed.set_footer(text=f'ID: {role.id}')

        await ctx.reply(file=File(buffer, 'unknown.png'),
                        embed=embed,
                        mention_author=False)
Пример #11
0
    async def reactionrole_add(self, ctx: Context, msg: Message, emoji: EmojiConverter, role: Role, auto_remove: bool):
        """
        add a new reactionrole link
        """

        emoji: PartialEmoji

        if await db_thread(ReactionRole.get, msg.channel.id, msg.id, str(emoji)) is not None:
            raise CommandError(translations.rr_link_already_exists)
        if not msg.channel.permissions_for(msg.guild.me).add_reactions:
            raise CommandError(translations.rr_link_not_created_no_permissions)

        if role >= ctx.me.top_role:
            raise CommandError(translations.f_link_not_created_too_high(role, ctx.me.top_role))
        if role.managed or role.is_default():
            raise CommandError(translations.f_link_not_created_managed_role(role))

        await db_thread(ReactionRole.create, msg.channel.id, msg.id, str(emoji), role.id, auto_remove)
        await msg.add_reaction(emoji)
        embed = Embed(
            title=translations.reactionrole, colour=Colours.ReactionRole, description=translations.rr_link_created
        )
        await ctx.send(embed=embed)
        await send_to_changelog(
            ctx.guild, translations.f_log_rr_link_created(emoji, role.id, msg.jump_url, msg.channel.mention)
        )
Пример #12
0
 async def selfroles(self, ctx, func: str, name: str, *, role: discord.Role = None):
     """Manage the guild self roles for the `iam` command.
     Valid functions: `add`, `new`, `remove`, `rm`, `rem`, `delete`, `del`"""
     if func in ['add', 'new']:
         if role:
             if role.is_default():
                 return await ctx.send(resolve_emoji('ERROR', ctx) + ' You cannot set the default everyone role as a self role.')
             if role.position >= ctx.author.top_role.position:
                 return await ctx.send(
                     resolve_emoji('ERROR', ctx) + ' You cannot manage a role higher than your own.')
             results = self.bot.query_db(f'''SELECT self_roles FROM settings WHERE guildid={ctx.guild.id};''')
             selfroles = json.loads(results[0][0].replace("'", '"')) if results and results[0][0] else json.loads('{}')
             selfroles[name] = role.id
             self.bot.query_db(f'''UPDATE settings SET self_roles="{str(selfroles)}" WHERE guildid={ctx.guild.id};''')
             await ctx.send(resolve_emoji('SUCCESS', ctx) + f' Successfully added self role **{name}** which gives role **{role}**. This can be applied with `{ctx.prefix}iam {name}`')
         else:
             await ctx.send(resolve_emoji('ERROR', ctx) + f' Missing required argument `role`, check `{ctx.prefix}help {ctx.command}`')
     elif func in ['rm', 'rem', 'remove', 'delete', 'del']:
         results = self.bot.query_db(f'''SELECT self_roles FROM settings WHERE guildid={ctx.guild.id};''')
         selfroles = json.loads(results[0][0].replace("'", '"')) if results and results[0][0] else json.loads('{}')
         try:
             del selfroles[name]
         except KeyError:
             return await ctx.send(resolve_emoji('ERROR', ctx) + f' There is no self role with the name `{name}`')
         self.bot.query_db(f'''UPDATE settings SET self_roles="{str(selfroles)}" WHERE guildid={ctx.guild.id};''')
         await ctx.send(resolve_emoji('SUCCESS', ctx) + f' Successfully removed self role **{name}**.')
     else:
         await ctx.send(resolve_emoji('ERROR', ctx) + f' Invalid function, check `{ctx.prefix}help {ctx.command}`')
Пример #13
0
    async def add(self, ctx: Context, message: Message,
                  emoji: FixedEmojiConverter, role: Role):
        """
        add a new reactionrole link
        """

        emoji: PartialEmoji

        if await run_in_thread(ReactionRole.get, message.channel.id,
                               message.id, str(emoji)) is not None:
            raise CommandError(translations.rr_link_already_exists)

        if role > ctx.me.top_role:
            raise CommandError(
                translations.f_link_not_created_too_high(
                    role, ctx.me.top_role))
        if role.managed or role.is_default():
            raise CommandError(
                translations.f_link_not_created_managed_role(role))

        await run_in_thread(ReactionRole.create, message.channel.id,
                            message.id, str(emoji), role.id)
        await message.add_reaction(emoji)
        await ctx.send(translations.rr_link_created)
        await send_to_changelog(
            ctx.guild,
            translations.f_log_rr_link_created(emoji, role, message.jump_url))
Пример #14
0
    async def _add_remove(self,
                          ctx: commands.Context,
                          role: discord.Role,
                          *,
                          rm: bool = False):
        if role.is_default():
            raise commands.BadArgument(
                "cannot make a server's default role mentionable")
        async with self.config.guild(ctx.guild).roles() as roles:
            if rm is False:
                if role.id in roles:
                    await ctx.send(
                        warning(_("That role is already mentionable")))
                    return
                roles.append(role.id)

            else:
                if role.id not in roles:
                    await ctx.send(
                        warning(_("That role is not currently mentionable")))
                    return
                roles.remove(role.id)

            await ctx.send(
                escape(
                    tick(
                        _("`{}` is now allowed to be mentioned").format(role.
                                                                        name)),
                    mass_mentions=True,
                ) if rm is False else escape(
                    tick(
                        _("`{}` is no longer allowed to be mentioned").
                        format(role.name)),
                    mass_mentions=True,
                ))
Пример #15
0
async def take(ctx, member: discord.Member, *, role: discord.Role):
    await ctx.message.delete()
    if role != None:
        if role > ctx.author.top_role and ctx.message.author.id != 338714886001524737:
            await ctx.send(
                'Вы не можете забрать эту роль, так как она имеет более высокий ранг, чем ваша высшая роль.'
            )
        elif role == ctx.author.top_role and ctx.message.author.id != 338714886001524737:
            await ctx.send(
                'Вы не можете забрать эту роль у кого-либо, так как она равна вашей высшей роли.'
            )
        elif role.is_default():
            await ctx.send('Забирать everyone? Всё с башкой хорошо?')
        else:
            await member.remove_roles(role)
            channel = client.get_channel(714175791033876490)
            emb = discord.Embed(colour=member.color,
                                timestamp=ctx.message.created_at)
            emb.add_field(name='Была забрана роль',
                          value=f'{role.mention} | {role.name} | ID {role.id}')
            emb.add_field(name='Забрана:', value=member.mention)
            emb.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
            emb.set_footer(
                text='Обратите внимание, что это Бета версия основного бота.')
            await channel.send(embed=emb)
    else:
        emb = discord.Embed(
            description=
            f'{ctx.author.mention}, я не могу найти {role.mention} в списке ролей.',
            colour=member.color,
            timestamp=ctx.message.created_at)
        await ctx.send(embed=emb)
Пример #16
0
async def move_role_position_below(role:discord.Role, below:discord.Role, reason:typing.Optional[str]) -> None:
    """|coro|

    Moves the current role beneath the given role, cascading down and fixing the order of all lower roles
    """

    if below.is_default() or role.is_default():
        raise discord.errors.InvalidArgument("Cannot move default role")

    if below == role:
        return  # Save discord the extra request.

    http = role._state.http

    # Fetch the roles from the API, ordered by the order of the cache
    all_guild_roles = sorted(await role.guild.fetch_roles())

    # Get the order of the roles we want to append
    roles = []
    encounters = 0
    for r in all_guild_roles[1:]:
        if r.id == role.id:
            encounters += 1
            continue
        if r.id == below.id:
            encounters += 1
            roles.append(role)
            roles.append(r)
        else:
            roles.append(r)
        if encounters == 2:
            break

    # For up positions for the roles
    # I do it like this so there's less of a chance of me having to move the top role of the listing
    # or any roles above it, so that there's less of a chance of me having to move roles that
    # I don't have permission to deal with
    position = 1
    new_roles = [{"id": roles[0].id, "position": 1}]
    for r in roles[1:]:
        if r.id > new_roles[-1]["id"]:
            position += 1
        new_roles.append({"id": r.id, "position": position})

    # Make and send the payload
    await http.move_role_position(role.guild.id, new_roles, reason=reason)
Пример #17
0
def test_set_point_leader_role_replaces_old_role_if_one_exists(
        discord_role: DiscordRole, guild: Guild, leader_role: PointLeaderRole):
    discord_role.id = ROLE_ID + 1
    set_point_leader_role(discord_role)

    assert PointLeaderRole.select().count() == 1
    role = PointLeaderRole.get(PointLeaderRole.guild_id == guild.id)
    assert role.role_id == discord_role.id
Пример #18
0
    async def roleinfo(self, ctx, *, role: discord.Role):

        "See a role info"

        if role.hoist:

            hoist = f"📲 | Is Hoist"

        else:

            hoist = f"~~📲 | Isn't Hoist~~"

        if role.managed:

            managed = f"⌨️ | Is Managed"

        else:

            managed = f"~~⌨️ | Isn't Managed~~"

        if role.mentionable:

            mentionable = f"🏓 | Is Mentionable"

        else:

            mentionable = f"~~🏓 | Isn't Mentionable~~"

        if role.is_default():

            default = f"📐 | By Default"

        else:

            default = "~~📐 | Not By Default~~"

        emb = discord.Embed(title=role.name,
                            description=f"""
😀  | {role.name}
🆔 | {role.id}
📢 | {role.mention}

🍰 | Created at {role.created_at.strftime("%m / %d / %Y (%H:%M)")}
🙅 | {len(role.members)} users
📑 | {role.position}° position
🎨 | {role.colour}

🛑 | {role.permissions.value} Perms Value
{hoist}
{managed}
{mentionable}
{default}
""",
                            colour=role.colour,
                            timestamp=ctx.message.created_at)
        emb.set_footer(text=ctx.guild.name, icon_url=ctx.guild.icon_url)
        await ctx.send(embed=emb)
Пример #19
0
def discord_role(discord_connection, discord_guild):
    from discord import Role

    return Role(data={
        "id": 1,
        "name": "FakeRole"
    },
                guild=discord_guild,
                state=discord_connection)
Пример #20
0
 async def role_info(self, ctx, role: discord.Role):
     e = Embed(color=discord.Color.dark_theme())
     e.add_field(name="Name", value=role.mention)
     e.add_field(name="Color", value=role.color)
     e.add_field(name="Member count", value=len(role.members))
     e.add_field(name="Bot Role?", value=role.is_bot_managed())
     e.add_field(name="Nitro Role?", value=role.is_premium_subscriber())
     e.add_field(
         name="Permissions",
         value=
         f"**Admin?** {role.permissions.administrator}\n**Manager?** {role.permissions.manage_guild}",
     )
     e.add_field(name="Position", value=role.position)
     e.add_field(name="ID", value=role.id)
     e.add_field(name="Created at", value=role.created_at)
     try:
         await ctx.send(embed=e)
     except Exception as e:
         await ctx.send(e)
Пример #21
0
async def can_manage_role(bot: commands.Bot, role: discord.Role) -> bool:
    if role.is_default():
        print(1)
        return False
    if role.managed:
        print(2)
        return False
    if role.position >= role.guild.me.top_role.position:
        print(3)
        return False
    return True
Пример #22
0
 async def role_update(self, role: discord.Role):
     (await GuildRoles.update.values(
         id=role.id,
         name=role.name,
         colour=str(role.colour),
         hoist=role.hoist,
         position=role.position,
         managed=role.managed,
         mentionable=role.mentionable,
         is_default=role.is_default(),
         created_at=role.created_at).where(GuildRoles.id == role.id
                                           ).gino.status())
Пример #23
0
Файл: code.py Проект: D-9341/PRO
async def role(ctx, *, role: discord.Role):
    await ctx.message.delete()
    if ctx.guild.id not in guilds:
        emb = discord.Embed(description = f'Сервер `{ctx.guild}` не имеет активных подписок. Купить можно по [Ссылке](https://www.patreon.com/cephaloncy) Преимущества: пинг не более 25ms, больший аптайм, защита от несанкционированного добавления на сервера.', colour = discord.Color.red())
        await ctx.send(embed = emb)
    else:
        if role.mentionable == False:
            role.mentionable = 'Нет'
        elif role.mentionable == True:
            role.mentionable = 'Да'
        if role.managed == False:
            role.managed = 'Нет'
        elif role.managed == True:
            role.managed = 'Да'
        if role.hoist == False:
            role.hoist = 'Нет'
        elif role.hoist == True:
            role.hoist = 'Да'
        emb = discord.Embed(title = role.name, colour = role.colour)
        emb.add_field(name = 'ID', value = role.id)
        emb.add_field(name = 'Цвет', value = role.color)
        emb.add_field(name = 'Упоминается?', value = role.mentionable)
        emb.add_field(name = 'Управляется интеграцией?', value = role.managed)
        emb.add_field(name = 'Позиция в списке', value = role.position)
        now = datetime.datetime.today()
        then = role.created_at
        delta = now - then
        d = role.created_at.strftime('%d/%m/%Y %H:%M:%S UTC')
        emb.add_field(name = 'Создана', value = f'{delta.days} дня(ей) назад. ({d})', inline = False)
        emb.add_field(name = 'Показывает участников отдельно?', value = role.hoist)
        await ctx.send(embed = emb)
Пример #24
0
async def role(ctx, *, role: discord.Role):
    await ctx.message.delete()
    if role.mentionable == False:
        role.mentionable = 'Нет'
    elif role.mentionable == True:
        role.mentionable = 'Да'
    if role.managed == False:
        role.managed = 'Нет'
    elif role.managed == True:
        role.managed = 'Да'
    if role.hoist == False:
        role.hoist = 'Нет'
    elif role.hoist == True:
        role.hoist = 'Да'
    emb = discord.Embed(title=role.name, colour=role.colour)
    emb.add_field(name='ID', value=role.id)
    emb.add_field(name='Цвет', value=role.color)
    emb.add_field(name='Упоминается?', value=role.mentionable)
    emb.add_field(name='Управляется интеграцией?', value=role.managed)
    emb.add_field(name='Позиция в списке', value=role.position)
    now = datetime.datetime.today()
    then = role.created_at
    delta = now - then
    d = role.created_at.strftime('%d/%m/%Y %H:%M:%S UTC')
    emb.add_field(name='Создана',
                  value=f'{delta.days} дня(ей) назад. ({d})',
                  inline=False)
    emb.add_field(name='Показывает участников отдельно?', value=role.hoist)
    emb.set_footer(
        text='Обратите внимание, что это Бета версия основного бота.')
    await ctx.send(embed=emb)
Пример #25
0
 async def set_new_role(self, ctx: "IceTeaContext", target_role: discord.Role = None, when: int = 0):
     """
     Automatically assigns a role to a user, upon joining the server.
     Can only be used by server managers
     it has an optimal param to allow the bot to give the role after x seconds, If not set, will give the user the
     role right away. If you wish to disable this function after it's been enabled simply run this command without
     giving it a role.
     """
     if target_role < ctx.me.top_role and not target_role.is_default():
         ctx.guild_data.role = target_role.id
         ctx.guild_data.delay = when
         await ctx.guild_data.save()
         await ctx.send(f"I will now give {target_role} to new members")
Пример #26
0
 async def role(self, ctx: commands.Context, r: discord.Role):
     """Shows role info"""
     emb = discord.Embed(title=r.name, color=r.color)
     emb.set_author(name=f'Color: #{r.color.value:X}')
     if r.is_bot_managed():
         emb.description = 'Bot role: ' + self.bot.get_user(
             r.tags.bot_id).mention
     elif r.is_default():
         emb.description = 'Default role'
     elif r.is_integration():
         emb.description = 'Integration role: ❄ID ' + str(
             r.tags.integration_id)
     elif r.is_premium_subscriber():
         emb.description = 'Nitro Boost role'
     emb.add_field(name='❄ ID', value=r.id)
     # noinspection PyTypeChecker
     emb.add_field(name='Member count', value=len(r.members))
     emb.add_field(name='Displays separately', value=r.hoist)
     emb.add_field(name='Created at', value=r.created_at)
     emb.add_field(name='Permissions', value=f'0x{r.permissions.value:X}')
     emb.add_field(name='Position', value=r.position)
     await ctx.reply(embed=emb)
Пример #27
0
 async def rinfo(self, ctx, *, role: discord.Role):
     """Get info about role"""
     em = discord.Embed(
         title=chat.escape(role.name, formatting=True),
         color=role.color if role.color.value else discord.Embed.Empty,
     )
     em.add_field(name=_("ID"), value=role.id)
     em.add_field(
         name=_("Permissions"),
         value=
         "[{0}](https://cogs.fixator10.ru/permissions-calculator/?v={0})".
         format(role.permissions.value),
     )
     em.add_field(
         name=_("Exists since"),
         value=get_markdown_timestamp(role.created_at,
                                      TimestampStyle.datetime_long),
     )
     em.add_field(name=_("Color"), value=role.colour)
     em.add_field(name=_("Members"), value=str(len(role.members)))
     em.add_field(name=_("Position"), value=role.position)
     em.add_field(name=_("Managed"), value=bool_emojify(role.managed))
     em.add_field(name=_("Managed by bot"),
                  value=bool_emojify(role.is_bot_managed()))
     em.add_field(name=_("Managed by boosts"),
                  value=bool_emojify(role.is_premium_subscriber()))
     em.add_field(name=_("Managed by integration"),
                  value=bool_emojify(role.is_integration()))
     em.add_field(name=_("Hoist"), value=bool_emojify(role.hoist))
     em.add_field(name=_("Mentionable"),
                  value=bool_emojify(role.mentionable))
     em.add_field(name=_("Mention"),
                  value=role.mention + "\n`" + role.mention + "`")
     em.set_thumbnail(
         url=
         f"https://xenforo.com/community/rgba.php?r={role.colour.r}&g={role.color.g}&b={role.color.b}&a=255"
     )
     await ctx.send(embed=em)
Пример #28
0
 async def remove(self, ctx: commands.Context, target: discord.Member,
                  *roles: discord.Role):
     roles = list(roles)
     for role in roles[:]:
         if role.position >= ctx.author.top_role.position:
             await ctx.send(
                 "You don't have the power to manage the `{}` role!".format(
                     role.name))
             roles.remove(role)
     if roles == []:
         return
     await target.remove_roles(*roles,
                               reason="Requested by " + ctx.author.name)
     s_roles = ""
     for i in range(len(roles)):
         if i != len(roles) - 1 and i != len(roles) - 2:
             s_roles += "`{}`, ".format(roles[i].name)
         elif i == len(roles) - 2:
             s_roles += "`{}`, and ".format(roles[i].name)
         else:
             s_roles += "`{}`".format(roles[i].name)
     await ctx.send("Took the {1} role(s) from {0}".format(
         target.mention, s_roles))
Пример #29
0
    async def role(self, ctx, role: discord.Role):
        if (role.is_default() or role.managed
                or role.position >= ctx.guild.me.top_role.position):
            await ctx.send(
                "Please choose a role that isn't the `everyone` role, "
                "and isn't managed by an integration such as a bot, that I have permission to give."
            )
            return

        await self.bot.config.upsert({
            "_id": ctx.guild.id,
            "quiz_role": role.id
        })
        await ctx.send("Role added as a quiz role.")
Пример #30
0
    async def delete_role(self, ctx, *, role: discord.Role = None):
        """This command can be used to delete one of the roles from the server

        EXAMPLE: !role delete StupidRole
        RESULT: No more role called StupidRole"""
        # No use in running through everything if the bot cannot manage roles
        if not ctx.message.guild.me.permissions_in(
                ctx.message.channel).manage_roles:
            await ctx.send(
                "I can't delete roles in this server, do you not trust  me? :c"
            )
            return

        # If no role was given, get the current roles on the server and ask which ones they'd like to remove
        if role is None:
            server_roles = [
                role for role in ctx.message.guild.roles
                if not role.is_default()
            ]

            await ctx.send(
                "Which role would you like to remove from the server? Here is a list of this server's roles:"
                "```\n{}```".format("\n".join([r.name for r in server_roles])))

            # For this method we're only going to delete one role at a time
            # This check attempts to find a role based on the content provided, if it can't find one it returns None
            # We can use that fact to simply use just that as our check
            def check(m):
                if m.author == ctx.message.author and m.channel == ctx.message.channel:
                    return discord.utils.get(server_roles,
                                             name=m.content) is not None
                else:
                    return False

            try:
                msg = await ctx.bot.wait_for('message',
                                             timeout=60,
                                             check=check)
            except asyncio.TimeoutError:
                await ctx.send(
                    "You took too long. I'm impatient, don't make me wait")
                return
            # If we have gotten here, based on our previous check, we know that the content provided is a valid role.
            # Due to that, no need for any error checking here
            role = discord.utils.get(server_roles, name=msg.content)

        await role.delete()
        await ctx.send(
            "I have just removed the role {} from this server".format(
                role.name))