Last active
May 28, 2023 13:55
-
-
Save gillchristian/98d1d2cbb86a8a77f108980da2a4585f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn format_entities(text: String, entities: Vec<MessageEntityRef<'_>>) -> String { | |
let mut text = text; | |
// Raplace entities in reverse order to avoid messing up the indexes | |
for entity in entities.into_iter().rev() { | |
let start = entity.start(); | |
let end = entity.end(); | |
let entity_text = entity.text(); | |
let replacement = match entity.kind() { | |
MessageEntityKind::Bold => format!("**{}**", entity_text), | |
MessageEntityKind::Italic => format!("_{}_ ", entity_text), | |
MessageEntityKind::Strikethrough => format!("~{}~", entity_text), | |
MessageEntityKind::Code => format!("`{}`", entity_text), | |
MessageEntityKind::Email => format!("[{}](mailto:{})", entity_text, entity_text), | |
MessageEntityKind::Url => format!("[{}]({})", entity_text, entity_text), | |
MessageEntityKind::BotCommand => format!("`{}`", entity_text), | |
MessageEntityKind::Pre { | |
language: Some(lang), | |
} => format!("```{}\n{}```", lang, entity_text), | |
MessageEntityKind::Pre { language: None } => format!("```\n{}```", entity_text), | |
MessageEntityKind::TextLink { url } => format!("[{}]({})", entity_text, url.to_string()), | |
MessageEntityKind::TextMention { user } => format!("[{}]({})", entity_text, user.url()), | |
_ => entity_text.to_string(), | |
}; | |
text.replace_range(start..end, &replacement); | |
} | |
text | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment