Search code examples
pythondiscordfetchdiscord.pymessage

How to fetch messages using discord.py


I have created a piece of code that used to be a snipe function to a fetch function I assume snipe and fetch are basically the opposite of each other and my theory seems to be true! However that is not the case or why I am creating this question, I am having issues with my messages not being fetched after I run my !fetch command, there is no outcome which is supposed to be a embed that displays the content/message.

Concern/question

My code does not send an embed after the !fetch command is ran, there is no error listed within the console/terminal. However, when a message is sent within the channel the embed information is logged/shown within the console (Discord name, tag, id, guild id, guild name etc)! I want to fetch messages from a channel and print the messages when the command is ran.

Code

import discord
from discord.ext import commands
from tokens import token, CHANNEL_ID

client = commands.Bot(command_prefix='!')
client.sniped_message = None

@client.event
async def on_ready():
    print("Your bot is ready.")

@client.event
async def on_message(message):
    # Make sure it's in the watched channel, and not one of the bot's own
    # messages.
    if message.channel.id == CHANNEL_ID and message.author != client.user:
        print(f'Fetched message: {message}')
        client.sniped_message = message

@client.command()
async def fetch(ctx):
    # Only respond to the command in the watched channel.
    if ctx.channel.id != CHANNEL_ID:
        return

    if client.sniped_message is None:
        await ctx.channel.send("Couldn't find a message to fetch!")
        return

    message = client.sniped_message

    embed = discord.Embed(
        description=message.content,
        color=discord.Color.purple(),
        timestamp=message.created_at
    )
    embed.set_author(
        name=f"{message.author.name}#{message.author.discriminator}",
        icon_url=message.author.avatar_url
    )
    embed.set_footer(text=f"Message sent in: #{message.channel.name}")

    await ctx.channel.send(embed=embed)

client.run(token)

I'm not really sure if the sniped messages have a impact on the code. Also, this code was shared from my friend, who received helped with his snipe function.* Thanks!


Solution

  • From the documentation:

    Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message.

    So you just have to add await client.process_commands(message) at the end of on_message