Reputation: 11
I am trying to create a command for my Discord bot that will write the channel history to a .txt.
I have tried several different attempts using channel.history().flatten(). I'm sure there are significant issues with my code and I apologize for that. I am quite new to this and haven't entirely grasped the concepts. Thanks so much.
@client.command(name="history")
async def history():
channel_id = XXXXXXXXXXXXXXXX
messages = await channel.history(channel_id).flatten()
with open("channel_messages.txt", "a", encoding="utf-8") as f:
f.write(f"{messages}")
Upvotes: 0
Views: 3285
Reputation: 60944
you don't need to pass an id to TextChannel.history
@client.command()
async def history(ctx, limit: int = 100):
messages = await ctx.channel.history(limit=limit).flatten()
with open("channel_messages.txt", "a+", encoding="utf-8") as f:
print(*messages, sep="\n\n", file=f)
Other changes: removed the name=
because it uses the name of the callback by default, every command needs an invocation context to be passed, I added a limit
argument so you can control how many messages to get, and I changed the write
to a print
with a file
argument, because I think that make it easier to control what gets written to the file.
Upvotes: 1