#python #discord
#python #Discord
Вопрос:
Я пишу бота для discord, и есть команда ($ bone), в которой бот пишет следующее: «выберите число от 1 до 9», и после этого пользователь должен ответить, и вот как я могу прочитать строку, в которой он написал число?
Комментарии:
1. Что вы подразумеваете под «строкой»? Что вы пробовали до сих пор? Как выглядит ваш текущий код?
2. строка, в которую пользователь напишет любое число от 1 до 9
3.вы хотите
wait_for_message
discordpy.readthedocs.io/en/latest /…
Ответ №1:
Как упоминалось в комментариях, мы будем использовать сопрограмму с именем wait_for, которая ожидает таких событий, как message
: https://discordpy.readthedocs.io/en/latest/api.html#discord .Client.wait_for
Поскольку это те же события, с которыми мы могли бы подключиться bot.event
, мы сможем обработать возвращенное сообщение.
@bot.command()
async def bone(ctx):
await ctx.send("Select a number 1-9")
def my_check_func(message): #A checking function: When we return True, consider our message "passed".
if message.author == ctx.author: #Make sure we're only responding to the original invoker
return True
else:
return False
response = await bot.wait_for("message", check=my_check_func) #This waits for the first message event that passes the check function.
#This execution process now freezes until a message that passes that check is sent,
#but other bot interactions can still happen.
c = response.content #equal to message.content, because response IS a message
if c.isdigit() and 1 <= int(c) <= 9: #if our response is a number equal to 1, 9, or between those...
await ctx.send("You sent: {}".format(response.content))
else:
await ctx.send("That's not a number between 1 and 9!")
Реальный пример взаимодействия, чтобы доказать, что это работает:
Cook1
$bone
Tutbot
Select a number 1-9
Cook1
4
Tutbot
You sent: 4
Cook1
$bone
Tutbot
Select a number 1-9
Cook1
no
Tutbot
That's not a number between 1 and 9!