|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2020 Google LLC. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +// [START functions_slack_setup] |
| 19 | +use Psr\Http\Message\ServerRequestInterface; |
| 20 | +use Psr\Http\Message\ResponseInterface; |
| 21 | +use GuzzleHttp\Psr7\Response; |
| 22 | + |
| 23 | +// [END functions_slack_setup] |
| 24 | + |
| 25 | +// [START functions_verify_webhook] |
| 26 | +/** |
| 27 | + * Verify that the webhook request came from Slack. |
| 28 | + */ |
| 29 | +function isValidSlackWebhook(ServerRequestInterface $request): bool |
| 30 | +{ |
| 31 | + $SLACK_SECRET = getenv('SLACK_SECRET'); |
| 32 | + |
| 33 | + // Check for headers |
| 34 | + $timestamp = $request->getHeader('X-Slack-Request-Timestamp'); |
| 35 | + $signature = $request->getHeader('X-Slack-Signature'); |
| 36 | + if (!$timestamp || !$signature) { |
| 37 | + return false; |
| 38 | + } else { |
| 39 | + $timestamp = $timestamp[0]; |
| 40 | + $signature = $signature[0]; |
| 41 | + } |
| 42 | + |
| 43 | + // Compute signature |
| 44 | + $plaintext = 'v0:' . $timestamp . ':' . (string) $request->getBody(); |
| 45 | + $hash = 'v0=' . hash_hmac('sha256', $plaintext, $SLACK_SECRET); |
| 46 | + |
| 47 | + return $hash === $signature; |
| 48 | +} |
| 49 | +// [END functions_verify_webhook] |
| 50 | + |
| 51 | +// [START functions_slack_format] |
| 52 | +/** |
| 53 | + * Format the Knowledge Graph API response into a richly formatted Slack message. |
| 54 | + */ |
| 55 | +function formatSlackMessage(Google_Service_Kgsearch_SearchResponse $kgResponse, string $query): string |
| 56 | +{ |
| 57 | + $responseJson = [ |
| 58 | + 'response_type' => 'in_channel', |
| 59 | + 'text' => 'Query: ' . $query |
| 60 | + ]; |
| 61 | + |
| 62 | + $entityList = $kgResponse['itemListElement']; |
| 63 | + |
| 64 | + // Extract the first entity from the result list, if any |
| 65 | + if (empty($entityList)) { |
| 66 | + $attachmentJson = ['text' => 'No results match your query...']; |
| 67 | + $responseJson['attachments'] = $attachmentJson; |
| 68 | + |
| 69 | + return json_encode($responseJson); |
| 70 | + } |
| 71 | + |
| 72 | + $entity = $entityList[0]['result']; |
| 73 | + |
| 74 | + // Construct Knowledge Graph response attachment |
| 75 | + $title = $entity['name']; |
| 76 | + if (isset($entity['description'])) { |
| 77 | + $title = $title . ' ' . $entity['description']; |
| 78 | + } |
| 79 | + $attachmentJson = ['title' => $title]; |
| 80 | + |
| 81 | + if (isset($entity['detailedDescription'])) { |
| 82 | + $detailedDescJson = $entity['detailedDescription']; |
| 83 | + $attachmentJson = array_merge([ |
| 84 | + 'title_link' => $detailedDescJson[ 'url'], |
| 85 | + 'text' => $detailedDescJson['articleBody'], |
| 86 | + ], $attachmentJson); |
| 87 | + } |
| 88 | + |
| 89 | + if ($entity['image']) { |
| 90 | + $imageJson = $entity['image']; |
| 91 | + $attachmentJson['image_url'] = $imageJson['contentUrl']; |
| 92 | + } |
| 93 | + |
| 94 | + $responseJson['attachments'] = array($attachmentJson); |
| 95 | + |
| 96 | + return json_encode($responseJson); |
| 97 | +} |
| 98 | +// [END functions_slack_format] |
| 99 | + |
| 100 | +// [START functions_slack_request] |
| 101 | +/** |
| 102 | + * Send the user's search query to the Knowledge Graph API. |
| 103 | + */ |
| 104 | +function searchKnowledgeGraph(string $query): Google_Service_Kgsearch_SearchResponse |
| 105 | +{ |
| 106 | + $API_KEY = getenv("KG_API_KEY"); |
| 107 | + |
| 108 | + $apiClient = new Google\Client(); |
| 109 | + $apiClient->setDeveloperKey($API_KEY); |
| 110 | + |
| 111 | + $service = new Google_Service_Kgsearch($apiClient); |
| 112 | + |
| 113 | + $params = ['query' => $query]; |
| 114 | + |
| 115 | + $kgResults = $service->entities->search($params); |
| 116 | + |
| 117 | + return $kgResults; |
| 118 | +} |
| 119 | +// [END functions_slack_request] |
| 120 | + |
| 121 | +// [START functions_slack_search] |
| 122 | +/** |
| 123 | + * Receive a Slash Command request from Slack. |
| 124 | + */ |
| 125 | +function receiveRequest(ServerRequestInterface $request): ResponseInterface |
| 126 | +{ |
| 127 | + // Validate request |
| 128 | + if ($request->getMethod() !== 'POST') { |
| 129 | + // [] = empty headers |
| 130 | + return new Response(405); |
| 131 | + } |
| 132 | + |
| 133 | + // Parse incoming URL-encoded requests from Slack |
| 134 | + // (Slack requests use the "application/x-www-form-urlencoded" format) |
| 135 | + $bodyStr = $request->getBody(); |
| 136 | + parse_str($bodyStr, $bodyParams); |
| 137 | + |
| 138 | + if (!isset($bodyParams['text'])) { |
| 139 | + // [] = empty headers |
| 140 | + return new Response(400); |
| 141 | + } |
| 142 | + |
| 143 | + if (!isValidSlackWebhook($request, $bodyStr)) { |
| 144 | + // [] = empty headers |
| 145 | + return new Response(403); |
| 146 | + } |
| 147 | + |
| 148 | + $query = $bodyParams['text']; |
| 149 | + |
| 150 | + // Call knowledge graph API |
| 151 | + $kgResponse = searchKnowledgeGraph($query); |
| 152 | + |
| 153 | + // Format response to Slack |
| 154 | + // See https://api.slack.com/docs/message-formatting |
| 155 | + $formatted_message = formatSlackMessage($kgResponse, $query); |
| 156 | + |
| 157 | + return new Response( |
| 158 | + 200, |
| 159 | + ['Content-Type' => 'application/json'], |
| 160 | + $formatted_message |
| 161 | + ); |
| 162 | +} |
| 163 | +// [END functions_slack_search] |
0 commit comments