Im trying to setup a clear/purge command for my discord.py bot. There are no errors but when I run the command, nothing happens

Viewed 1155

This the start of the code. Did I type something wrong in the code that doesn't make the command work?

import discord
import os
from keep_alive import keep_alive
from discord.ext import commands
import random

client = commands.Bot(command_prefix= '>')

@client.event
async def on_ready():
    print('The bot is online')
    await client.change_presence(
        activity=discord.Game('>help ┃ Created by ColeTMK'))

@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=6):
  await ctx.channel.purge(limit=amount)
1 Answers

I have explained properly how to do that. Using the coroutine it is possbile.

There seems to be no error in your code. I would just say create the command as I have mentioned below and try again.


I created a purge command first which has the following code:

@nucleobot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
    await ctx.message.delete()
    await asyncio.sleep(1)
    await ctx.channel.purge(limit=limit)
    purge_embed = discord.Embed(title='Purge [!purge]', description=f'Successfully purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
    purge_embed.set_footer(text=str(datetime.datetime.now()))
    await ctx.channel.send(embed=purge_embed, delete_after=True)

How does this code work?

  1. The command usage is deleted, i.e., !purge 10 would be deleted when sent into the chat.

  2. It would pause for 1 second due to await asyncio.sleep(1). You would need to import asyncio in order to use it. (You might know that already :D)

  3. The number of messages your entered are cleared from the channel using await ctx.message.delete(limit=limit) (This is a discord.py coroutine)

  4. purge_embed is the embed variable which is used to send the embed after the deletion. I have used datetime module to add the time of the command completion on the embed. (You need to import datetime as well, but only if you want to use it. If not then remove the footer code.)

This would make up your complete and working purge command. :D


Examples with images.

I created a new channel and added 10 messages with numbers from 1 to 10 as shown below:

Messages in Trail

Then I entered the command in the message box and it was like (I know it was not needed but never mind):

Command Entered

After I sent this message and the command was executed, the purge successful embed was posted by the bot:

Successful Purge


I was glad I could help. Any doubts of confusions are appreciated. Ask me anytime. :D

Thank You! :)

Related