I am building a Discord bot using the discord.py
library. The library uses the on_message(ctx)
event to let us modify a message if we want to. What I would like to do is to remove the formatting and replace the user mentions with the Discord names. The text of the message looks like this:
<@!34565734654367046435> <@!34565734645354367046435> are you here?
In the ctx
variable I can get the mentions as User
objects from ctx.mentions
and I can get the NAME and the ID of each mentioned user.
I'd like to replace the <@!34565734654367046435>
with the name of the user. The result to be something like:
Name1 Name2 are you here?
This is what I have so far but it does not seem to work.
remove_formatting = utils.remove_markdown(context.content)
print(remove_formatting) # prints the very first code styled line in this question
for member in context.mentions:
remove_formatting.replace(f'<@!{member.id}>', member.name)
If I print the member.id
and the member.name
without doing anything else, I get the expected values. How do I update the string in this for loop?
CodePudding user response:
The replace
function returns a new string, it doesn't edit the existing string in place. If you edit your loop to:
remove_formatting = utils.remove_markdown(context.content)
for member in context.mentions:
remove_formatting = remove_formatting.replace(f'<@!{member.id}>', member.name)
it should work.