Skip to content

Commit 85ecb11

Browse files
authored
Added EscapeText function
1 parent b6df6c2 commit 85ecb11

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

bot.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,3 +1065,30 @@ func (bot *BotAPI) SetMyCommands(commands []BotCommand) error {
10651065
}
10661066
return nil
10671067
}
1068+
1069+
// EscapeText takes an input text and escape Telegram markup symbols.
1070+
// In this way we can send a text without being afraid of having to escape the characters manually.
1071+
// Note that you don't have to include the formatting style in the input text, or it will be escaped too.
1072+
//
1073+
// parseMode is the text formatting mode (ModeMarkdown, ModeMarkdownV2 or ModeHTML)
1074+
// text is the input string that will be escaped
1075+
func (*BotAPI) EscapeText(parseMode string, text string) string {
1076+
var replacer *strings.Replacer
1077+
1078+
if parseMode == ModeHTML {
1079+
replacer = strings.NewReplacer("<", "&lt;", ">", "&gt;", "&", "&amp;")
1080+
} else if parseMode == ModeMarkdown {
1081+
replacer = strings.NewReplacer("_", "\\_", "*", "\\*", "`", "\\`", "[", "\\[")
1082+
} else if parseMode == ModeMarkdownV2 {
1083+
replacer = strings.NewReplacer(
1084+
"_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(",
1085+
"\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>",
1086+
"#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|",
1087+
"\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!",
1088+
)
1089+
} else {
1090+
return ""
1091+
}
1092+
1093+
return replacer.Replace(text)
1094+
}

0 commit comments

Comments
 (0)