简体   繁体   中英

How do i delete the previous messages that my discord bot sent in a specific channel?

I'm trying to make a discord bot that sends a message in a specific channel for telling users when my Minecraft server is on or off. I just need to send 2 embeds one for starting and another for turning off like this:

在此处输入图像描述

I'm trying to delete the old messages the bot has sent but I don't know how.

import discord
import sys
import os
from datetime import datetime
now = datetime.now()
Ntime = now.strftime("%H:%M:%S")
txtStart = ()
client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    channel = client.get_channel(800317242910834699)
    embed= discord.Embed(title="[ Server Status ]", description="Running...", color=discord.Color.green())
    embed.add_field(name="success At :", value=Ntime, inline=True)
    file = discord.File(os.path.join("D:\Scripts\Discord/ServerStarted.gif"), filename="ServerStarted.gif")
    embed.set_thumbnail(url="attachment://ServerStarted.gif")
    message = await channel.send(file=file, embed=embed)

    embed= discord.Embed(title="[ Server Status ]", description="shutting down...", color=discord.Color.red())
    embed.add_field(name="success At :", value=Ntime, inline=True)
    file = discord.File(os.path.join("D:\Scripts\Discord/ServerStoped.gif"), filename="ServerStoped.gif")
    embed.set_thumbnail(url="attachment://ServerStoped.gif")
    await channel.send(file=file, embed=embed)

You can use the TextChannel.purge method:

await channel.purge(limit=1)

Remember to send the message afterwards , not beforehand .

Note that this method will delete the oldest message in the channel, if you want to delete the latest message sent by the bot you can use use a check function:

def is_me(m):
    return m.author == client.user

await channel.purge(limit=1, check=is_me)

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM