問題描述
我正在發出等待用戶回復機器人的命令,但我希望機器人只接受作者的回復.
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.
推薦答案
你需要重寫你的 check
讓它知道作者是誰.一種方法是使用閉包.假設您有一張現有的支票
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
然后,您可以通過使用適當的參數調用外部檢查,將內部檢查傳遞給 wait_for
:
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)
為了您的檢查,這將是
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
這篇關于discord.py 如何使用 wait_for 等待作者消息?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!