如何取消用户?

问题描述 投票:2回答:2

我知道如何禁止成员,我知道如何踢他们,但我不知道如何取消他们。我有以下代码输出错误:

discord.ext.commands.errors.CommandInvokeError:命令引发异常:AttributeError:'generator'对象没有属性'id'

码:

@bot.command(pass_context=True)
@commands.has_role("Moderator")
async def unban2(ctx):
    mesg = ctx.message.content[8:]
    banned = client.get_user_info(mesg)
    await bot.unban(ctx.message.server, banned)
    await bot.say("Unbanned!")
python python-3.x discord discord.py
2个回答
1
投票

unban用户,你需要他们的user object。你似乎在做的方式是在命令中传递user_id,然后根据它创建用户对象。你也可以使用下面解释的get_bans()来做,但我会先回答你的问题。

在命令中传递user_id

在您的代码中,mseg是user_id,banned是用户对象。

mesg = ctx.message.content[8:]
banned = await client.get_user_info(mesg)

编辑:正如squaswin指出的那样,你需要等待get_user_info()

您将user_id定义为ctx.message.content[8:],在这种情况下,您的消息中的文本是从第8个字符开始,第一个字符为0。

根据您的代码,以下内容应该有效:

(以下数字只是为了显示角色位置)

!unban2 148978391295820384
012345678...

这样做的问题是如果你的命令名或前缀改变了长度,那么你必须改变ctx.message.content[8:]中的索引以与你的消息中的user_id对齐。

更好的方法是将user_id作为参数传递给您的命令:

async def unban(ctx, user_id):
    banned = await client.get_user_info(user_id)

现在你可以直接使用它与client.get_user_info()

使用get_bans()

您可以使用get_bans()获取禁用用户列表,然后使用该列表获取有效的用户对象。例如:

async def unban(ctx):
    ban_list = await self.bot.get_bans(ctx.message.server)

    # Show banned users
    await bot.say("Ban list:\n{}".format("\n".join([user.name for user in ban_list])))

    # Unban last banned user
    if not ban_list:
        await bot.say("Ban list is empty.")
        return
    try:
        await bot.unban(ctx.message.server, ban_list[-1])
        await bot.say("Unbanned user: `{}`".format(ban_list[-1].name))
    except discord.Forbidden:
        await bot.say("I do not have permission to unban.")
        return
    except discord.HTTPException:
        await bot.say("Unban failed.")
        return

要将其转换为一组有效的命令,您可以创建一个命令来显示被禁用户的索引列表,以及另一个根据列表索引取消用户的命令。


1
投票

get_user_info是一个协程。这意味着它必须以与awaitunban相同的方式进行sayed。 根据经验,除非您实际使用生成器,否则您获得的任何生成器错误都可能是由于没有等待协程。

banned = await bot.get_user_info(mesg)

哦,并且在文档中写的是这个函数可能会抛出错误,因此可能值得确保没有任何问题。

try:
    banned = await bot.get_user_info(mesg)
except discord.errors.NotFound:
    await bot.say("User not found")
© www.soinside.com 2019 - 2024. All rights reserved.