Reputation: 13321
I am trying to write a slackbot. I've tried a variety of frameworks from github, but the most promising I've used seems to be hanu
What I'd like to do is send a message to a bot like so:
@bot <command> "Something" "Another thing that contains spaces" "A final thing with spaces"
I'd like to then have each of those 3 parameters be passed as strings to a var, which then has a handle func which can be executed.
I just don't seem to be able to do this! The hanu framework linked above seems to use this framework which states:
The allot library supports placeholders and regular expressions for parameter matching and parsing.
But because I'm a terrible developer, I can't seem to figure out how to do this in the framework above because there's no examples.
So I'd like to either be able to:
Upvotes: 0
Views: 664
Reputation: 156642
One approach would be to abuse strings.FieldsFunc(...)
to split the string on whitespace only if it is not in a quoted section:
func main() {
s := `@bot <command> "Something" "Another thing that contains spaces, it's great" "A final thing with spaces"`
tokens := splitWithQuotes(s)
for i, t := range tokens {
fmt.Printf("OK: tokens[%d] = %s\n", i, t)
}
// OK: tokens[0] = @bot
// OK: tokens[1] = <command>
// OK: tokens[2] = "Something"
// OK: tokens[3] = "Another thing that contains spaces, it's great"
// OK: tokens[4] = "A final thing with spaces"
}
func splitWithQuotes(s string) []string {
inquote := false
return strings.FieldsFunc(s, func(c rune) bool {
switch {
case c == '"':
inquote = !inquote
return false
case inquote:
return false
default:
return unicode.IsSpace(c)
}
})
}
Strictly speaking, this approach might not work with all versions of golang since, per the documentation:
If f does not return consistent results for a given c, FieldsFunc may crash.
...and this function definitely returns varying results for whitespace characters; however, it seems to work with go 1.9 and newer, so I guess it depends on your appetite for adventure!
Upvotes: 1