Kexo
Kexo

Reputation: 15

Discord.py - How can i kick user without ctx or member? - Solution here

@pytest.mark.asyncio
async def timecheck():
    tm = time.localtime()
   
    if tm[6] == 6:
        user = await client.fetch_user(id)
        await user.kick(reason='Test')

@tasks.loop(seconds=60)
async def mainloop():
    asyncio.create_task(timecheck())


mainloop.start()

When i try to run bot it gives me error:

AttributeError: 'User' object has no attribute 'kick

I tried to look into discord documentation but the command didn't work, then i tried to search it but i couldn't find anything.

Upvotes: 0

Views: 301

Answers (1)

itzFlubby
itzFlubby

Reputation: 2289

Don't mix up the user and member objects! Members can be kicked, because they are, by definition, member of a guild. User represents just a normal Discord user, so nothing to kick there. In order to kick a member from a guild without having the objects given by an event-handler, you will need to create them manually like so

guild = client.get_guild(<guild-id>)
member = guild.get_user(<user-id>)

where the contents inside the <> brackets obviously have to be replaced with the real ids.


If guilds or members are however not cached by your bot, you will need to fetch them instead

guild = await client.fetch_guild(<guild-id>)
member = await guild.fetch_member(<user-id>)

You can then use this info to kick the member

@pytest.mark.asyncio
async def timecheck():
    tm = time.localtime()
   
    if tm[6] == 6:
        guild = await client.fetch_guild(guildID)
        member = await guild.fetch_member(userID)
        await member.kick(reason='Test')

@tasks.loop(seconds=60)
async def mainloop():
    asyncio.create_task(timecheck())


mainloop.start()

If you're not sure that the fetch functions will always return the object, you can also check if they aren't None to avoid any errors

@pytest.mark.asyncio
async def timecheck():
    tm = time.localtime()
   
    if tm[6] == 6:
        guild = await client.fetch_guild(guildID)
        if guild != None:
            member = await guild.fetch_member(userID)
            if member != None:
                await member.kick(reason='Test')

@tasks.loop(seconds=60)
async def mainloop():
    asyncio.create_task(timecheck())


mainloop.start()

Upvotes: 1

Related Questions