gpt4 book ai didi

go - 支持用引号包裹参数的Slackbot

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:03 25 4
gpt4 key购买 nike

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

我想做的是像这样向机器人发送消息:

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

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

我就是做不到啊!上面链接的 hanu 框架似乎使用了 this框架规定:

The allot library supports placeholders and regular expressions for parameter matching and parsing.

但因为我是一个糟糕的开发人员,我似乎无法弄清楚如何在上面的框架中执行此操作,因为没有示例。

所以我希望能够:

  • 弄清楚如何使用带有这些参数的上述库,这样我就可以开始构建一些东西了
  • 使用 github.com/nlopes/slack 编写一个机器人命令,我自己使用这些参数并传递我自己的处理函数。

最佳答案

一种方法是滥用 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,因为根据文档:

If f does not return consistent results for a given c, FieldsFunc may crash.

...并且此函数肯定会针对空白字符返回不同的结果;然而,它似乎适用于 go 1.9 和更新版本,所以我想这取决于你对冒险的胃口!

关于go - 支持用引号包裹参数的Slackbot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com