在HTTP POST请求中将Sland发送给Slack

时间:2015-08-09 14:27:23

标签: json api slack-api

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

我一直在使用curlPostman进行测试,但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"}'

在邮递员中,这是原始身体:

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

我之前没有做过这样的事情,所以我不确定我是否遗漏了一些东西。谢谢!

11 个答案:

答案 0 :(得分:61)

我有点晚了,但我希望这可以帮助其他像我一样偶然发现这个问题的人。我刚刚与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'`

我希望这有帮助! :)

答案 1 :(得分:8)

好的,重新阅读文档后我发现了:

  

JSON编码的正文

     

对于这些写入方法,您也可以发送HTTP POST   数据为Content-type:application / json。

     

有一些基本规则:

     
      
  • 您必须将Content-type HTTP标头显式设置为application / json。没有它我们就不会解释你的POST主体。
  •   
  • 您必须在授权HTTP标头中将您的令牌作为承载令牌进行传输。
  •   
  • 您不能将您的令牌作为查询字符串的一部分发送,也不能作为发布的JSON中的属性发送。
  •   
  • 不要在查询字符串,URL编码的POST正文和JSON属性之间混合参数。每个请求选择一种方法。
  •   
  • 为属性提供显式空值将导致为其分配默认行为。
  •   

curl示例。请注意授权标题。

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

答案 2 :(得分:6)

这可能不符合完整答案的条件,但如果目的是发送邮件附件,您可以发送urlencode d 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的值是网址编码的[{"color":"good","fallback":"plain text","text":"colored text"}]。您应该能够使用所有附件属性described here

答案 3 :(得分:5)

2018年3月开始, Slack 现在支持 POST JSON 正文

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

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

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

请注意 授权 标题中的 承载

答案 4 :(得分: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:"

答案 5 :(得分:3)

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

答案 6 :(得分:1)

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

您在请求中传递了哪些令牌?您需要传递OAuth令牌,您可以从here获取。

答案 7 :(得分:1)

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

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

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

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

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

  3. 然后在Body表单的raw部分中填写您的数据:

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

答案 8 :(得分: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        
    }

答案 9 :(得分:0)

如果你使用java和spring这样的依赖,Voila !!你去吧

     * 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);
        }
    }

答案 10 :(得分: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

相关问题