【问题标题】:(Discord.py) How to make bot delete his own message after some time?(Discord.py)如何让机器人在一段时间后删除自己的消息?
【发布时间】:2021-04-01 15:45:54
【问题描述】:

我在 Python 中有这段代码:

import discord
client = commands.Bot(command_prefix='!')

@client.event
async def on_voice_state_update(member):
    channel = client.get_channel(channels_id_where_i_want_to_send_message))
    response = f'Hello {member}!'
    await channel.send(response)

client.run('bots_token')

我希望机器人删除自己的消息。比如一分钟后,我该怎么做?

【问题讨论】:

    标签: python bots discord.py


    【解决方案1】:

    这不应该太复杂。希望对您有所帮助。

    import discord
    from discord.ext import commands
    import time
    import asyncio
    client = commands.Bot(command_prefix='!')
    
    @commands.command(name="test")
    async def test(ctx):
        message = 'Hi'
        msg = await ctx.send(message)
        await ctx.message.delete() # Deletes the users message
        await asyncio.sleep(5) # you want it to wait.
        await msg.delete() # Deletes the message the bot sends.
     
    client.add_command(test)
    client.run(' bot_token')
    

    【讨论】:

      【解决方案2】:

      在我们做任何事情之前,我们要导入 asyncio。这可以让我们在代码中等待设定的时间。

      import asyncio
      

      首先定义您发送的消息。这样我们就可以稍后再回来。

      msg = await channel.send(response)
      

      然后,我们可以使用 asyncio 等待一段时间。括号中的时间以秒为单位,因此一分钟为 60,两分钟为 120,依此类推。

      await asyncio.sleep(60)
      

      接下来,我们实际上删除了我们最初发送的消息。

      await msg.delete()
      

      因此,您的代码最终会看起来像这样:

      import discord
      import asyncio
      
      client = commands.Bot(command_prefix='!')
      
      @client.event
      async def on_voice_state_update(member, before, after):
          channel = client.get_channel(123...))
          response = f'Hello {member}!'
          msg = await channel.send(response) # defining msg
          await asyncio.sleep(60) # waiting 60 seconds
          await msg.delete() # Deleting msg
      

      您还可以在here 中阅读更多内容。希望这有帮助!

      【讨论】:

      • 我不得不将 py async def on_voice_state_update(member) 更改为 py async def on_voice_state_update(member, after, before) 因为它说:TypeError: on_voice_state_update() 需要 1 个位置参数,但给出了 3 个但现在一切正常,非常感谢!
      【解决方案3】:

      有比 Dean AmbrosDom 建议的更好的方法,您可以简单地将 kwarg delete_after 添加到 .send

      await ctx.send('whatever', delete_after=60.0)
      

      reference

      【讨论】:

        猜你喜欢
        • 2019-06-02
        • 2020-11-08
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        • 2021-06-11
        • 2022-01-06
        • 2021-04-09
        • 1970-01-01
        相关资源
        最近更新 更多