【问题标题】:Discord.py bot that creates channel via given arguments and gives specific permissions to the user for that channelDiscord.py 机器人通过给定参数创建频道并为该频道的用户提供特定权限
【发布时间】:2022-01-15 21:28:36
【问题描述】:

我正在寻找一个个人不和谐机器人,版主将使用它来为特定用户创建频道。它将以“$create firstName lastName category user”的形式调用,哪个类别是创建频道的类别,user 是带有标签的用户的用户名。我已经设法让它创建频道,但我不知道如何为新创建的频道授予用户特定权限。这是我当前从命令创建频道的定义

@bot.command()
async def create(ctx, firstName, lastName, category, user):
    print(ctx)
    role = discord.utils.get(ctx.guild.roles, name="Moderator")
    if role in ctx.author.roles:
        cat = discord.utils.get(ctx.guild.categories, name=category)
        await ctx.guild.create_text_channel(firstName + ' ' + lastName, category=cat)
        #insert permission changes for user id: user id is the actual username and tag

    else:
        await ctx.send("You do not have permissions to create a channel. Only Moderators do")```

【问题讨论】:

    标签: python discord bots


    【解决方案1】:

    您可能想做的与您的问题无关的一件事是添加一个关于是否找到该类别的检查。版主可以输入一个不存在的类别名称,在这种情况下,您的命令将失败且没有错误消息。您可以像其他检查一样执行此操作:

    cat = discord.utils.get(ctx.guild.categories, name=category)
    if not cat:
        await ctx.send("This category does not exist.")
        return
    await ctx.guild.create_text_channel(firstName + ' ' + lastName, category=cat)
    

    现在,要添加权限,您有两种选择。您可以创建频道然后编辑其权限,但您也可以传递dict 的权限覆盖您创建频道。这就是我们将采取的方法。

    当我们在dict 中传递覆盖时,键应该是MemberRolePermissionOverwrite 应该是值。在这种情况下,假设我们想要保留所有默认类别权限但添加用户,我们将需要一个带有一项的dict:在user 参数中指定的Member 和相应的PermissionOverwrite授予访问权限

    首先,我们需要将您的用户转换为Member 对象。执行此操作的“简单”方法是使用discord.ext.commands.MemberConverter。这样做的缺点是它不仅通过username#discrim 搜索Member,还通过用户ID 和提及等其他方法搜索。如果您严格要求只能使用 username#discrim 格式,则需要解决此问题。我们还想检查是否找到了用户:

    try:
        member = discord.ext.commands.MemberConverter().convert(ctx, user)
    except discord.ext.commands.MemberNotFound:
        await ctx.send("Member not found.")
    

    现在,使用我们的成员对象,我们可以创建dictPermissionOverwrites。然后,我们可以创建我们的文本通道:

    overwrites = {member: discord.PermissionOverwrite(read_messages=True)}
    await ctx.guild.create_text_channel(firstName + ' ' + lastName, category=cat, overwrites=overwrites)
    

    现在应该使用传递的覆盖创建通道(即允许用户读取访问权限)。

    【讨论】:

      猜你喜欢
      • 2017-03-18
      • 2021-07-28
      • 1970-01-01
      • 2021-02-18
      • 2021-03-24
      • 2020-10-04
      • 1970-01-01
      • 2021-01-29
      • 2020-07-23
      相关资源
      最近更新 更多