Search code examples
pythondiscordpycord

delete replied message pycord


how can I make my bot delete the message I've replied in discord.py? I have only code for standard clear command

@commands.has_permissions(manage_messages=True)
@bot.slash_command(description="Clears X messages.")
@discord.option("num", description="amount of messages")
@discord.option("target", description="from specific member")
async def clear(ctx, num: int, target: discord.Member=None):
    if num > 500 or num < 0:
        return await ctx.send("Invalid amount. Maximum is 500.")
    def msgcheck(amsg):
        if target:
           return amsg.author.id == target.id
        return True
    deleted = await ctx.channel.purge(limit=num, check=msgcheck)
    EmbClear = discord.Embed(title=":white_check_mark:Success!", description=f':thumbsup: Deleted **{len(deleted)}/{num}** messages.')
    await ctx.respond(embed=EmbClear, delete_after=5)

Solution

  • To be able to delete a message, you will need the Manage Messages permission. You can add this permission to your bot by opening your server's settings, going to the "permissions" tab and selecting Manage Messages from the available options. Once you've done that, you can delete a message with the following command: message.delete()

    You can use the delete() function on the Message object that you get back from replying. For example:

    @bot.event
    async def on_message(message):
        if message.content.startswith('!hello'):
            msg = await message.channel.send('Hello!')
            await msg.delete()