Search code examples
pythondiscord.pyattributeerrorcoroutine

Discord.py command that deletes messages doesn't work


I'm trying to make a command that deletes a number of messages I want, but it doesn't work.

I got this error:

'coroutine' object has no attribute 'delete'.

if message.content.startswith("!נקה"):
    delete_count = 0
    try:
        value = message.content.split("!נקה ",1)[1] #gets the value of the messages I want to delete
        value = int(value)
        flag = 1
    except:
        flag = 0
        msg = await message.channel.send("שכחת לכתוב כמה הודעות למחוק.")
        await asyncio.sleep(5)
        await msg.delete()
    if flag == 1:
        for i in range(value-1):
            if True:
                with open("messagesList.txt", "r") as json_file:
                    messagesList = json.load(json_file) #loads a list of the id of messages
                message_id = messagesList[0]
                msg = message.channel.fetch_message(message_id)
                await msg.delete()
                delete_count += 1
                with open("messagesList.txt", "w") as json_file:
                    json.dump(messagesList, json_file)
            else:
                print("", end = "")
        if delete_count != 0:
            message = await message.channel.send(f"{delete_count}הודעות נמחקו בהצלחה.") #prints the messages successfully delete
        await asyncio.sleep(3) #wait 3 seconds
        await message.delete()

Solution

  • Are you trying to create something like a purge command? If you want to simply delete some amount of messages from the channel (without other operations), then try this:

    @client.command()
    async def clear(ctx, amount = 5): # you can set the default amount of messages that will be deleted (if you didn't specify the amount while running the command)
        deleted = await ctx.channel.purge(limit=amount + 1) # adding one to remove "clear" command too
        await ctx.send(f"Deleted {len(deleted)} messages") # sends how many messages were deleted
    

    Commands in docs