Slack API为新行使用n在chat.postMessage(golang)中不起作用



我正在使用Slack web API将消息发布到Go中的频道。我正在尝试在文本字段中支持多行消息。根据文档,简单地添加一个应该有效,但不起作用。张贴时,\n会显示在文本中,并且没有换行符。

这是我正在使用的代码:

func PostMessage(token, channelName, userName, text string) error {
    uv := url.Values{}
    uv.Add("token", token)
    uv.Add("channel", channelName)
    uv.Add("username", userName)
    uv.Add("text", text)
    resp, err := http.PostForm("https://slack.com/api/chat.postMessage", uv)
    if err != nil {
        return err
    }
    return nil
}
func main() {
    if err := PostMessage("xxxx", "#test-channel", "API", "This should be the first linenThis should be the second line"); err != nil {
        panic(err)
    }
}

我发现了这个问题。我最初发布的样本实际上会按预期工作。我简化了原始代码,它是一个命令行应用程序,其中文本是作为CLI标志传递的参数,所以它看起来有点像:

cliapp --text="onentwo"

持有该标志值的变量实际上并没有转义字符,所以它实际上是:

"one\ntwo"

我使用了一个简单的字符串替换来修复值:

text = strings.Replace(text, "\n", "n", -1)

我使用的是Java,我做了

message.replace("\n","n")

它奏效了。

只需用"`n"转义换行符"\n"

参考:https://ss64.com/ps/syntax-esc.html

最新更新