Skip to content

Instantly share code, notes, and snippets.

@diamondburned
Last active December 23, 2019 00:28
Show Gist options
  • Save diamondburned/74c7a229be6e43cd8bd0b05ddb7d529b to your computer and use it in GitHub Desktop.
Save diamondburned/74c7a229be6e43cd8bd0b05ddb7d529b to your computer and use it in GitHub Desktop.
Escaping @everyone in Go
// EscapeEveryone escapes @everyone and @here mentions.
func EscapeEveryone(s string) string {
var mentionBuf string
var mentionInd int
for i, r := range s {
if r == '@' && i != len(s)-1 {
mentionBuf += string(r)
mentionInd = i
continue
}
if unicode.IsSpace(r) {
mentionBuf = ""
continue
}
if mentionBuf != "" && unicode.IsLetter(r) {
mentionBuf += string(r)
}
if stringsCmp(mentionBuf, "@everyone", "@here") {
s = s[:mentionInd+1] + "\u200b" + s[mentionInd+1:]
// Reset buffer
mentionBuf = ""
mentionInd = 0
}
}
return s
}
func stringsCmp(str string, cmp ...string) bool {
for _, c := range cmp {
if c == str {
return true
}
}
return false
}
func TestEscapeEveryone(t *testing.T) {
var samples = [...]string{
"@everyone",
"@\u202eeveryone",
}
for _, sample := range samples {
esc := EscapeEveryone(sample)
if !strings.HasPrefix(esc, "@\u200b") {
t.Fatal("Escape failed:", fmt.Sprintf("%#v", esc))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment