Search code examples
apichatattachmentpostmessageslack

Slack API: How to reply for an attachment action?


I've created an integration with Slack as a WebHook APP. The code is to send a message to a slack channel, using the chat.postMessage method, with some attachment actions, then when the user click the action button, I send him a success message. I'm trying to do something like this:

https://api.slack.com/img/api/message_guidelines/Example_6.gif

The problem is when I try to send the success message. Slack is receiving only the text part of the answer. Here is the code:

$message = 'Pre-text message';

$attachments = array(
  array(
    "title" => 'Title message',
    "author_name" => 'My name',
"author_link" => 'https://www.facebook.com/',
"author_icon" => 'https://graph.facebook.com/v2.6/picture',
"image_url" => 'https://i.scdn.co/image',
  ),
);

$answer = array(
  'text' => $message,
  'attachments' => json_encode($attachments)
)

How can I do to Slack show the answer with the attachment part as shown in the image above? If I comment the text part on $answer, Slack show an error to user ('Oh no, something went wrong. Please try that again.'). Many thanks for any help.


Solution

  • I found the solution. Posting here to help somebody with the same problem. When you posting a message, should json_encode the attachment part, but when posting the attachment action answer, is not necessary. Here is the solution:

    $message = 'Pre-text message';
    
    $attachments = array(
      array(
        "title" => 'Title message',
        "author_name" => 'My name',
        "author_link" => 'https://www.facebook.com/',
        "author_icon" => 'https://graph.facebook.com/v2.6/picture',
        "image_url" => 'https://i.scdn.co/image',
      ),
    );
    
    $answer = array(
        'text' => $message,
        'attachments' => $attachments
    )