How can I find the first message in a discord channel?

I want to be able to find the earliest message in a specific discord channel using python, not bound to a discord command.

I’ve tried using a discord bot but it seems those are mostly used for bot commands, so how would I be able to do this at any time?

I’ve tried the following:

import discord

client = Client(intents=discord.Intents.all())

async def getfirstmessage():
    channel = client.get_guild(guildid).get_channel(channelid)
    messages = [message async for message in channel.history(limit=1, oldest_first=True)]
    print(messages)

and i got this error:

RuntimeWarning: coroutine 'getfirstmessage' was never awaited getfirstmessage()

and when i try to add await in front of the ‘getfirstmessage’ function if get this error:

SyntaxError: 'await' outside function

Thanks in advance.

>Solution :

import discord
import asyncio

intents = discord.Intents.default()
intents.message_content = True  # Enable message content for intents

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'Logged in as {client.user.name}')
    await get_first_message()

async def get_first_message():
    guild_id = 1234567890  # Replace with your guild ID
    channel_id = 1234567890  # Replace with your channel ID

    guild = client.get_guild(guild_id)
    channel = guild.get_channel(channel_id)

    async for message in channel.history(limit=1, oldest_first=True):
        print(f'Earliest message: {message.content}')
        break  # Exit the loop after retrieving the first message

# Run the bot
loop = asyncio.get_event_loop()
loop.run_until_complete(client.start('YOUR_BOT_TOKEN'))  # Replace with your bot token
# Make sure to replace guild_id, channel_id, and 'YOUR_BOT_TOKEN' with your specific values.

Leave a Reply