一次向两个或多个成员添加角色

时间:2020-12-24 15:30:42

标签: python discord.py

当我给一个成员角色时,下面的代码工作得很好。它向我显示了与我输入的名称相匹配的成员列表。但是,当我尝试制作它以便我可以为多个成员批量分配角色时,它不起作用。我已经用 Greedy 的单独代码完成了这项工作,其中我没有搜索功能。所以我不完全确定是什么导致了错误。

 @commands.command(brief="Give Role to Member")
    @commands.has_permissions(manage_roles=True)
    async def give(self, ctx: commands.Context, member_name: typing.Optional[str], *, role: typing.Optional[str]) -> None:
        if not member_name:
            await ctx.send("Please enter a member query at the end of the command.")
            return
        elif not role:
            await ctx.send("Please enter a role name at the end of the command.")
            return
        members = await self.search_members(ctx.guild, member_name)
        role = await self.process_role(ctx, role)
        if len(members) == 0:
            await ctx.send(f"No members found for `{member_name}`.")
            return
        elif not role:
            await ctx.send(f"No role found for `{role}`.`")
            return
        if not len(members) > 1:
            member: discord.Member = members[0]
            try:
                await member.add_roles(role)
            except discord.Forbidden:
                await ctx.send("I don't have enough permissions to add the role or the member/role is higher than me.")
                return
            except Exception as e:
                await ctx.send(f"Something went wrong. Error: {e}.")
                return
            await ctx.send(f"Added {role.name} role to {member.display_name}!")
            return
        em = discord.Embed(title=f"Multiple users found for \"{member_name}\"", color=discord.Color.red())
        description = ""
        for n, i in enumerate(members, start=1):
            if n > 20:
                description += (f"...and {len(members) - 20} more.")
                break
            description += f"{n}. **{i}**\n"
        em.description = description
        em.set_footer(icon_url=self.bot.user.avatar_url_as() ,text=str(self.bot.user))
        em.timestamp = datetime.datetime.utcnow()
        em.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url_as())
        await ctx.send(embed=em)
        await ctx.send(f"**{ctx.author}**, please type the number of the user you wish to select below, or type `c` to cancel. This query will expire in 1 minute.")
        
        def check(msg):
            """Custom check to wait for message sent by command invoker"""
            return msg.author.id == ctx.author.id

        response = await self.bot.wait_for("message", check=check, timeout=60)
        if not await self.is_int(response.content):
            if response.content.lower() == "c":
                await ctx.send("Cancelled role give.")
                return
            else:
                await ctx.send("Invalid response.")
                return
        
        index = int(response.content)
        member = members[index - 1]
        try:
            await member.add_roles(role)
        except discord.Forbidden:
            await ctx.send("I don't have enough permissions to add the role or the member/role is higher than me.")
            return
        except Exception as e:
            await ctx.send(f"Something went wrong. Error: {e}.")
            return
        await ctx.send(f"Added {role.name} role to **{member.display_name}**!")
        return

    @commands.command(brief="Give Role to Members in Bulk")
    @commands.has_permissions(manage_roles=True)
    async def bulkgive(self, ctx: commands.Context, member_name: typing.Optional[str], *, role: typing.Optional[str]) -> None:
        if not member_name:
            await ctx.send("Please enter a member query at the end of the command.")
            return
        elif not role:
            await ctx.send("Please enter a role name at the end of the command.")
            return
        members = await self.search_members(ctx.guild, member_name)
        role = await self.process_role(ctx, role)
        if len(members) == 0:
            await ctx.send(f"No members found for `{member_name}`.")
            return
        elif not role:
            await ctx.send(f"No role found for `{role}`.`")
            return
        em = discord.Embed(title=f"Bulk giving {role} role to", color=discord.Color.red())
        description = ""
        for n, i in enumerate(members, start=1):
            if n > 20:
                description += (f"...and {len(members) - 20} more.")
                break
            description += f"{n}. **{i}**\n"
        em.description = description
        em.set_footer(icon_url=self.bot.user.avatar_url_as() ,text=str(self.bot.user))
        em.timestamp = datetime.datetime.utcnow()
        await ctx.send(embed=em)
        for member in members:
            try:
                await member.add_roles(role)
            except discord.Forbidden:
                await ctx.send(f"Couldn't add role to **{member}**. I don't have enough permissions to add the role or the member/role is higher than me.")
                continue
            except Exception as e:
                await ctx.send(f"Something went wrong. Couldn't add role to **{member}**. Error: {e}.")
                continue
        await ctx.send(f"Finished giving {role.name} role in bulk!")
        return

以下是我最初的做法。

@command(name="bulkgive")
    @has_permissions(manage_roles=True)
    async def bulkgive_role(self, ctx, targets: Greedy[Member], *, role: discord.Role):
        if not len(targets):
            await ctx.send("One or more required arguments are missing.")

        else:
            for target in targets:
                await target.add_roles(role)

                embed = Embed(title="Roles Given",
                              colour=role.colour,
                              timestamp=datetime.utcnow())

                fields = [("--------------------------------------", f"***{target.display_name}*** successfully added to ***{role.name}*** role by ***{ctx.author.display_name}***", False)]

                for name, value, inline in fields:
                    embed.add_field(name=name, value=value, inline=inline)

                await ctx.send(f"***{target.display_name}*** successfully added to ***{role.name}*** role by ***{ctx.author.display_name}***")
                await self.log_channel.send(embed=embed)

        await ctx.message.delete()

0 个答案:

没有答案