user16717447
user16717447

Reputation: 25

How to search and print discord chat history with discord.py?

So, I have a code that on receiving a message it will print it to the python terminal, but I want to be able to see previous messages as this code will only show messages sent while the code is running. I was thinking of getting the history printed in the startup section (async def on_ready():) but wasn't sure how. Thanks for your help.

@client.event
async def on_message(message):
  print(f"{message.guild.name}: {message.channel.name}\n{message.author.name}: {message.content}")

Upvotes: 1

Views: 2786

Answers (1)

Dominik
Dominik

Reputation: 3592

I've put together a way for you to query the last x messages in a channel of your choice with one command. For an event you have to change this accordingly or look at example two of me.

Example 1:

@client.command() / @bot.command() / @commands.command()
async def history(ctx):
    messages = await ctx.channel.history(limit=YourLimit).flatten() # Get the history of the channel where the command was invoked
    for message in messages: # Get only the messages and not any extra information
        print(message.content, sep="\n") # Print the messages and show each in a new line

If you want to use this in an on_ready event you have to rewrite the command a bit, it could look like

Example 2:

@client.event / @bot.event / @commands.Cog.listener()
async def on_ready():
    channel = client.get_channel(ChannelID) # A channel ID must be entered here
    messages = await channel.history(limit=YourLimit).flatten()
    for message in messages:
        print(message.content, sep="\n")

Upvotes: 3

Related Questions