Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

python - discord.py rewrite | How to wait for author message?

I am making a command which waits for a user to reply to the bot, but I would like the bot to only accept the author's reply.

@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

My issue is that anyone can respond to "Pick a number," whereas I would only like the person who started the command to be able to respond.

I am not too sure what to try, but I think it may have something to do with arguments. I have no idea where to begin, though, so a solution would be appreciated! Thanks a ton.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need rewrite your check so that it knows who the author is. One way of doing this is to use a closure. Let's say you have an existing check

def check(message):
    return message.content == "Hello"

You can replace this with a function that generates equivalent check functions with the author you want to check for injected into them

def check(author):
    def inner_check(message):
        return message.author == author and message.content == "Hello"
    return inner_check

Then you would pass the inner check to wait_for by calling the outer check with the appropriate argument:

msg = await client.wait_for('message', check=check(context.author), timeout=30)

For your check this would be

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...