go - 支持用引号括起来的参数的 Slackbot
问题描述
我正在尝试编写一个 slackbot。我已经尝试了来自 github 的各种框架,但我用过的最有前途的似乎是hanu
我想做的是向机器人发送消息,如下所示:
@bot <command> "Something" "Another thing that contains spaces" "A final thing with spaces"
然后我想将这 3 个参数中的每一个作为字符串传递给一个 var,然后它有一个可以执行的句柄 func。
我只是似乎无法做到这一点!上面链接的 hanu 框架似乎使用了这个框架,它指出:
allot 库支持用于参数匹配和解析的占位符和正则表达式。
但是因为我是一个糟糕的开发人员,我似乎无法在上面的框架中弄清楚如何做到这一点,因为没有示例。
所以我希望能够:
- 弄清楚如何使用带有这些参数的上述库,以便我可以开始构建一些东西
- 编写一个机器人命令,使用 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,因为根据文档:
如果 f 没有为给定的 c 返回一致的结果,FieldsFunc 可能会崩溃。
...并且此函数肯定会为空白字符返回不同的结果;但是,它似乎适用于 go 1.9 及更高版本,所以我想这取决于您对冒险的兴趣!
推荐阅读
- powerbi - Dax 比较不支持值类型文本和值类型整数
- php - 如何在数据库的不同列中插入每张图片
- python - 如何将图像的 2x2 矩阵广播到另一个矩阵中以获得以下结果
- angular - 交换或更改 Angular Mat Table 中的列,而无需重新初始化表中的每个组件
- google-sheets - Filter() 公式正在停止条件格式的工作
- python - 如何计算数据框中一行的增加/减少次数
- excel - 如何强制加载 COM 插件?
- javascript - 本地存储和可见 DOM 上存在的元素上的 QuerySelector null
- reactjs - 在 React 中将按钮渲染为加载登录
- java - 如何在我的 Java Spring 应用程序中获取 ActiveMQ 队列的入队和出队计数?