方法
blocksを使った場合は、unfurled,_linksをtrueにした上で、textにslack上で展開したいURLを入力すると、Slack上でURLが展開されるようです。
※ textに含まれるURLのみ展開されるようです。
※ blocksやattachments内のURLは展開されてないようです。
例えば以下のコードを実行すると、textに含まれているはてなブログのURLだけがSlack上で展開されます。
var url = "https://hooks.slack.com/services/xxxxx";//incoming webhooksのURL
var payload = {
"text" : "<https://hatenablog.com>",
"unfurl_links": true,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Qiita: <https://www.qiita.com>"
}
}
],
"attachments" : [
{
"color": "#FD8F07",
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Amebaブログ <https://ameblo.jp/>"
}
}
]
}
]
};
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
実行結果
text, blocks, attachmentsの関係
現在のSlackのchat.postMessage APIのtext, blocks, attachmentsの関係は以下のようになっているようです。
| text | blocks | attachments | slack上の表示 | |
|---|---|---|---|---|
| 1 | あり | あり | あり | blocks + attachments |
| 2 | あり | あり | なし | blocks |
| 3 | あり | なし | あり | text + attachments |
| 4 | あり | なし | なし | text |
| 5 | なし | あり | あり | blocks + attachments |
| 6 | なし | あり | なし | blocks |
| 7 | なし | なし | あり | attachments |
| 8 | なし | なし | なし | エラー |
textとblocksについて
-
blocksを使用しない場合:textの値がSlack上で表示される -
blocksを使用している場合:textの値はSlack上に表示されない
となっているようです。
textは本来必須項目ですが、blocksやattachmentsがある場合は空でOKみたいですね(blocksが代わりにっていう表記は見つけられなかったんですが…)。

chat.postMessage method | Slackより
URLの展開

chat.postMessage method | Slackより
このunfurled,_linksをtrueにすると展開されるようです。
しかし、この対象となっているのはどうもtextのところだけみたいですね。
Incoming Webhooksではなく、Tokenを使った場合は?
上述の仕様と同じようです。
tokenを使った場合は以下の感じになります。
var url = 'https://slack.com/api/chat.postMessage';
var token = 'xoxb-xxxxxxxxxx'; //tokenを入力する
var payload = {
"channel" : "{ChannelID or Channel Name}",
"text" : "<https://hatenablog.com>",
"unfurl_links": true,
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Qiita: <https://www.qiita.com>"
}
}
],
"attachments" : [
{
"color": "#FD8F07",
"blocks" : [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Abemaブログ <https://ameblo.jp/>"
}
}
]
}
]
};
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
まとめ
blocksのおかげでいろいろ見やすくなりましたが、textのことも思い出さないとですね。
参考
SlackのIncoming Webhooksで投稿したURLが展開されなくて困った話 - Qiita
Slack APIでリンクを開く - Qiita
