Skip to content

Instantly share code, notes, and snippets.

@gillchristian
Last active May 28, 2023 13:55
Show Gist options
  • Save gillchristian/98d1d2cbb86a8a77f108980da2a4585f to your computer and use it in GitHub Desktop.
Save gillchristian/98d1d2cbb86a8a77f108980da2a4585f to your computer and use it in GitHub Desktop.
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