Skip to content

Commit

Permalink
Merge pull request #388 from ErikPelli/master
Browse files Browse the repository at this point in the history
Escape Telegram formatting symbols
  • Loading branch information
Syfaro committed Nov 7, 2020
2 parents 19e61c7 + 7d4ae71 commit 54104a0
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -1065,3 +1065,31 @@ func (bot *BotAPI) SetMyCommands(commands []BotCommand) error {
}
return nil
}

// EscapeText takes an input text and escape Telegram markup symbols.
// In this way we can send a text without being afraid of having to escape the characters manually.
// Note that you don't have to include the formatting style in the input text, or it will be escaped too.
// If there is an error, an empty string will be returned.
//
// parseMode is the text formatting mode (ModeMarkdown, ModeMarkdownV2 or ModeHTML)
// text is the input string that will be escaped
func EscapeText(parseMode string, text string) string {
var replacer *strings.Replacer

if parseMode == ModeHTML {
replacer = strings.NewReplacer("<", "&lt;", ">", "&gt;", "&", "&amp;")
} else if parseMode == ModeMarkdown {
replacer = strings.NewReplacer("_", "\\_", "*", "\\*", "`", "\\`", "[", "\\[")
} else if parseMode == ModeMarkdownV2 {
replacer = strings.NewReplacer(
"_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(",
"\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>",
"#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|",
"\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!",
)
} else {
return ""
}

return replacer.Replace(text)
}

0 comments on commit 54104a0

Please sign in to comment.