44

我正在尝试使用Slack 的 chat.postMessage API 调用发送消息。我在 HTTP GET 中编码我的测试消息没有问题,但我试图在 HTTP POST 请求中使用 JSON 实现相同的结果。

我一直在测试Postmancurl和两者,但 Slack 似乎根本不承认我的请求正文。

{
  "ok": false,
  "error": "not_authed"
}

curl中,我的请求编码如下:

curl -H "Content-type: application/json" -X POST -d '{"token":"my-token-here","channel":"#channel-name-or-id","text":"Text here.","username":"otherusername"}'

在 Postman 中,这是原始的身体:

{
    "token":"my-token-here",
    "channel":"#channel-name-or-id",
    "text":"Text here.",
    "username":"otherusername"
}

我以前没有做过这样的事情,所以我不确定我是否遗漏了什么。谢谢!

4

11 回答 11

67

我有点晚了,但我希望这可以帮助像我这样偶然发现这个问题的其他人。我刚刚与 Slack 取得联系,他们是这样告诉我的:

Slack Web API 根本不接受 JSON 数据——所以除了更改 Content-Type 之外,这些变量应该使用标准的 HTTP 表单属性发布。

我们计划在未来支持 JSON 数据以保持未来的一致性。

因此,您的 cURL 行应如下所示:

curl -X POST -d 'token=my-token-here&channel=#channel-name-or-id&text=Text here.&username=otherusername'`

我希望这有帮助!:)

于 2015-10-23T20:12:36.643 回答
12

Okay, after re-reading the documentation I found it:

JSON-encoded bodies

For these write methods, you may alternatively send your HTTP POST data as Content-type: application/json.

There are some ground rules:

  • You must explicitly set the Content-type HTTP header to application/json. We won't interpret your POST body as such without it.
  • You must transmit your token as a bearer token in the Authorization HTTP header.
  • You cannot send your token as part of the query string or as an attribute in your posted JSON.
  • Do not mix arguments between query string, URL-encoded POST body, and JSON attributes. Choose one approach per request.
  • Providing an explicitly null value for an attribute will result in whichever default behavior is assigned to it.

And the curl example. Notice the Authorization header.

curl -X POST \
     -H 'Authorization: Bearer xoxb-1234-56789abcdefghijklmnop' \
     -H 'Content-type: application/json; charset=utf-8' \
    --data '{"channel":"C061EG9SL","text":""..."}' \
https://slack.com/api/chat.postMessage
于 2018-01-09T23:43:25.437 回答
6

这可能不符合完整的答案,但如果目的是发送消息附件,您可以发送一个urlencoded JSON 结构作为attachments参数的值,如下所示(为了清楚起见分成多行):

https://slack.com/api/chat.postMessage?
token=YOUR-TOKE-N000&
channel=%23alerts&
text=Hi&
attachments=%5B%7B%22color%22%3A%22good%22%2C%22fallback%22%3A%22plain+text%22%2C%22text%22%3A%22colored+text%22%7D%5D

的值attachments是 URL 编码的[{"color":"good","fallback":"plain text","text":"colored text"}]。您应该能够使用此处描述的所有附件属性。

于 2016-02-16T05:53:01.840 回答
6

截至2018 年 3 月Slack现在支持带有JSON正文的POST

端点https://slack.com/api/chat.postMessage

标题Authorization: Bearer xoxp-your-hardly-find-token-here

身体{"channel":"CH9NN37","text":"something from me!"}

注意 Authorization标头中的Bearer

于 2018-03-06T01:53:16.227 回答
4

Slack 已更新,现在可以使用。试试这个例子:

curl -X POST -H 'Content-type: application/json' --data '{"text":"This is a line of text.\nAnd this is another one."}' https://hooks.slack.com/services/AAAAAA/BBBBBB/CCCCCC

有关文档,请参阅https://api.slack.com/incoming-webhooks

于 2016-12-28T19:00:52.003 回答
3

尝试将每个属性放在自己的 -d 参数中,如下所示:

curl https://slack.com/api/chat.postMessage -X POST -d "channel=#tehchannel" -d "text=teh text" -d "username=teh user" -d "token=teh-token-you-got-from-teh-page-that-machinehead115-linked-to" -d "icon_emoji=:simple_smile:"
于 2015-10-06T10:01:44.360 回答
2

在邮递员上,您可以像这样构建您的请求:

网址(POST):https ://slack.com/api/chat.postMessage

然后在Headers部分下放置这两个标题:

  1. 键(Content-Type)值(application/json

  2. 键(Authorization)值(YOUR-TOKEN-NAME

然后在表格Body部分中输入raw您的数据:

    {"channel": "CHANNEL-NAME", "data": "You better post this to channel"}
于 2018-02-07T02:59:58.307 回答
1

not_authed表示未提供身份验证令牌。

您在请求中传递了哪个令牌?您需要传递您的 OAuth 令牌,您可以从此处获取。

于 2015-08-10T15:18:22.570 回答
0

我在powershell中做了这个,它就像一个魅力。

$url="https://slack.com/api/chat.postMessage"
    $messageContent= # your message here
    $token = # your token here
    $channel = # channel name
    $opt_username= # optional user name

    $body = @{token=$token;channel=$channel;username=$opt_username;text=$messageContent;pretty=1}

    try
    {
        Invoke-WebRequest -Uri $url -Method POST -Body $body
    }
    catch
    {
        Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
        Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription        
    }
于 2017-02-02T16:39:19.943 回答
0

如果你使用 java 和 spring 这样的依赖,瞧!干得好

     * Make a POST call to the chat.PostMessage.
     */
    public void chatPostMessage(Message message)
    {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("token", slackPostMessageToken); //Required
        map.add("text", message.getText());//Required
        map.add("channel", message.getChannelId());//Required

        map.add("unfurl_links","true");
        map.add("as_user","false");//Default false
        map.add("icon_emoji",":chart_with_upwards_trend:");
        map.add("attachments","[\n" +
                "        {\n" +
                "            \"fallback\": \"Required plain-text summary of the attachment.\",\n" +
                "            \"color\": \"#36a64f\",\n" +
                "            \"pretext\": \"Optional text that appears above the attachment block\",\n" +
                "            \"author_name\": \"Bobby Tables\",\n" +
                "            \"author_link\": \"http://flickr.com/bobby/\",\n" +
                "            \"author_icon\": \"http://flickr.com/icons/bobby.jpg\",\n" +
                "            \"title\": \"Slack API Documentation\",\n" +
                "            \"title_link\": \"https://api.slack.com/\",\n" +
                "            \"text\": \"Optional text that appears within the attachment\",\n" +
                "            \"fields\": [\n" +
                "                {\n" +
                "                    \"title\": \"Priority\",\n" +
                "                    \"value\": \"High\",\n" +
                "                    \"short\": false\n" +
                "                }\n" +
                "            ],\n" +
                "            \"image_url\": \"http://my-website.com/path/to/image.jpg\",\n" +
                "            \"thumb_url\": \"http://example.com/path/to/thumb.png\",\n" +
                "            \"footer\": \"Datoo ©\",\n" +
                "            \"ts\": "+System.currentTimeMillis()+"" +
                "        }\n" +
                "    ]");
        map.add("username","III");


        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(slackPostMessageUrl, request, String.class);
            System.out.println(response);
        }
        catch (RestClientException e) {
            logger.error("Error :-( : ", e);
        }
    }
于 2018-01-03T19:55:45.360 回答
0

下面的 curl 命令对我有用。

curl -X POST -H 'Authorization: Bearer xoxb-41234078565-14457098702432-ZLJj9UFOZKnOJtjNW4dv3ukG'  -H 'Content-type: application/json; charset=utf-8'  --data '{"channel":"#general","text":"I hope the tour went well, Mr. Wonka."}' https://slack.com/api/chat.postMessage

于 2020-10-20T10:54:47.490 回答