discord.py如何再次从用户那里获取消息?

问题描述

在discord.py重写中,我试图建立一个投票系统。投票可能需要空格,例如

!vote do this option    or do that option

所以我想从同一用户那里收到2条消息。
起初,我使用@client.commmands(),但我认为使用on_message会更好,但是任何一个都可以。
我在想这个,

@client.event
async def on_message(ctx): #We only get ctx because it can contain spaces
    userid = ctx.author.id
    @client.event
    ....

所以我的问题是,它将使用任何功能来使您从同一用户获得2次内容,并且可以在@client.event中使用async def

有解决方案吗?谢谢。

解决方法

您可以通过两种方法实现所需的功能。

  • 保存用户发送的最后一封邮件。
  • 等待投票命令中的新选项

最后一点更好。我将解释如何做到这一点。

第1步:创建!vote命令

@client.commmands()
async def vote(ctx):
    # logic to do some things when someone votes

第2步:添加用于waits_for选项的逻辑

我们在wait_for上使用了超时,因此它不会永远持续下去,因为我们使用了超时,因此我们需要捕获它引发的异常。这是通过尝试完成的,除了。我们还使用while循环,因为这使我们能够接收尽可能多的选项。请注意,while循环中的条件可以更改。

@client.command()
async def vote(ctx):
    # logic to do some things when someone votes

    try:
        # While the user inputs options
        while True:
            await __handle_vote_option_message(ctx)
    except asyncio.TimeoutError:
        # The user did not respond in time.
        return

async def __handle_vote_option_message(ctx):
    timeout_ = 10
    message = await client.wait_for('message',check=lambda message: message.author == ctx.author,timeout=timeout_)
    if not __is_message_valid_vote_option(message):
        # logic to handle incorrect vote options
    else:
        # Whatever you want to do with the option the user provided.

def __is_message_valid_vote_option(message):
    # check if message is correct.
    return message.content.startswith("option")

在我看来,这种方式比用这种逻辑填充on_message事件要好得多。由于逻辑属于表决命令,而不是on_message事件。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...