Пример #1
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)
Пример #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 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)
Пример #5
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)
Пример #6
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)
        )
Пример #7
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,
                ))
Пример #8
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))
Пример #9
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}`')
Пример #10
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)
Пример #11
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)
Пример #12
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
Пример #13
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
Пример #14
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())
Пример #15
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")
Пример #16
0
    async def colour(self, ctx, role: discord.Role, colour):
        not_author_perms = role >= ctx.author.top_role and ctx.author != ctx.guild.owner

        not_bot_perms = not ctx.me.guild_permissions.manage_roles or (
            role >= ctx.me.top_role and ctx.guild.me != ctx.guild.owner)

        if not_author_perms or not_bot_perms or role.is_default():
            return await ctx.dest.send(
                f'Um de nós não tem permissão para mudar a cor do seguinte cargo: `{role.name}`'
            )

        colour = discord.Colour(int(colour, 16))
        await role.edit(colour=colour)
        await ctx.dest.send('Cor alterada com sucesso.')
Пример #17
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.")
Пример #18
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))
Пример #19
0
    async def autorole_add(self, ctx, *, role: discord.Role):
        if role.is_default() or role.managed:
            return await ctx.send(":x: You can't use this role as an autorole")

        query = """INSERT INTO autoroles (guild_id, role_id)
                   VALUES ($1, $2)
                """
        try:
            await self.bot.db.execute(query, ctx.guild.id, role.id)
        except asyncpg.UniqueViolationError:
            return await ctx.send(
                ":x: This role is already in the autorole list")

        self.get_autoroles.invalidate(role.guild.id)

        await ctx.send(":white_check_mark: Added role to autorole list")
Пример #20
0
    async def role(self, ctx: commands.Context, *, role: discord.Role):
        bot_role: discord.Role = discord.utils.get(ctx.guild.me.roles,
                                                   managed=True)
        if role >= bot_role:
            return await ctx.send(
                'The Streamcord role must be higher than the live role.')
        elif role.managed:
            return await ctx.send(
                'The live role can\'t be managed by an integration.')
        elif role.is_default():
            return await ctx.send(
                'The live role can\'t be the server\'s default role. Use `!twitch lr del` to clear '
                'the configuration.')
        async with ctx.typing():
            await self.bot.db.liveRole.update_one(
                {'_id': str(ctx.guild.id)}, {'$set': {
                    'role': str(role.id)
                }},
                upsert=True)
        await ctx.send(
            'Server members who stream on Twitch will receive the **{role}** role.'
            .format(role=role.name))

        # fill roles for members that are already live
        config = await self.bot.db.liveRole.find_one(
            {'_id': str(ctx.guild.id)}) or {}

        role_members = [
            m for m in ctx.guild.members
            if config['role'] in [str(r.id) for r in m.roles]
        ]
        member: discord.Member
        for member in role_members:
            if not LiveRole._streaming_base(member):
                # user isn't streaming, so they shouldn't have the live role
                await member.remove_roles(
                    role, reason='[Live role] User is not streaming')
                self.log.info('Removed role from %s: not streaming', member.id)
            elif filter_role := config.get('filter'):
                if filter_role not in [str(r.id) for r in member.roles]:
                    # user doesn't have the filter role
                    await member.remove_roles(
                        role,
                        reason='[Live role] User does not have filter role')
                    self.log.info('Removed role from %s: no filter role',
                                  member.id)
Пример #21
0
    async def set_role_color(self, ctx, role: discord.Role,
                             color: discord.Color):
        """
        Color the nickname of the participant. * Let there be bright colors and colors! *
        [!] In development.
        Arguments:
        color in HEX

        For example:
        !setcolor #FF0000
        """
        try:
            if not role.is_default():
                await role.edit(color=color)
                embed = discord.Embed(
                    title=f"Changed the role color for {role.name} to {color}",
                    color=color)
                await ctx.send(embed=embed)
                await self.database.audit_record(ctx.guild.id, ctx.guild.name,
                                                 ctx.message.content,
                                                 ctx.message.author.id)
            else:
                embed = discord.Embed(
                    title="Peribot cannot affect the default roles.")
                await ctx.send(embed=embed)
        except discord.Forbidden:
            embed = discord.Embed(
                title="Peribot does not have permissions to change roles.")
            await ctx.send(embed=embed)
        except discord.HTTPException:
            embed = discord.Embed(
                title=f"Peribot failed to update {role.name}'s color")
            await ctx.send(embed=embed)
        except discord.InvalidArgument:
            embed = discord.Embed(
                title=f"Invalid Arguments!",
                description=
                f"{ctx.prefix}setcolor @Role [Hex Code or Generic Name]")
            await ctx.send(embed=embed)
        except discord.ext.commands.errors.BadArgument:
            embed = discord.Embed(
                title=f"Invalid Arguments!",
                description=
                f"{ctx.prefix}setcolor @Role [Hex Code or Generic Name]")
            await ctx.send(embed=embed)
Пример #22
0
        async def rinfo(ctx, *, str: discord.Role):
            if ctx.message.author == bot.user:
                return

            else:
                textchannel = ctx.message.channel
                await textchannel.trigger_typing()
                time.sleep(2)
                embed = discord.Embed(color=0x9b59b6)
                embed.add_field(name="Role Name", value=str.mention)
                embed.add_field(name="Role ID", value=str.id)
                embed.add_field(name="Color Hex", value=str.colour)
                embed.add_field(
                    name="Created At",
                    value=str.created_at.strftime("%m/%d/%y, %I:%M %p"))
                embed.add_field(name="Mentionable", value=str.mentionable)
                embed.add_field(name="Default Role", value=str.is_default())
                await ctx.send(embed=embed)
Пример #23
0
    async def remindrole(self, ctx, role: discord.Role, *, text):
        """Same as doing .remind me plus a role ping

        Remind role: When you create this reminder, it will automatically make the
        selected role by id pingable and will ping it after the reminder is triggered
        (after the ping the role will be unpinable again or left pingable if it was b4)

        Example: `[p]rro 1231432432 #movie-night Hey peeps with the role id 12314.... Movie time in 15h`
        `[p]rro Muted #general lol you guys are muted at 15:30`
        """
        # r = discord.utils.get(ctx.guild.roles, id=int(roleID))
        if role.is_default():
            return await ctx.send('Cannot use the @\u200beveryone role.')
        if role > ctx.author.top_role and ctx.author.id != ctx.guild.owner_id:
            return await ctx.send('This role is higher than your highest role.'
                                  )
        if role > ctx.me.top_role:
            return await ctx.send('This role is higher than my highest role.')
        await self.remindFunction(ctx, text, role)
Пример #24
0
    async def set_grant_role(self, ctx, role: Role = None):
        """Role bot grants upon successful vouching"""
        guild_cfg = ctx.client.my_cfg['guilds'][str(ctx.guild_id)]
        if role is not None:
            if not role.is_default():
                grid = str(role.id)
                guild_cfg['grant-role-id'] = grid
                msg = no_ping(f"Set grant role to {role.name}")
            else:
                msg = no_ping("Granting the @eveyone role is not possible")
        else:
            try:
                del guild_cfg['grant-role-id']
                msg = "Removed configured grant role"
            except KeyError:
                msg = "Grant role is not set"

        await respond_and_warn(ctx, msg)
        write_config(ctx.client.my_cfg)
Пример #25
0
    async def set_admin_role(self, ctx: Interaction, role: Role = None):
        """Set role granting access to guild settings on the bot"""
        guild_cfg = ctx.client.my_cfg['guilds'][str(ctx.guild_id)]
        if role is not None:
            if not role.is_default():
                arid = str(role.id)
                guild_cfg['admin-role-id'] = arid
                msg = no_ping(f"Set admin role to {role.name}")
            else:
                msg = "Granting admin access to everyone is not allowed"
        else:
            try:
                del guild_cfg['admin-role-id']
                msg = "Removed configured admin role"
            except KeyError:
                msg = "Admin role is not set"

        await respond_and_warn(ctx, msg)
        write_config(ctx.client.my_cfg)
Пример #26
0
    async def set_admin_role(self, ctx, role: Role = None):
        """Role granting access to settings on the bot"""
        cfg = self.bot.my_config
        if role is not None:
            if not role.is_default():
                arid = str(role.id)
                cfg['guilds'][str(ctx.guild.id)]['admin-role-id'] = arid
                msg = no_ping("Set admin role to {}".format(role.name))
            else:
                msg = "Granting admin access to everyone is not allowed"
        else:
            try:
                del cfg['guilds'][str(ctx.guild.id)]['admin-role-id']
                msg = "Removed configured admin role"
            except KeyError:
                msg = "Admin role is not set"

        await send_and_warn(ctx, msg)
        write_config(cfg)
Пример #27
0
    async def _filter(self, ctx: commands.Context, *, role: discord.Role):
        config = await self.bot.db.liveRole.find_one(
            {'_id': str(ctx.guild.id)}) or {}
        if not config.get('role'):
            return await ctx.send(
                'You must first set a live role using `!twitch lr set role @role-name`'
            )
        elif role.is_default():
            return await ctx.send(
                'The live role can\'t be the server\'s default role. Use `!twitch lr del filter` to '
                'clear the filter role.')

        async with ctx.typing():
            await self.bot.db.liveRole.update_one(
                {'_id': str(ctx.guild.id)}, {'$set': {
                    'filter': str(role.id)
                }})

        live_role = ctx.guild.get_role(int(config['role']))
        await ctx.send(
            'Server members who stream on Twitch and have the **{filter}** role will receive the'
            ' **{role}** role.'.format(filter=role.name, role=live_role.name))
Пример #28
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)
Пример #29
0
    async def mute_role_set(self, ctx, *, role: discord.Role):
        if role.is_default():
            return await ctx.send(":x: Cannot use the default role")
        elif role > ctx.author.top_role:
            return await ctx.send(
                ":x: This role is higher than your highest role")
        elif role > ctx.me.top_role:
            return await ctx.send(
                ":x: This role is higher than my highest role")

        config = await self.get_guild_config(ctx.guild)

        if config.mute_role:
            result = await menus.Confirm(
                "Are you sure you want to set a new mute role? All currently muted users will stay muted"
            ).prompt(ctx)
            if not result:
                return await ctx.send("Aborting")

        await config.set_mute_role(role)

        await ctx.send(
            f":white_check_mark: Mute role set to `{role.name}` ({role.id})")
Пример #30
0
    async def _assign(self, ctx, role: discord.Role, user: discord.Member = None):
        """Assign a role to a user"""
        author = ctx.author
        if user is None:
            user = author
        role_id = role.id
        server_dict = await self.config.guild(ctx.guild).roles()

        if role.is_default():
            notice = self.ASSIGN_NO_EVERYONE
        elif role_id not in server_dict:  # No role authorised to give this role.
            notice = self.AUTHORISE_EMPTY.format(role.name)
        # Check if any of the author's roles is authorised to grant the role.
        elif not any(r.id in server_dict[role_id] for r in author.roles):
            notice = self.AUTHORISE_MISMATCH.format(author.mention, role.name)
        else:  # Role "transaction" is valid.
            if role in user.roles:
                await user.remove_roles(role)
                notice = self.ASSIGN_REMOVED.format(role.name)
            else:
                await user.add_roles(role)
                notice = self.ASSIGN_ADDED.format(role.name)
        await ctx.send(notice)