为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

撒科打诨 2023-05-16 16:56:16
在 discord.py 重写中,我试图制作一个投票系统。投票可能需要空格,比如!vote do this option    or do that option所以我想收到同一个用户的 2 条消息。起初,我使用@client.commmands(),但我认为使用on_message会更好,但任何一个都可以。我在想这个,@client.eventasync 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 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

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


保存用户发送的最后一条消息。

等待投票命令中的新选项

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


第 1 步:创建您的 !vote 命令


@client.commmands()

async def vote(ctx):

    # logic to do some things when someone votes

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


我们在 上使用超时wait_for,所以它不会永远持续下去,因为我们使用超时,我们需要捕获它引发的异常。这是通过 try, except 完成的。我们还使用 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事件。


查看完整回答
反对 回复 2023-05-16
  • 1 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信