Sending JSON to Slack in a HTTP POST request

天大地大妈咪最大 提交于 2019-12-02 17:26:13
finferflu

I'm a bit late, but I hope this can help other people who stumble into this issue like me. I've just been in touch with Slack, and this is what they told me:

The Slack Web API doesn't accept JSON data at all — so along with changing the Content-Type those variables should be posted using standard HTTP form attributes.

We plan to support JSON data in the future for consistency in the future.

So, your cURL line should look like:

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

I hope this helps! :)

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

This may not qualify for the complete answer, but if the purpose is to send a message attachment, you can send a urlencoded JSON structure as the value of the attachments parameter, like so (split into multiple lines for clarity):

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

The value of attachments is URL-encoded [{"color":"good","fallback":"plain text","text":"colored text"}]. You should be able to use all attachment attributes described here.

As of March 2018, Slack now supports POST with JSON body

Endpoint: https://slack.com/api/chat.postMessage

Headers: Authorization: Bearer xoxp-your-hardly-find-token-here

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

Notice the Bearer in the Authorization header.

Try putting each property in its own -d parameter, like so:

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:"

Slack has been updated, this now works. Try this example:

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

See https://api.slack.com/incoming-webhooks for documentation.

not_authed means No authentication token provided.

Which token are you passing along in the request? You need to pass your OAuth token, which you can get from here.

On postman you can frame your request like this:

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

Then under Headers section put these two headers:

  1. key(Content-Type) value(application/json)

  2. key(Authorization) value(YOUR-TOKEN-NAME)

Then in Body section in raw form put your data:

    {"channel": "CHANNEL-NAME", "data": "You better post this to channel"}

I did this in powershell and it works like a charm.

$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        
    }
rbyndoor

If you are using java and spring such dependency, Voila!! here you go

     * 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);
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!