DiscoveringCreation
DiscoveringCreation

Reputation: 43

In Discord.py, how can I use a message ID to store the message as a variable?

I'm trying to make something in discord.py that locates a message from a given message ID and then stores that message as a variable. I can't find anything else so far that can do this. My desired effect is to type in a message ID, store the message as a variable, change the text slightly, and then make the bot say the result.

Please go easy on me, I've only recently started with discord.py.

Upvotes: 1

Views: 621

Answers (1)

Coder N
Coder N

Reputation: 252

You can get a message from a message id by using ctx.fetch_message

Note that this method is a coroutine, meaning that it needs to be awaited.

Example

@bot.command()
async def getmsg(ctx, msgID: int): 
    try:
      msg = await ctx.fetch_message(msgID)
    except discord.errors.NotFound:
      # means that the messageID is invalid

This returns a discord.Message object

To get the message content you just need to access the content attribute of the object

msg_content = msg.content

This example uses the current text channel as the place to find the message

If you want to find a message in a whole server, it's a bit trickier since the fetch_message method is only callable from an abc.Messegeable object, which includes:

• TextChannel
• DMChannel
• GroupChannel
• User
• Member
• Context

So, to get a message from a whole guild,you should probably loop over the channels in a guild, and call the fetch_message on that channel.

Maybe something like this:

@bot.command()
async def getmsg(ctx, msgID: int):
  msg = None
  for channel in ctx.guild.text_channels:
    try:
       msg = await channel.fetch_message(msgID)
    except discord.errors.NotFound:
       continue
  if not msg:
    # means that the given messageId is invalid

After all this there is just one thing I want to add.

I strongly recommend that you use one of discord.py's forks since discord.py isn't maintained anymore.

Upvotes: 1

Related Questions