我正在使用該discord.py庫構建一個 Discord 機器人。如果需要,庫使用該on_message(ctx)事件讓我們修改訊息。我想要做的是洗掉格式并將用戶提及替換為 Discord 名稱。訊息文本如下所示:
<@!34565734654367046435> <@!34565734645354367046435> are you here?
在ctx變數中,我可以從中獲取作為User物件的提及,ctx.mentions并且可以獲取每個提到的用戶的名稱和ID。
我想<@!34565734654367046435>用用戶名替換。結果是這樣的:
Name1 Name2 are you here?
這是我到目前為止所擁有的,但似乎不起作用。
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)
如果我在不做任何其他事情member.id的member.name情況下列印和,我會得到預期值。如何更新此 for 回圈中的字串?
uj5u.com熱心網友回復:
該replace函式回傳一個新字串,它不會就地編輯現有字串。如果您將回圈編輯為:
remove_formatting = utils.remove_markdown(context.content)
for member in context.mentions:
remove_formatting = remove_formatting.replace(f'<@!{member.id}>', member.name)
它應該作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373411.html
上一篇:KotlinCollections中的Any與NestedConcrete型別
下一篇:函式中的元組比較
