Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

python - Discord reprint message bot command

I'm working on a bot command that reprints the text of a message when the user replies to it and calls the command.

So far this is the code:

@bot.command(name='repeat_message', help='help me to understand bots')    
async def repeat_message(ctx):
key_details=ctx.message.reference
#missing line
await asyncio.gather(ctx.send(line))

In the above key_details will be the details of the old message, for example:

<MessageReference message_id=123 channel_id=123  guild_id=123>

Looking through the documentation I can't find a command that would allow me to get the original message. I would be suprised if one doesn't exist, if it doesn't can you think of a work around?

question from:https://stackoverflow.com/questions/65903983/discord-reprint-message-bot-command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the contents of a MessageReference with two ways.

First, you can use .cached_message to get the Message object, where you can get the contents by getting the .content property. If you were to do that, it would look like this:

key_details=ctx.message.reference
msg_refd = key_details.cached_message
msg_content = msg_refd.content # String that holds what the referenced message said

The only problem with using .cached_message is that it can only fetch from the bot's message cache, so if it's not in the cache, then it'll return None.

To mitigate, another solution you could use is using fetch_message(). This will guarantee a message object, but is slower (though likely by a marginal amount). If you were to use this function, your code would look something like this:

key_details=ctx.message.reference
msg_refd = await ctx.fetch_message(key_details.message_id)
msg_content = msg_refd.content # String that holds what the referenced message said

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...