Discord.py - 如何在没有 ctx 或成员的情况下踢用户? - 解决方案在这里

时间:2021-05-24 15:51:21

标签: python discord discord.py

@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()

当我尝试运行机器人时,它给了我错误:

AttributeError: 'User' 对象没有属性 'kick

我尝试查看 discord 文档但该命令不起作用,然后我尝试搜索它但找不到任何内容。

1 个答案:

答案 0 :(得分:1)

不要混淆 usermember 对象!成员可以被踢,因为根据定义,他们是公会的成员。 User 只是一个普通的 Discord 用户,所以没有什么可踢的。为了在没有事件处理程序提供的对象的情况下从公会中踢出成员,您需要像这样手动创建它们

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

其中 <> 括号内的内容显然必须替换为真实的 id。


如果公会或成员没有被您的机器人缓存,您将需要取而代之

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

然后您可以使用此信息踢会员

@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()

如果您不确定提取函数是否总是返回对象,您还可以检查它们是否不是 None 以避免任何错误

@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()