【问题标题】:How to add a delay to message.delete()?如何向 message.delete() 添加延迟?
【发布时间】:2019-12-15 01:08:30
【问题描述】:

如果在指定频道之外的任何其他频道中给出命令,机器人会删除命令消息并通知用户他们只能使用帮助频道中的命令。我希望机器人在大约 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()

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

【问题讨论】:

    标签: python discord python-3.7 discord.py discord.py-rewrite


    【解决方案1】:

    你也可以这样做:

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

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

    【讨论】:

      【解决方案2】:

      TextChannel.send(...) 也返回一个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()
      

      【讨论】:

      • 我明白你做了什么。再次感谢您
      【解决方案3】:

      可以使用定时休眠功能:

      import time
      time.sleep(5)
      

      【讨论】:

      • 这是阻塞的,最好使用asyncio.sleep()
      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 2014-01-04
      • 2017-10-29
      • 2011-09-20
      相关资源
      最近更新 更多