【问题标题】:How do I delete the messages a discord bot sent after a time interval? (discord.py)如何删除不和谐机器人在一段时间后发送的消息? (discord.py)
【发布时间】:2021-04-09 04:37:57
【问题描述】:

我正在使用 python 制作一个不和谐的机器人,它将每隔几秒发送一次特定的消息。所以它不会弄乱通道,我希望它删除它在 while 循环开始时最后发送的消息,用新消息替换消息。

我不知道该怎么做,任何帮助将不胜感激:)

@bot.command()
async def start(ctx):
    await ctx.send("Bot Started.")
    global bot_status
    bot_status = "running"
    while bot_status == "running":
        if bot_status == "stopped":
            break

        time.sleep(10)

        #delete
        #delete
        #delete

        await ctx.send("test")
        await ctx.send("test")
        await ctx.send("test")

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    .send() 函数有一个名为delete_after 的参数。您可以使用它在特定时间后删除消息。此外,您可以使用布尔值代替字符串。

    @bot.command()
    async def start(ctx):
        await ctx.send("Bot Started.")
        global bot_status
        bot_status = True
        while bot_status == True:
            if bot_status == False:
                break
            await ctx.send("test", delete_after=11)
            await ctx.send("test", delete_after=11)
            await ctx.send("test", delete_after=11)
            await asyncio.sleep(10)
    

    或者,您可以使用Message.delete。为此,您必须将发送的消息分配给变量。

    @bot.command()
    async def start(ctx):
        await ctx.send("Bot Started.")
        global bot_status
        bot_status = True
        while bot_status == True:
            if bot_status == False:
                break
            msg1 = await ctx.send("test")
            msg2 = await ctx.send("test")
            msg3 = await ctx.send("test")
            await asycnio.sleep(10)
            await msg1.delete()
            await msg2.delete()
            await msg3.delete()
    

    【讨论】:

    • 在异步函数中使用 time.sleep 会阻止机器人工作,因为它是一个阻塞函数。相反,请参考 asyncio 的 asyncio.sleep(x) 协程。
    • 对了,我忘了。
    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-12-23
    • 2020-11-08
    • 2019-06-02
    相关资源
    最近更新 更多