How do I unblock a user?
I know how to ban members, I know
how to kick them, but I don’t know how to cancel them. I have the following code that outputs the error:
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: AttributeError: ‘generator’ object has no attribute ‘id’
Code:
@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!")
Solution
To unban users, you need their user object 。 The way you seem to do this is by passing a user_id in your command and then creating a user object based on it. You can also do it using get_bans() explained below, but I’ll answer your question first.
Pass the user_id in the command
In your code, mseg
is the user_id and banned
is the user object.
mesg = ctx.message.content[8:]
banned = await client.get_user_info(mesg)
EDIT: As squaswin points out, you need to wait for get_user_info().
You define user_id as ctx.message.content[8:]
, in this case the text in your message starting at 8th> character forward, with the first character being 0.
Depending on your code, the following should work:
(The numbers below are only meant to indicate character positions).
!unban2 148978391295820384
012345678...
The problem is that if your command name or prefix changes length, then you will have to change the index in ctx.message.content[8:]
to match the user_id in your message.
A better approach is to pass user_id as a parameter to your command:
async def unban(ctx, user_id):
banned = await client.get_user_info(user_id)
Now you can use it directly via client.get_user_info().
Use get_bans().
Instead, you can use get_bans() to get a list of banned users, and then use that list to get valid User object. For example:
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
To turn this into a valid set of commands, you can create one command to display an indexed list of banned users, and another command to unban users based on the list index.