首页 > 解决方案 > 支持用引号括起来的参数的 Slackbot

问题描述

我正在尝试编写一个 slackbot。我已经尝试了来自 github 的各种框架,但我用过的最有前途的似乎是hanu

我想做的是向机器人发送消息,如下所示:

@bot <command> "Something" "Another thing that contains spaces" "A final thing with spaces"

然后我想将这 3 个参数中的每一个作为字符串传递给一个 var,然后它有一个可以执行的句柄 func。

我只是似乎无法做到这一点!上面链接的 hanu 框架似乎使用了这个框架,它指出:

allot 库支持用于参数匹配和解析的占位符和正则表达式。

但是因为我是一个糟糕的开发人员,我似乎无法在上面的框架中弄清楚如何做到这一点,因为没有示例。

所以我希望能够:

标签: goslackslack-api

解决方案


一种方法是strings.FieldsFunc(...)仅当字符串不在引号部分中时才滥用在空格上拆分字符串:

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)
    }
  })
}

严格来说,这种方法可能不适用于所有版本的 golang,因为根据文档:

如果 f 没有为给定的 c 返回一致的结果,FieldsFunc 可能会崩溃。

...并且此函数肯定会为空白字符返回不同的结果;但是,它似乎适用于 go 1.9 及更高版本,所以我想这取决于您对冒险的兴趣!


推荐阅读