我知道如何禁止成员,我知道如何踢他们,但我不知道如何取消他们。我有以下输出错误的代码:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'generator' object has no attribute '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!")
请您参考如下方法:
要 unban 用户,您需要他们的 user object 。您似乎这样做的方式是在您的命令中传递一个 user_id,然后基于它创建 user 对象。您也可以使用下面解释的 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:] ,在本例中是消息中从 8th 字符开始的文本,第一个字符为 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
要将其变成一组有效的命令,您可以创建一个命令来显示被禁用户的索引列表,以及另一个命令来根据列表索引取消对用户的禁止。
