discord.py 重写 | 如何等待作者消息?

xup*_*aii 3 python python-3.x discord.py discord.py-rewrite

我正在发出一个等待用户回复机器人的命令,但我希望机器人只接受作者的回复。

@client.command(name='numgame',
            brief='Guess a number between 1 and 100',
            pass_context=True)
async def numgame(context):
number = random.randint(1,100)
guess = 4
while guess != 0:
    await context.send('Pick a number between 1 and 100')
    msg = await client.wait_for('message', check=check, timeout=30)
    attempt = int(msg.content)
    if attempt > number:
        await context.send(str(guess) + ' guesses left...')
        await asyncio.sleep(1)
        await context.send('Try going lower')
        await asyncio.sleep(1)
        guess -= 1
    elif attempt < number:
        await context.send(str(guess) + ' guesses left...')
        await asyncio.sleep(1)
        await context.send('Try going higher')
        await asyncio.sleep(1)
        guess -=1
    elif attempt == number:
        await context.send('You guessed it! Good job!')
        break
Run Code Online (Sandbox Code Playgroud)

我的问题是任何人都可以响应“选择一个号码”,而我只希望启动命令的人能够响应。

我不太确定该尝试什么,但我认为这可能与争论有关。但是,我不知道从哪里开始,因此将不胜感激!万分感谢。

Pat*_*ugh 6

你需要重写你的,check以便它知道作者是谁。一种方法是使用闭包。假设您有一张现有支票

def check(message):
    return message.content == "Hello"
Run Code Online (Sandbox Code Playgroud)

您可以将其替换为一个函数,该函数生成与您要检查的作者等效的检查函数注入其中

def check(author):
    def inner_check(message):
        return message.author == author and message.content == "Hello"
    return inner_check
Run Code Online (Sandbox Code Playgroud)

然后,您将通过wait_for使用适当的参数调用外部检查来传递内部检查:

msg = await client.wait_for('message', check=check(context.author), timeout=30)
Run Code Online (Sandbox Code Playgroud)

对于您的检查,这将是

def check(author):
    def inner_check(message): 
        if message.author != author:
            return False
        try: 
            int(message.content) 
            return True 
        except ValueError: 
            return False
    return inner_check
Run Code Online (Sandbox Code Playgroud)