| 32 | * @returns {object} The formatted message. |
| 33 | */ |
| 34 | const formatSlackMessage = (query, response) => { |
| 35 | let entity; |
| 36 | |
| 37 | // Extract the first entity from the result list, if any |
| 38 | if ( |
| 39 | response && |
| 40 | response.data && |
| 41 | response.data.itemListElement && |
| 42 | response.data.itemListElement.length > 0 |
| 43 | ) { |
| 44 | entity = response.data.itemListElement[0].result; |
| 45 | } |
| 46 | |
| 47 | // Prepare a rich Slack message |
| 48 | // See https://api.slack.com/docs/message-formatting |
| 49 | const slackMessage = { |
| 50 | response_type: 'in_channel', |
| 51 | text: `Query: ${query}`, |
| 52 | attachments: [], |
| 53 | }; |
| 54 | |
| 55 | if (entity) { |
| 56 | const attachment = { |
| 57 | color: '#3367d6', |
| 58 | }; |
| 59 | if (entity.name) { |
| 60 | attachment.title = entity.name; |
| 61 | if (entity.description) { |
| 62 | attachment.title = `${attachment.title}: ${entity.description}`; |
| 63 | } |
| 64 | } |
| 65 | if (entity.detailedDescription) { |
| 66 | if (entity.detailedDescription.url) { |
| 67 | attachment.title_link = entity.detailedDescription.url; |
| 68 | } |
| 69 | if (entity.detailedDescription.articleBody) { |
| 70 | attachment.text = entity.detailedDescription.articleBody; |
| 71 | } |
| 72 | } |
| 73 | if (entity.image && entity.image.contentUrl) { |
| 74 | attachment.image_url = entity.image.contentUrl; |
| 75 | } |
| 76 | slackMessage.attachments.push(attachment); |
| 77 | } else { |
| 78 | slackMessage.attachments.push({ |
| 79 | text: 'No results match your query...', |
| 80 | }); |
| 81 | } |
| 82 | |
| 83 | return slackMessage; |
| 84 | }; |
| 85 | // [END functions_slack_format] |
| 86 | |
| 87 | // [START functions_verify_webhook] |