How to delete the bot's previous message on discord.py

Viewed 662

I have seen this command

@bot.command()
async def disappear(ctx):
    msg = await ctx.send("Hey!")
    await msg.delete(delay=1)

However, I'm trying to delete the "msg" in some other function. To be precise, this is my code

@bot.command()
async def disappear(ctx):
    msg = await ctx.send("Hey!")
    await msg.delete(delay=1)

@bot.command()
async def somethingelse(ctx):
    await msg.delete(delay=1)

which gives me an error

 NameError: name 'msg' is not defined

So i wanted to know if there is any method where it is possible to delete the bot's previous message by the bot itself.

2 Answers

You could try this:

prev_msg = None

@bot.command()
async def deleteprevmsg(ctx):
    global prev_msg

    try:
        await prev_msg.delete(delay = 1)
    except:
        prev_msg = await ctx.send("No previous message found")

And put prev_msg = before every await ctx.send(). Remember to global prev_msg in every function that uses it.

If you don't want to use globals, you can get last message sent by your bot in that channel then delete it.

@client.command()
async def somethingelse(ctx):
    channel = client.get_channel(123456789123456)  # ID of channel
    msg = await channel.history().get(author__id=123456789123456)  # ID of bot
    await msg.delete(delay=1)
    print(f"Deleted message: {msg.id}")

channel.history()

Related