如何为 message.delete() 添加延迟?

How to add a delay to message.delete()?

如果在指定频道之外的任何其他频道中发出命令,bot 会删除命令消息并通知用户他们只能在帮助频道中使用命令。我希望机器人在大约 5 秒后删除它自己的消息。

这就是我所拥有的和正在尝试的,API 文档说要在 await message.delete() 中添加一个 delay=,但是当我这样做时,消息仍然存在。即使没有它说消息不存在,这是一条未知消息,有一次我几乎删除了整个通用频道。

代码:

if message.content.startswith('!commands'):
        channel = client.get_channel(525412770062139402)
        if message.channel is not channel:
            await message.delete()
            channel = message.channel
            await channel.send("{0.mention} Please use bot commands in the #help channel.".format(message.author))
            channel = message.channel
            await message.delete()

这告诉我这是一条未知消息。我将如何检索机器人的最后一条消息?如果我没有理解错的话,机器人正在尝试检索已删除的消息,而不是它自己的消息。

您可以使用定时睡眠功能:

import time
time.sleep(5)

TextChannel.send(...) returns 一个 Message 所以如果你想存储你的机器人刚刚发送的消息,你可以这样做:

botSentMessage = await channel.send("some message")

最后,要添加延迟,您可以使用 await asyncio.sleep(delayInSeconds)

你的最终结果应该是这样的:

if message.content.startswith('!commands'):
        channel = client.get_channel(525412770062139402)
        if message.channel is not channel:
            await message.delete()
            channel = message.channel

            # Gets the message the bots just sent.
            botsMessage = await channel.send("{0.mention} Please use bot commands in the #help channel.".format(message.author))
            # Waits for 3 seconds before continuing to the next line of code
            await asyncio.sleep(3)
            await botsMessage.delete()

您也可以这样做:

await ctx.send("My message", delete_after = 5)

delete_after参数会在倒计时结束时自动删除已发送的消息。 Documentation