2017-08-16 31 views
0

我正在自動化一個在託管服務提供商工作的流程。我正在嘗試向用戶發送消息,當他們有一個逾期未付的服務檯票證時。發生這種情況時,我正在觸發以下PHP腳本(對於本示例簡化):無法使用chat.postMessage發送附件

<?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陣列中嵌套陣列不起作用。

我想知道如果有人能指出我在正確的方向。我嘗試了一些變化,但似乎無法釘這一個。

回答

0

documentation

結構化附件的基於JSON-A陣列,呈現爲一個URL編碼的字符串。

從文檔預期值的一個例子:

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

所以你要你的​​變量改成這樣:

$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"} 
+0

這並獲得成功,非常感謝你! –

+0

@GrahamBewley歡迎你:) –