首页 > 解决方案 > 如何在不和谐的机器人 python 上添加权限限制

问题描述

我设置了 Discord Bot,但目前任何人都可以运行删除消息的清理命令,但我只希望服务器上具有管理员权限的人能够运行它(如果有人也可以告诉我如何删除一条消息)太好了,它是清理命令中的注释),我现在的代码是:

@client.event
async def on_message(message):
    # print message content
    print(message.content)
    # if the message came from the bot ignore it
    if message.author == client.user:
        return
    # if the message starts with "!repeat" then say the message in chat
    if message.content.startswith("!repeat"):
        sentmessage = message.content.replace("!repeat", "")
        await message.channel.send(sentmessage)

    if "hello" in message.content.lower():
        await message.channel.send("Hello!")

    if message.content.startswith("!cleanup"):
        num2c = 0
        num2c = int(message.content.replace("!cleanup", ""))+1
        print(num2c)
        await message.channel.purge(limit=num2c)
        num2c = num2c-1
        cleanmessage = str("Cleared  "+str(num2c)+" Messages.")
        await message.channel.send(cleanmessage)
        t.sleep(2)
        #needs to delete the message again afterwards 

标签: pythondiscorddiscord.py

解决方案


if not message.author.guild_permissions.administrator:
    return await message.channel.send("You do not have permission to run this command!")

但是,我强烈建议使用命令扩展,它可以更轻松地为您处理这个问题。此外,您似乎正在使用time.sleep(). 这是阻塞的,并且不适用于您的异步代码,它将导致机器人基本上“冻结”,并且不响应任何其他内容。相反,您应该使用asyncio.sleep(),这是非阻塞的。要删除您在一定时间后发送的消息,您只需传递delete_after=number_of_secondssend().


推荐阅读