【问题标题】:How to take the next line as input for discord bot如何将下一行作为不和谐机器人的输入
【发布时间】:2021-02-15 05:42:12
【问题描述】:

我正在制作一个不和谐的机器人,在用户键入某个命令后,我希望用户的下一行成为变量的输入。

所以:

import discord
@client.event

async def on_ready():
print('{0.user}'.format(client)+'logged in')
@client.event
async def on_message(message):

if message.author == client.user:
   return
if message.content.startswith('Lets play hangman'):
    message.channel.send('Please Guess a letter')
    userGuess = ### and here put whatever the user writes next (so no matter what is contained inside)

我唯一能找到的是,如果消息包含特定内容,那么当机器人执行某些操作时,但在这种情况下,无论如何我只想将整个消息作为输入。

【问题讨论】:

    标签: python discord


    【解决方案1】:

    我不确定这是否是您要查找的内容,但简要查看 discord.py documentation 它提供了如何等待用户回复的示例。

    @client.event
    async def on_message(message):
        if message.content.startswith('$greet'):
            channel = message.channel
            await channel.send('Say hello!')
    
            def check(m):
                return m.content == 'hello' and m.channel == channel
    
            msg = await client.wait_for('message', check=check)
            await channel.send('Hello {.author}!'.format(msg))
    

    基本上,如果命令以$greet 开头,那么机器人会发回Say hello!。然后,它会等到用户回复。

    我建议取变量msg 的值,该值等于用户回复的消息并将其设置为userGuess

    所以:

    userGuess = await client.wait_for('message') 就是答案。

    但这就是整个消息对象,只获取消息本身,然后在其后附加.content

    函数代码:

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return
        if message.content.startswith('Lets play hangman'):
            await message.channel.send('Please Guess a letter')
            userGuess =  await client.wait_for('message')
            //prints the message content into console
            print(userGuess.content)
    

    【讨论】:

    • 因此,如果用户通过说出一个语句来激活代码,我希望机器人将用户接下来编写的内容作为变量的输入。例如:用户激活代码机器人写入消息并等待用户响应用户在机器人存储下一个写入的内容
    • 是的,我现在已经修改了代码,希望它现在可以工作。 print 语句将用户的响应打印到控制台中。
    • 是的,这很有效,不幸的是我不理解代码,或者至少不了解 await 和 .content,因为我对不和谐机器人和一般编码非常陌生,await 和 .content 有什么意义。内容以及为什么我把它拿走后它会停止工作。
    • 查看this 了解更多信息@await/async 是如何工作的。至于.content,那是因为bot得到的message实际上是消息对象。我的意思是它包含消息内容以及有关它的元数据,例如发送时间、作者。但是您只需要content 属性,或者用户实际输入的内容,因此.content 是必要的。
    猜你喜欢
    • 2020-09-25
    • 2021-07-27
    • 2021-03-05
    • 1970-01-01
    • 2021-10-14
    • 2021-08-27
    • 2021-01-17
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多