Discord.py file logging, change number of messages

Viewed 336

I've got this code that I use for discord channel logging. It basically gets the last 10,000 messages in a channel, and makes a .txt file with those messages in it, with the !log command. However, how would I make it so optionally users can type a number after !log, and it will log that number of previous messages? EG: "!log" on it's own logs the last 10,000 messages, but "!log 100" would log the last 100 messages. But I have no clue how to do that.

Here's my code:

@commands.has_any_role('Logger', 'logger')
@bot.command()
async def log(ctx):
    try:
        channel = ctx.message.channel
        await ctx.message.delete()
        await channel.send(ctx.message.author.mention+" Creating a log now. This may take up to 5 minutes, please be patient.")
        messages = await ctx.channel.history(limit=10000).flatten()
        numbers = "\n".join([f"{message.author}: {message.clean_content}" for message in messages])
        f = BytesIO(bytes(numbers, encoding="utf-8"))
        file = discord.File(fp=f, filename='Log.txt')
        await channel.send(ctx.message.author.mention+" Message logging has completed.")
        await channel.send(file=file)
    except:
        embed = discord.Embed(title="Error creating normal log:", description="The bot doesn't have necessary permissions to make this log type. Please confirm the bot has these permissions for this channel: View Channel, Read and Send Messages, Attatch Files (used for sending the log file), Manage Messages (used for deleting the command the user sends when making a log).", color=0xf44336)
        await channel.send(embed=embed)

Any help about how to make it so they can optionally provide a number, which would then log that amount, would help a lot. Thanks!

1 Answers
Related