首页 > 解决方案 > Discord 清除命令仅限于所有者

问题描述

对不和谐机器人来说非常新。我希望将明确的命令限制为仅删除所有者的消息。如果调用命令的用户没有权限,我还想返回一条简单的消息“您没有使用此命令的权限”。我目前写了以下内容:

async def is_owner(ctx):

    return ctx.author.id == *my userid*

@client.command(pass_context=True)

@commands.check(is_owner)

async def clear(ctx, amount=5):

    channel = ctx.message.channel

    messages = []

    async for message in client.logs_from(channel, limit=int(amount)):

        messages.append(message)

    await client.delete_messages(messages)

    await client.say('Messages deleted')

虽然这确实起作用,但当前运行它的任何用户都能够执行该命令。不知道我错过了什么。我感谢任何纠正此问题的方向或建议。

def is_owner(ctx)修正后报错如下:

Ignoring exception in on_message
Traceback (most recent call last):
  File "F:\Python\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "F:\Python\lib\site-packages\discord\ext\commands\bot.py", line 857, in on_message
    yield from self.process_commands(message)
  File "F:\Python\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "F:\Python\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
    yield from self.prepare(ctx)
  File "F:\Python\lib\site-packages\discord\ext\commands\core.py", line 344, in prepare
    self._verify_checks(ctx)
  File "F:\Python\lib\site-packages\discord\ext\commands\core.py", line 338, in _verify_checks
    if not self.can_run(ctx):
  File "F:\Python\lib\site-packages\discord\ext\commands\core.py", line 438, in can_run
    return all(predicate(context) for predicate in predicates)
  File "F:\Python\lib\site-packages\discord\ext\commands\core.py", line 438, in <genexpr>
    return all(predicate(context) for predicate in predicates)
  File "f:\Discord Bots\First\bot.py", line 19, in is_owner
    return ctx.author.id == 'MY USERID'
AttributeError: 'Context' object has no attribute 'author'

标签: pythonbotsdiscorddiscord.py

解决方案


你可能会看到一个错误,RuntimeWarning: coroutine 'is_owner' was never awaited这意味着你给了一个协程,而它并不期望它,所以它的值被忽略了。

在异步分支上,commands.check仅适用于函数而不是协程。通过删除将协程更改is_owner为函数async

def is_owner(ctx):
    return ctx.message.author.id == *my userid*

推荐阅读