Search code examples
python-3.xpycharmdiscord.py

Input Messages in Discord.py


I'm trying to find a way to program my bot to clear a specific amount of messages in a channel. However, I do not know how to get my bot to run it's code based on the user's input data. For example, let's say I'm a user who wants to clear a specific amount of messages, like let's say 15 messages. I want my bot to then clear 15 messages exactly, no more, no less. How do I do that?

    if message.content == "{clear":
    await message.channel.send("Okay")
    await message.channel.send("How many messages should I clear my dear sir?")

This is legit all I got lmao. I'm sorry that I'm such a disappointment to this community ;(


Solution

  • Using a on_message event, you'd have to use the startswith mehtod and create a amount variable which takes your message content without {clear as a value:

    if message.content.startswith("{clear"):
        amount = int(message.content[7:])
        await message.channel.purge(limit=amount+1)
    

    However, I don't recommend using on_message events to create commands. You could use the commands framework of discord.py. It will be much easier for you to create commands.
    A quick example:

    from discord.ext import commands
    
    bot = commands.Bot(command_prefix='{')
    
    @bot.event
    async def on_ready():
        print("Bot's ready to go")
    
    @bot.command(name="clear")
    async def clear(ctx, amount: int):
        await ctx.channel.purge(limit=amount+1)
    
    bot.run("Your token")
    

    ctx will allow you to access the message author, channel, guild, ... and will allow you to call methods such as send, ...