无法使用chat.postMessage发送附件

时间:2017-08-16 14:44:44

标签: php slack-api

我正致力于自动化我在托管服务提供商处工作的流程。我正在尝试向用户发送消息,因为他们的服务台票证已逾期。当发生这种情况时,我会触发以下PHP脚本(本例简化):

<?php

$attachments = array(
    "fallback" => "Attachment 1 Fallback",
    "title" => "This is Attachment 1",
    "text" => "Attachment 1 text",
    "color" => "95baa9");

$ch = curl_init("https://slack.com/api/chat.postMessage");

$data = http_build_query([
    "token" => "xoxb-0000000000-00000000000", //omitting my token
    "channel" => "@johnsmith",
    "text" => "Here's some text!",
    "attachments" => json_encode($attachments),
    "as_user" => "true"
]);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);

return $result;

除了附件外,一切似乎都在起作用。当我触发此脚本时,我会收到没有附件的消息,只有text。我目前正在使用json_encode,因为将数组嵌套在$data数组中不起作用。

我想知道是否有人可以指出我正确的方向。我尝试了一些变化,但似乎无法确定这个。

1 个答案:

答案 0 :(得分:1)

来自documentation

  

基于JSON的结构化附件数组,以URL编码的字符串形式显示。

文档中预期值的一个示例:

[{"pretext": "pre-hello", "text": "text-world"}]

因此,您必须将$attachments变量更改为:

$attachments = array(
    array(
        "fallback" => "Attachment 1 Fallback",
        "title" => "This is Attachment 1",
        "text" => "Attachment 1 text",
        "color" => "95baa9"
    )
);

以下是json_encode的结果(与文档格式相同):

[{"fallback":"Attachment 1 Fallback","title":"This is Attachment 1","text":"Attachment 1 text","color":"95baa9"}]

这就是你现在的样子:

{"fallback":"Attachment 1 Fallback","title":"This is Attachment 1","text":"Attachment 1 text","color":"95baa9"}