How to Retrieve a Message by ID Using a Discord Python Bot?

Estimated read time 2 min read

To retrieve a message by ID using a Discord Python bot, you can utilize the get_channel() and fetch_message() methods from the library. Here’s an example:

import discord

# Create a bot instance
bot = discord.Client()

async def on_ready():
    print('Bot is ready.')

async def on_message(message):
    if message.content.startswith('!get_message'):
        # Extract the message ID from the command
        command, message_id = message.content.split(' ')
        # Get the channel object using the channel ID
        channel = bot.get_channel(
            # Fetch the message using the message ID
            fetched_message = await channel.fetch_message(int(message_id))
        except discord.NotFound:
            print('Message not found.')

# Run the bot'YOUR_BOT_TOKEN')

In this example, the bot waits for a command starting with !get_message followed by a space and a message ID. It retrieves the channel object using bot.get_channel() and fetches the message using channel.fetch_message() with the provided message ID.

The await keyword is used to asynchronously fetch the message, as it may require an API call.

If the message is found, the bot prints the content of the fetched message. If the message is not found, it catches the discord.NotFound exception and prints “Message not found.”

Replace 'YOUR_BOT_TOKEN' with your own Discord bot token, which you can obtain by creating a bot application on the Discord Developer Portal.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply