Skip to content

Commit 5330d78

Browse files
SyfaroArtem Abubakirov
authored andcommitted
Merge pull request go-telegram-bot-api#388 from ErikPelli/master
Escape Telegram formatting symbols
2 parents 19e61c7 + 7d4ae71 commit 5330d78

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

bot.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,3 +1065,31 @@ 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+
// If there is an error, an empty string will be returned.
1073+
//
1074+
// parseMode is the text formatting mode (ModeMarkdown, ModeMarkdownV2 or ModeHTML)
1075+
// text is the input string that will be escaped
1076+
func EscapeText(parseMode string, text string) string {
1077+
var replacer *strings.Replacer
1078+
1079+
if parseMode == ModeHTML {
1080+
replacer = strings.NewReplacer("<", "&lt;", ">", "&gt;", "&", "&amp;")
1081+
} else if parseMode == ModeMarkdown {
1082+
replacer = strings.NewReplacer("_", "\\_", "*", "\\*", "`", "\\`", "[", "\\[")
1083+
} else if parseMode == ModeMarkdownV2 {
1084+
replacer = strings.NewReplacer(
1085+
"_", "\\_", "*", "\\*", "[", "\\[", "]", "\\]", "(",
1086+
"\\(", ")", "\\)", "~", "\\~", "`", "\\`", ">", "\\>",
1087+
"#", "\\#", "+", "\\+", "-", "\\-", "=", "\\=", "|",
1088+
"\\|", "{", "\\{", "}", "\\}", ".", "\\.", "!", "\\!",
1089+
)
1090+
} else {
1091+
return ""
1092+
}
1093+
1094+
return replacer.Replace(text)
1095+
}

go.mod

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
module github.com/go-telegram-bot-api/telegram-bot-api
1+
module github.com/TheRTK/telegram-bot-api
22

33
go 1.12
44

5-
require github.com/technoweenie/multipartstreamer v1.0.1
5+
require (
6+
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible
7+
github.com/technoweenie/multipartstreamer v1.0.1
8+
)

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
1+
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU=
2+
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM=
13
github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM=
24
github.com/technoweenie/multipartstreamer v1.0.1/go.mod h1:jNVxdtShOxzAsukZwTSw6MDx5eUJoiEBsSvzDU9uzog=

0 commit comments

Comments
 (0)