Jack Thorn
Jack Thorn

Reputation: 67

Discord.py logging messages

I've got this code, which when I type !snapshot should log the last 100 messages in the channel, and make them into a text file:

snapshot_channel = (my snapshot channel ID)

@commands.has_permissions(administrator=True)
@bot.command()
async def snapshot(ctx):
    channel = bot.get_channel(snapshot_channel)
    await ctx.message.delete()
    messages = message in ctx.history(limit=100)
    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="snapshot.txt")
    await channel.send("Snapshot requested has completed.")
    await channel.send(file=file)

I've got BytesIO imported, and it works fine for a different command which purges messages and logs them, but this code which should just make a log and then send it in the channel doesn't work. Please can you send me what it should look like for it to work. Thanks!

Upvotes: 0

Views: 975

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

TextChannel.history is an async generator, you're not using it properly

messages = await ctx.channel.history(limit=100).flatten()
numbers = "\n".join([f"{message.author}: {message.clean_content}" for message in messages])

Another option would be

numbers = ""
async for message in ctx.channel.history(limit=100):
    numbers += f"{message.author}: {message.clean_content}"

Upvotes: 1

Related Questions