首页 文章

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

提问于
浏览
36

我正在尝试使用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"}'

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

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

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

10 回答

  • 6

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

    我希望这有帮助! :)

  • 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 的值是URL编码的 [{"color":"good","fallback":"plain text","text":"colored text"}] . 您应该能够使用所有附件属性described here .

  • 58

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

    JSON编码的主体对于这些写入方法,您也可以将HTTP POST数据作为Content-type:application / json发送 . 有一些基本规则:您必须将Content-type HTTP标头显式设置为application / json . 没有它我们不会解释你的POST主体 . 您必须在Authorization HTTP标头中将令牌作为承载令牌进行传输 . 您不能将您的令牌作为查询字符串的一部分或作为发布的JSON中的属性发送 . 不要在查询字符串,URL编码的POST正文和JSON属性之间混合参数 . 每个请求选择一种方法 . 为属性提供显式空值将导致为其分配任何默认行为 .

    curl 的例子 . 注意 Authorization Headers .

    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
    
  • 1

    尝试将每个属性放在自己的-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:"
    
  • 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 .

  • -1

    截至 March 2018Slack 现在支持 POSTJSON 正文

    Endpointhttps://slack.com/api/chat.postMessage

    HeadersAuthorization: Bearer xoxp-your-hardly-find-token-here

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

    注意 Authorization Headers 中的 Bearer .

  • 0

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

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

  • 1

    在邮差上你可以像这样构建你的请求:

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

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

    • 键( Content-Type )值( application/json

    • 键( Authorization )值( YOUR-TOKEN-NAME

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

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

    我在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        
        }
    
  • 3

    如果你使用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);
            }
        }
    

相关问题