python - 如何在不和谐的机器人 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
解决方案
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_seconds
给send()
.
推荐阅读
- c++ - 使用文件系统和 fstream 标准库时出现编译错误
- c# - 通过代码自定义开箱即用的功能区
- cocos2d-x - 在 Cocos Creator 中加载 CCBi 文件
- python - 我正在做我的 NEA 骰子游戏,但我无法将回合数加起来
- java - Java Swing 如何在我的自定义 ColorChooserPanel 中创建颜色样本?
- python - 列表中某个连续重复值的最大数量
- html - 位置粘性与方向 rtl 不起作用
- openwhisk - Windows 10 CLI 上的 wskdeploy 未识别错误
- java - 使用 AWSCredentials 构建 AmazonS3Client 实例的首选方式
- javascript - 找不到模块“集合/双端队列”