To retrieve a message by ID using a Discord Python bot, you can utilize the get_channel()
and fetch_message()
methods from the discord.py
library. Here’s an example:
import discord
# Create a bot instance
bot = discord.Client()
@bot.event
async def on_ready():
print('Bot is ready.')
@bot.event
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(message.channel.id)
try:
# Fetch the message using the message ID
fetched_message = await channel.fetch_message(int(message_id))
print(fetched_message.content)
except discord.NotFound:
print('Message not found.')
# Run the bot
bot.run('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.
+ There are no comments
Add yours