'Have the bot delete previous message sent by the bot in channel, not just the executed command by the user
So I want the bot when sending a message in a channel, to delete the previous message sent by the bot. I know ctx.message.delete removes the previous users message, but I'd like to remove the previous bot's message so it doesn't get cluttered. If anyone could help I'd appreciate it
--Example--
@commands.command()
@commands.has_permissions(administrator=True)
async def cmds(self, ctx):
await ctx.channel.send("Sending Message")
await ctx.message.delete()
Solution 1:[1]
You can use channel.history() to iterate through the message history of a channel, given that you have message history permissions.
Then, it's possible to filter out what message you want to delete. In the code below, it checks that the message is not the one that was just sent, that the message is sent by the bot, and that it contains some kind of specific content.
@client.command(name='delete')
async def delete(ctx):
this_message = await ctx.send('hi, this message might be deleted')
try:
await ctx.message.delete()
async for msg in ctx.channel.history(limit=5): # adjust to your liking
if msg.id != this_message.id and msg.author.id == client.user.id and 'this message might be deleted' in msg.content: # you can change what to filter, or even use regex
await msg.delete()
break # only delete 1
except discord.errors.Forbidden:
# do something eg print out an error message
pass
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Jin |
