Slack 튜토리얼 - 슬래시 명령어(2세대)


이 튜토리얼에서는 Cloud Functions를 사용하여 Google Knowledge Graph API를 검색하는 Slack 슬래시 명령어의 구현 방법을 설명합니다.

목표

  • Slack에서 슬래시 명령어를 만듭니다.
  • HTTP Cloud Functions를 작성 및 배포합니다.
  • 슬래시 명령어를 사용하여 Google Knowledge Graph API를 검색합니다.

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

  • Cloud Functions
  • Cloud Build
  • Artifact Registry
  • Cloud Logging

자세한 내용은 Cloud Functions 가격 책정을 참조하세요.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Cloud Functions, Cloud Build, Artifact Registry, and Logging 사용 설정

    API 사용 설정

  5. Google Cloud CLI를 설치합니다.
  6. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  7. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  8. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  9. API Cloud Functions, Cloud Build, Artifact Registry, and Logging 사용 설정

    API 사용 설정

  10. Google Cloud CLI를 설치합니다.
  11. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  12. gcloud CLI가 이미 설치되어 있으면 다음 명령어를 실행하여 업데이트합니다.

    gcloud components update
  13. 개발 환경을 준비합니다.

데이터 흐름 시각화

Slack 슬래시 명령어 가이드 애플리케이션의 데이터 흐름 단계는 다음과 같습니다.

  1. 사용자가 Slack 채널에서 /kg <search_query> 슬래시 명령어를 실행합니다.
  2. Slack은 명령어 페이로드를 Cloud 함수의 트리거 엔드포인트로 보냅니다.
  3. Cloud Functions는 사용자의 검색어와 함께 Knowledge Graph API에 요청을 보냅니다.
  4. Knowledge Graph API는 이와 일치하는 결과로 응답합니다.
  5. Cloud 함수는 응답의 형식을 Slack 메시지로 지정합니다.
  6. Cloud 함수는 메시지를 다시 Slack으로 보냅니다.
  7. 사용자는 Slack 채널에서 형식 지정된 응답을 봅니다.

해당 단계를 시각화하면 다음과 같습니다.

사용자 인증 정보 가져오기

함수를 배포하려면 Google Cloud Console 제공 API 키 및 Slack 서명 보안 비밀이 필요합니다.

Knowledge Graph API 키 가져오기

Google Cloud Console 사용자 인증 정보 페이지에서 사용자 인증 정보 만들기 버튼을 클릭하고 API 키를 선택합니다. deploy 명령어의 일부로 포함하므로 이 키를 기억해 둡니다. 이 키가 있어야 함수가 Knowledge Graph API에 액세스할 수 있습니다.

Slack 서명 보안 비밀 가져오기

또한 함수 배포를 위해 Slack 서명 보안 비밀이 필요합니다. Slack 서명 보안 비밀을 가져오려면 Slack 슬래시 명령어를 호스팅하는 Slack 앱을 만듭니다. 이 앱은 통합 설치 권한이 있는 Slack과 연관되어야 합니다.

  1. Slack 내 앱 페이지로 이동해서 새 앱 만들기를 클릭합니다.

  2. 처음부터를 선택합니다.

  3. 앱 이름을 제공하고 통합 설치 권한이 있는 Slack 작업공간을 선택합니다.

  4. 앱 만들기를 클릭합니다.

    앱이 생성되고 디스플레이가 기본 정보 페이지로 바뀝니다.

  5. 기본 정보 페이지에서 Slack 서명 보안 비밀을 복사하고 이를 저장합니다.

  6. 변경사항을 저장합니다.

그런 후 소스 코드를 가져오고 함수를 배포해야 합니다. 함수를 배포한 후 애플리케이션 구성에 설명된 대로 배포된 함수와 통합하도록 Slack 앱을 구성합니다.

함수 준비

  1. 샘플 앱 저장소를 로컬 머신에 복제합니다.

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  2. Cloud Functions 샘플 코드가 있는 디렉터리로 변경합니다.

    Node.js

    cd nodejs-docs-samples/functions/slack/

    Python

    cd python-docs-samples/functions/slack/

    Go

    cd golang-samples/functions/functionsv2/slack/

    Java

    cd java-docs-samples/functions/slack/

    C#

    cd dotnet-docs-samples/functions/slack/SlackKnowledgeGraphSearch/

    Ruby

    cd ruby-docs-samples/functions/slack/

    PHP

    cd php-docs-samples/functions/slack_slash_command/

함수 배포

사용자 또는 Slack이 함수의 엔드포인트에 HTTP POST 요청을 실행할 때 실행되는 함수를 배포하려면 샘플 코드(또는 자바용 pom.xml 파일)를 포함하는 디렉터리에서 다음 명령어를 실행합니다.

YOUR_SLACK_SIGNING_SECRET을 앱 구성의 기본 정보 페이지에서 Slack이 제공한 서명 보안 비밀로, YOUR_KG_API_KEY를 앞에서 만든 Knowledge Graph API 키로 바꿉니다.

Node.js

gcloud functions deploy nodejs-slack-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=kgSearch \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

Python

gcloud functions deploy python-slack-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=kg_search \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

Go

gcloud functions deploy go-slack-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=KGSearch \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

Java

gcloud functions deploy java-slack-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.SlackSlashCommand \
--memory=512MB \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

C#

gcloud functions deploy csharp-slack-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=SlackKnowledgeGraphSearch.Function \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

Ruby

gcloud functions deploy ruby-slack-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=kg_search \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

PHP

gcloud functions deploy php-slack-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=receiveRequest \
--trigger-http \
--set-env-vars "SLACK_SECRET=YOUR_SLACK_SIGNING_SECRET,KG_API_KEY=YOUR_KG_API_KEY" \
--allow-unauthenticated

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

애플리케이션 구성

함수가 배포되면 명령어가 트리거될 때마다 Cloud Functions에 쿼리를 보내는 Slack 슬래시 명령어를 생성해야 합니다.

  1. 에서 만든 Slack 앱으로 돌아갑니다.

  2. 앱을 선택하고, 슬래시 명령어로 이동하고, 새 명령어 만들기 버튼을 클릭합니다.

  3. /kg를 명령어 이름으로 입력합니다.

  4. 요청 URL 필드에 함수 URL을 입력합니다.

    deploy 명령어 결과에서 URL을 복사하거나 Google Cloud 콘솔에서 Cloud Functions 개요 페이지로 이동하고 함수를 클릭하여 함수 세부정보 페이지를 열고 여기에서 URL을 복사합니다.

  5. 간단한 설명을 입력하고 저장을 클릭합니다.

  6. 기본 정보로 이동합니다.

  7. 작업공간에 설치를 클릭하고 화면의 안내에 따라 작업공간에 애플리케이션을 사용 설정합니다.

    Slack 슬래시 명령어가 곧 작동됩니다.

코드 이해하기

종속 항목 가져오기

애플리케이션은 Google Cloud Platform 서비스와 통신하기 위해 몇 가지 종속성을 가져와야 합니다.

Node.js

const functions = require('@google-cloud/functions-framework');
const google = require('@googleapis/kgsearch');
const {verifyRequestSignature} = require('@slack/events-api');

// Get a reference to the Knowledge Graph Search component
const kgsearch = google.kgsearch('v1');

Python

import os

from flask import jsonify
import functions_framework
import googleapiclient.discovery
from slack.signature import SignatureVerifier

kgsearch = googleapiclient.discovery.build(
    "kgsearch", "v1", developerKey=os.environ["KG_API_KEY"], cache_discovery=False
)

Go


package slack

import (
	"context"
	"log"
	"os"

	"google.golang.org/api/kgsearch/v1"
	"google.golang.org/api/option"
)

var (
	entitiesService *kgsearch.EntitiesService
	kgKey           string
	slackSecret     string
)

func setup(ctx context.Context) {
	kgKey = os.Getenv("KG_API_KEY")
	slackSecret = os.Getenv("SLACK_SECRET")

	if entitiesService == nil {
		kgService, err := kgsearch.NewService(ctx, option.WithAPIKey(kgKey))
		if err != nil {
			log.Fatalf("kgsearch.NewService: %v", err)
		}
		entitiesService = kgsearch.NewEntitiesService(kgService)
	}
}

Java

private static final Logger logger = Logger.getLogger(SlackSlashCommand.class.getName());
private static final String API_KEY = getenv("KG_API_KEY");
private static final String SLACK_SECRET = getenv("SLACK_SECRET");
private static final Gson gson = new Gson();

private final String apiKey;
private final Kgsearch kgClient;
private final SlackSignature.Verifier verifier;

public SlackSlashCommand() throws IOException, GeneralSecurityException {
  this(new SlackSignature.Verifier(new SlackSignature.Generator(SLACK_SECRET)));
}

SlackSlashCommand(SlackSignature.Verifier verifier) throws IOException, GeneralSecurityException {
  this(verifier, API_KEY);
}

SlackSlashCommand(SlackSignature.Verifier verifier, String apiKey)
    throws IOException, GeneralSecurityException {
  this.verifier = verifier;
  this.apiKey = apiKey;
  this.kgClient = new Kgsearch.Builder(
      GoogleNetHttpTransport.newTrustedTransport(), new GsonFactory(), null).build();
}

// Avoid ungraceful deployment failures due to unset environment variables.
// If you get this warning you should redeploy with the variable set.
private static String getenv(String name) {
  String value = System.getenv(name);
  if (value == null) {
    logger.warning("Environment variable " + name + " was not set");
    value = "MISSING";
  }
  return value;
}

C#

using Google.Apis.Kgsearch.v1;
using Google.Apis.Services;
using Google.Cloud.Functions.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;

// Specify a startup class to use for dependency injection.
// This can also be specified on the function type.
[assembly: FunctionsStartup(typeof(SlackKnowledgeGraphSearch.Startup))]

namespace SlackKnowledgeGraphSearch;

public class Startup : FunctionsStartup
{
    private static readonly TimeSpan SlackTimestampTolerance = TimeSpan.FromMinutes(5);

    public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
    {
        // These can come from an environment variable or a configuration file.
        string kgApiKey = context.Configuration["KG_API_KEY"];
        string slackSigningSecret = context.Configuration["SLACK_SECRET"];

        services.AddSingleton(new KgsearchService(new BaseClientService.Initializer
        {
            ApiKey = kgApiKey
        }));
        services.AddSingleton(new SlackRequestVerifier(slackSigningSecret, SlackTimestampTolerance));
        base.ConfigureServices(context, services);
    }
}

Ruby

require "functions_framework"
require "slack-ruby-client"
require "google/apis/kgsearch_v1"

# This block is executed during cold start, before the function begins
# handling requests. This is the recommended way to create shared resources
# and objects.
FunctionsFramework.on_startup do
  # Create a global handler object, configured with the environment-provided
  # API key and signing secret.
  kg_search = KGSearch.new kg_api_key:     ENV["KG_API_KEY"],
                           signing_secret: ENV["SLACK_SECRET"]
  set_global :kg_search, kg_search
end

# The KGSearch class implements the logic of validating and responding
# to requests. More methods of this class are shown below.
class KGSearch
  def initialize kg_api_key:, signing_secret:
    # Create the global client for the Knowledge Graph Search Service,
    # configuring it with your API key.
    @client = Google::Apis::KgsearchV1::KgsearchService.new
    @client.key = kg_api_key

    # Save signing secret for use by the signature validation method.
    @signing_secret = signing_secret
  end

PHP

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Psr7\Response;

웹훅 수신

다음 함수는 사용자(또는 Slack)가 함수의 엔드포인트로 HTTP POST 요청을 보낼 때 실행됩니다.

Node.js

/**
 * Receive a Slash Command request from Slack.
 *
 * Trigger this function by creating a Slack slash command with the HTTP Trigger URL.
 * You can find the HTTP URL in the Cloud Console or using `gcloud functions describe`
 *
 * @param {object} req Cloud Function request object.
 * @param {object} req.body The request payload.
 * @param {string} req.rawBody Raw request payload used to validate Slack's message signature.
 * @param {string} req.body.text The user's search query.
 * @param {object} res Cloud Function response object.
 */
functions.http('kgSearch', async (req, res) => {
  try {
    if (req.method !== 'POST') {
      const error = new Error('Only POST requests are accepted');
      error.code = 405;
      throw error;
    }

    if (!req.body.text) {
      const error = new Error('No text found in body.');
      error.code = 400;
      throw error;
    }

    // Verify that this request came from Slack
    verifyWebhook(req);

    // Make the request to the Knowledge Graph Search API
    const response = await makeSearchRequest(req.body.text);

    // Send the formatted message back to Slack
    res.json(response);

    return Promise.resolve();
  } catch (err) {
    console.error(err);
    res.status(err.code || 500).send(err);
    return Promise.reject(err);
  }
});

Python

@functions_framework.http
def kg_search(request):
    if request.method != "POST":
        return "Only POST requests are accepted", 405

    verify_signature(request)
    kg_search_response = make_search_request(request.form["text"])
    return jsonify(kg_search_response)

Go


// Package slack is a Cloud Function which receives a query from
// a Slack command and responds with the KG API result.
package slack

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

const (
	version                     = "v0"
	slackRequestTimestampHeader = "X-Slack-Request-Timestamp"
	slackSignatureHeader        = "X-Slack-Signature"
)

type Attachment struct {
	Color     string `json:"color"`
	Title     string `json:"title"`
	TitleLink string `json:"title_link"`
	Text      string `json:"text"`
	ImageURL  string `json:"image_url"`
}

// Message is the a Slack message event.
// see https://api.slack.com/docs/message-formatting
type Message struct {
	ResponseType string       `json:"response_type"`
	Text         string       `json:"text"`
	Attachments  []Attachment `json:"attachments"`
}

func init() {
	functions.HTTP("KGSearch", kgSearch)
	setup(context.Background())
}

// kgSearch uses the Knowledge Graph API to search for a query provided
// by a Slack command.
func kgSearch(w http.ResponseWriter, r *http.Request) {

	bodyBytes, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("failed to read body: %v", err)
		http.Error(w, "could not read request body", http.StatusBadRequest)
		return
	}
	if r.Method != "POST" {
		http.Error(w, "Only POST requests are accepted", http.StatusMethodNotAllowed)
		return
	}
	formData, err := url.ParseQuery(string(bodyBytes))
	if err != nil {
		log.Printf("Error: Failed to Parse Form: %v", err)
		http.Error(w, "Couldn't parse form", http.StatusBadRequest)
		return
	}

	result, err := verifyWebHook(r, bodyBytes, slackSecret)
	if err != nil || !result {
		log.Printf("verifyWebhook failed: %v", err)
		http.Error(w, "Failed to verify request signature", http.StatusBadRequest)
		return
	}

	if len(formData.Get("text")) == 0 {
		log.Printf("no search text found: %v", formData)
		http.Error(w, "search text was empty", http.StatusBadRequest)
		return
	}
	kgSearchResponse, err := makeSearchRequest(formData.Get("text"))
	if err != nil {
		log.Printf("makeSearchRequest failed: %v", err)
		http.Error(w, "makeSearchRequest failed", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	if err = json.NewEncoder(w).Encode(kgSearchResponse); err != nil {
		http.Error(w, fmt.Sprintf("failed to marshal results: %v", err), 500)
		return
	}
}

Java

/**
 * Receive a Slash Command request from Slack.
 *
 * @param request Cloud Function request object.
 * @param response Cloud Function response object.
 * @throws IOException if Knowledge Graph request fails
 */
@Override
public void service(HttpRequest request, HttpResponse response) throws IOException {

  // Validate request
  if (!"POST".equals(request.getMethod())) {
    response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
    return;
  }

  // reader can only be read once per request, so we preserve its contents
  String bodyString = request.getReader().lines().collect(Collectors.joining());

  // Slack sends requests as URL-encoded strings
  //   Java 11 doesn't have a standard library
  //   function for this, so do it manually
  Map<String, String> body = new HashMap<>();
  for (String keyValuePair : bodyString.split("&")) {
    String[] keyAndValue = keyValuePair.split("=");
    if (keyAndValue.length == 2) {
      String key = keyAndValue[0];
      String value = keyAndValue[1];

      body.put(key, value);
    }
  }

  if (body == null || !body.containsKey("text")) {
    response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);
    return;
  }

  if (!isValidSlackWebhook(request, bodyString)) {
    response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED);
    return;
  }

  String query = body.get("text");

  // Call knowledge graph API
  JsonObject kgResponse = searchKnowledgeGraph(query);

  // Format response to Slack
  // See https://api.slack.com/docs/message-formatting
  BufferedWriter writer = response.getWriter();

  writer.write(formatSlackMessage(kgResponse, query));

  response.setContentType("application/json");
}

C#

private readonly ILogger _logger;
private readonly KgsearchService _kgService;
private readonly SlackRequestVerifier _verifier;

public Function(ILogger<Function> logger, KgsearchService kgService, SlackRequestVerifier verifier) =>
    (_logger, _kgService, _verifier) = (logger, kgService, verifier);

public async Task HandleAsync(HttpContext context)
{
    var request = context.Request;
    var response = context.Response;

    // Validate request
    if (request.Method != "POST")
    {
        _logger.LogWarning("Unexpected request method '{method}'", request.Method);
        response.StatusCode = (int) HttpStatusCode.MethodNotAllowed;
        return;
    }

    if (!request.HasFormContentType)
    {
        _logger.LogWarning("Unexpected content type '{contentType}'", request.ContentType);
        response.StatusCode = (int) HttpStatusCode.BadRequest;
        return;
    }

    // We need to read the request body twice: once to validate the signature,
    // and once to read the form content. We copy it into a memory stream,
    // so that we can rewind it after reading.
    var bodyCopy = new MemoryStream();
    await request.Body.CopyToAsync(bodyCopy);
    request.Body = bodyCopy;
    bodyCopy.Position = 0;

    if (!_verifier.VerifyRequest(request, bodyCopy.ToArray()))
    {
        _logger.LogWarning("Slack request verification failed");
        response.StatusCode = (int) HttpStatusCode.Unauthorized;
        return;
    }

    var form = await request.ReadFormAsync();
    if (!form.TryGetValue("text", out var query))
    {
        _logger.LogWarning("Slack request form did not contain a text element");
        response.StatusCode = (int) HttpStatusCode.BadRequest;
        return;
    }

    var kgResponse = await SearchKnowledgeGraphAsync(query);
    string formattedResponse = FormatSlackMessage(kgResponse, query);
    response.ContentType = "application/json";
    await response.WriteAsync(formattedResponse);
}

Ruby

# Handler for the function endpoint.
FunctionsFramework.http "kg_search" do |request|
  # Return early if the request is not a POST.
  unless request.post?
    return [405, {}, ["Only POST requests are accepted."]]
  end

  # Access the global Knowledge Graph Search client
  kg_search = global :kg_search

  # Verify the request signature and return early if it failed.
  unless kg_search.signature_valid? request
    return [401, {}, ["Signature validation failed."]]
  end

  # Query the Knowledge Graph and format a Slack message with the response.
  # This method returns a nested hash, which the Functions Framework will
  # convert to JSON automatically.
  kg_search.make_search_request request.params["text"]
end

PHP

/**
 * Receive a Slash Command request from Slack.
 */
function receiveRequest(ServerRequestInterface $request): ResponseInterface
{
    // Validate request
    if ($request->getMethod() !== 'POST') {
        // [] = empty headers
        return new Response(405);
    }

    // Parse incoming URL-encoded requests from Slack
    // (Slack requests use the "application/x-www-form-urlencoded" format)
    $bodyStr = $request->getBody();
    parse_str($bodyStr, $bodyParams);

    if (!isset($bodyParams['text'])) {
        // [] = empty headers
        return new Response(400);
    }

    if (!isValidSlackWebhook($request, $bodyStr)) {
        // [] = empty headers
        return new Response(403);
    }

    $query = $bodyParams['text'];

    // Call knowledge graph API
    $kgResponse = searchKnowledgeGraph($query);

    // Format response to Slack
    // See https://api.slack.com/docs/message-formatting
    $formatted_message = formatSlackMessage($kgResponse, $query);

    return new Response(
        200,
        ['Content-Type' => 'application/json'],
        $formatted_message
    );
}

다음 함수는 Slack이 제공한 X-Slack-Signature 헤더를 확인하여 들어오는 요청을 인증합니다.

Node.js

/**
 * Verify that the webhook request came from Slack.
 *
 * @param {object} req Cloud Function request object.
 * @param {string} req.headers Headers Slack SDK uses to authenticate request.
 * @param {string} req.rawBody Raw body of webhook request to check signature against.
 */
const verifyWebhook = req => {
  const signature = {
    signingSecret: process.env.SLACK_SECRET,
    requestSignature: req.headers['x-slack-signature'],
    requestTimestamp: req.headers['x-slack-request-timestamp'],
    body: req.rawBody,
  };

  // This method throws an exception if an incoming request is invalid.
  verifyRequestSignature(signature);
};

Python

def verify_signature(request):
    request.get_data()  # Decodes received requests into request.data

    verifier = SignatureVerifier(os.environ["SLACK_SECRET"])

    if not verifier.is_valid_request(request.data, request.headers):
        raise ValueError("Invalid request/credentials.")

Go


// verifyWebHook verifies the request signature.
// See https://api.slack.com/docs/verifying-requests-from-slack.
func verifyWebHook(r *http.Request, body []byte, slackSigningSecret string) (bool, error) {
	timeStamp := r.Header.Get(slackRequestTimestampHeader)
	slackSignature := r.Header.Get(slackSignatureHeader)

	t, err := strconv.ParseInt(timeStamp, 10, 64)
	if err != nil {
		return false, fmt.Errorf("strconv.ParseInt(%s): %w", timeStamp, err)
	}

	if ageOk, age := checkTimestamp(t); !ageOk {
		return false, fmt.Errorf("checkTimestamp(%v): %v %v", t, ageOk, age)
	}

	if timeStamp == "" || slackSignature == "" {
		return false, fmt.Errorf("timeStamp and/or signature headers were blank")
	}

	baseString := fmt.Sprintf("%s:%s:%s", version, timeStamp, body)

	signature := getSignature([]byte(baseString), []byte(slackSigningSecret))

	trimmed := strings.TrimPrefix(slackSignature, fmt.Sprintf("%s=", version))
	signatureInHeader, err := hex.DecodeString(trimmed)

	if err != nil {
		return false, fmt.Errorf("hex.DecodeString(%v): %w", trimmed, err)
	}

	return hmac.Equal(signature, signatureInHeader), nil
}

func getSignature(base []byte, secret []byte) []byte {
	h := hmac.New(sha256.New, secret)
	h.Write(base)

	return h.Sum(nil)
}

// checkTimestamp allows requests time stamped less than 5 minutes ago.
func checkTimestamp(timeStamp int64) (bool, time.Duration) {
	t := time.Since(time.Unix(timeStamp, 0))

	return t.Minutes() <= 5, t
}

Java

/**
 * Verify that the webhook request came from Slack.
 *
 * @param request Cloud Function request object in {@link HttpRequest} format.
 * @param requestBody Raw body of webhook request to check signature against.
 * @return true if the provided request came from Slack, false otherwise
 */
boolean isValidSlackWebhook(HttpRequest request, String requestBody) {
  // Check for headers
  Optional<String> maybeTimestamp = request.getFirstHeader("X-Slack-Request-Timestamp");
  Optional<String> maybeSignature = request.getFirstHeader("X-Slack-Signature");
  if (!maybeTimestamp.isPresent() || !maybeSignature.isPresent()) {
    return false;
  }

  Long nowInMs = ZonedDateTime.now().toInstant().toEpochMilli();

  return verifier.isValid(maybeTimestamp.get(), requestBody, maybeSignature.get(), nowInMs);
}

C#

using Microsoft.AspNetCore.Http;
using System;
using System.Security.Cryptography;
using System.Text;

namespace SlackKnowledgeGraphSearch;

public class SlackRequestVerifier
{
    private const string Version = "v0";
    private const string SignaturePrefix = Version + "=";
    private static readonly byte[] VersionBytes = Encoding.UTF8.GetBytes(Version);
    private static readonly byte[] ColonBytes = Encoding.UTF8.GetBytes(":");

    private readonly byte[] _signingKeyBytes;
    private readonly TimeSpan _timestampTolerance;

    public SlackRequestVerifier(string signingKey, TimeSpan timestampTolerance) =>
        (_signingKeyBytes, _timestampTolerance) =
        (Encoding.UTF8.GetBytes(signingKey), timestampTolerance);

    /// <summary>
    /// Verifies a request signature with the given content, which would
    /// normally have been read from the request beforehand.
    /// </summary>
    public bool VerifyRequest(HttpRequest request, byte[] content)
    {
        if (!request.Headers.TryGetValue("X-Slack-Request-Timestamp", out var timestampHeader) ||
            !request.Headers.TryGetValue("X-Slack-Signature", out var signatureHeader))
        {
            return false;
        }

        // Validate that the request isn't too old.
        if (!int.TryParse(timestampHeader, out var unixSeconds))
        {
            return false;
        }
        var timestamp = DateTimeOffset.FromUnixTimeSeconds(unixSeconds);
        if (timestamp + _timestampTolerance < DateTimeOffset.UtcNow)
        {
            return false;
        }

        // Hash the version:timestamp:content
        using var hmac = new HMACSHA256(_signingKeyBytes);
        AddToHash(VersionBytes);
        AddToHash(ColonBytes);
        AddToHash(Encoding.UTF8.GetBytes(timestampHeader));
        AddToHash(ColonBytes);
        byte[] hash = hmac.ComputeHash(content);
        void AddToHash(byte[] bytes) => hmac.TransformBlock(bytes, 0, bytes.Length, null, 0);

        // Compare the resulting signature with the signature in the request.
        return CreateSignature(hash) == (string) signatureHeader;
    }

    private const string Hex = "0123456789abcdef";
    private static string CreateSignature(byte[] hash)
    {
        var builder = new StringBuilder(SignaturePrefix, SignaturePrefix.Length + hash.Length * 2);
        foreach (var b in hash)
        {
            builder.Append(Hex[b >> 4]);
            builder.Append(Hex[b & 0xf]);
        }
        return builder.ToString();
    }
}

Ruby

# slack-ruby-client expects a Rails-style request object with a "headers"
# method, but the Functions Framework provides only a Rack request.
# To avoid bringing in Rails as a dependency, we'll create a simple class
# that implements the "headers" method and delegates everything else back to
# the Rack request object.
require "delegate"
class RequestWithHeaders < SimpleDelegator
  def headers
    env.each_with_object({}) do |(key, val), result|
      if /^HTTP_(\w+)$/ =~ key
        header = Regexp.last_match(1).split("_").map(&:capitalize).join("-")
        result[header] = val
      end
    end
  end
end

# This is a method of the KGSearch class.
# It determines whether the given request's signature is valid.
def signature_valid? request
  # Wrap the request with our class that provides the "headers" method.
  request = RequestWithHeaders.new request

  # Validate the request signature.
  slack_request = Slack::Events::Request.new request,
                                             signing_secret: @signing_secret
  slack_request.valid?
end

PHP

/**
 * Verify that the webhook request came from Slack.
 */
function isValidSlackWebhook(ServerRequestInterface $request): bool
{
    $SLACK_SECRET = getenv('SLACK_SECRET');

    // Check for headers
    $timestamp = $request->getHeaderLine('X-Slack-Request-Timestamp');
    $signature = $request->getHeaderLine('X-Slack-Signature');
    if (!$timestamp || !$signature) {
        return false;
    }

    // Compute signature
    $plaintext = sprintf('v0:%s:%s', $timestamp, $request->getBody());
    $hash = sprintf('v0=%s', hash_hmac('sha256', $plaintext, $SLACK_SECRET));

    return $hash === $signature;
}

Knowledge Graph API 쿼리

다음 함수는 사용자의 검색어와 함께 Knowledge Graph API에 요청을 보냅니다.

Node.js

/**
 * Send the user's search query to the Knowledge Graph API.
 *
 * @param {string} query The user's search query.
 */
const makeSearchRequest = query => {
  return new Promise((resolve, reject) => {
    kgsearch.entities.search(
      {
        auth: process.env.KG_API_KEY,
        query: query,
        limit: 1,
      },
      (err, response) => {
        console.log(err);
        if (err) {
          reject(err);
          return;
        }

        // Return a formatted message
        resolve(formatSlackMessage(query, response));
      }
    );
  });
};

Python

def make_search_request(query):
    req = kgsearch.entities().search(query=query, limit=1)
    res = req.execute()
    return format_slack_message(query, res)

Go

func makeSearchRequest(query string) (*Message, error) {
	res, err := entitiesService.Search().Query(query).Limit(1).Do()
	if err != nil {
		return nil, err
	}
	return formatSlackMessage(query, res)
}

Java

/**
 * Send the user's search query to the Knowledge Graph API.
 *
 * @param query The user's search query.
 * @return The Knowledge graph API results as a {@link JsonObject}.
 * @throws IOException if Knowledge Graph request fails
 */
JsonObject searchKnowledgeGraph(String query) throws IOException {
  Kgsearch.Entities.Search kgRequest = kgClient.entities().search();
  kgRequest.setQuery(query);
  kgRequest.setKey(apiKey);

  return gson.fromJson(kgRequest.execute().toString(), JsonObject.class);
}

C#

private async Task<SearchResponse> SearchKnowledgeGraphAsync(string query)
{
    _logger.LogInformation("Performing Knowledge Graph search for '{query}'", query);
    var request = _kgService.Entities.Search();
    request.Limit = 1;
    request.Query = query;
    return await request.ExecuteAsync();
}

Ruby

# This is a method of the KGSearch class.
# It makes an API call to the Knowledge Graph Search Service, and formats
# a Slack message as a nested Hash object.
def make_search_request query
  response = @client.search_entities query: query, limit: 1
  format_slack_message query, response
end

PHP

/**
 * Send the user's search query to the Knowledge Graph API.
 */
function searchKnowledgeGraph(string $query): Google_Service_Kgsearch_SearchResponse
{
    $API_KEY = getenv('KG_API_KEY');

    $apiClient = new Google\Client();
    $apiClient->setDeveloperKey($API_KEY);

    $service = new Google_Service_Kgsearch($apiClient);

    $params = ['query' => $query];

    $kgResults = $service->entities->search($params);

    return $kgResults;
}

Slack 메시지 형식 지정

마지막으로 다음 함수는 지식 정보 결과를 서식 있는 Slack 메시지로 형식 지정하여 사용자에게 표시합니다.

Node.js

/**
 * Format the Knowledge Graph API response into a richly formatted Slack message.
 *
 * @param {string} query The user's search query.
 * @param {object} response The response from the Knowledge Graph API.
 * @returns {object} The formatted message.
 */
const formatSlackMessage = (query, response) => {
  let entity;

  // Extract the first entity from the result list, if any
  if (
    response &&
    response.data &&
    response.data.itemListElement &&
    response.data.itemListElement.length > 0
  ) {
    entity = response.data.itemListElement[0].result;
  }

  // Prepare a rich Slack message
  // See https://api.slack.com/docs/message-formatting
  const slackMessage = {
    response_type: 'in_channel',
    text: `Query: ${query}`,
    attachments: [],
  };

  if (entity) {
    const attachment = {
      color: '#3367d6',
    };
    if (entity.name) {
      attachment.title = entity.name;
      if (entity.description) {
        attachment.title = `${attachment.title}: ${entity.description}`;
      }
    }
    if (entity.detailedDescription) {
      if (entity.detailedDescription.url) {
        attachment.title_link = entity.detailedDescription.url;
      }
      if (entity.detailedDescription.articleBody) {
        attachment.text = entity.detailedDescription.articleBody;
      }
    }
    if (entity.image && entity.image.contentUrl) {
      attachment.image_url = entity.image.contentUrl;
    }
    slackMessage.attachments.push(attachment);
  } else {
    slackMessage.attachments.push({
      text: 'No results match your query...',
    });
  }

  return slackMessage;
};

Python

def format_slack_message(query, response):
    entity = None
    if (
        response
        and response.get("itemListElement") is not None
        and len(response["itemListElement"]) > 0
    ):
        entity = response["itemListElement"][0]["result"]

    message = {
        "response_type": "in_channel",
        "text": f"Query: {query}",
        "attachments": [],
    }

    attachment = {}
    if entity:
        name = entity.get("name", "")
        description = entity.get("description", "")
        detailed_desc = entity.get("detailedDescription", {})
        url = detailed_desc.get("url")
        article = detailed_desc.get("articleBody")
        image_url = entity.get("image", {}).get("contentUrl")

        attachment["color"] = "#3367d6"
        if name and description:
            attachment["title"] = "{}: {}".format(entity["name"], entity["description"])
        elif name:
            attachment["title"] = name
        if url:
            attachment["title_link"] = url
        if article:
            attachment["text"] = article
        if image_url:
            attachment["image_url"] = image_url
    else:
        attachment["text"] = "No results match your query."
    message["attachments"].append(attachment)

    return message

Go


package slack

import (
	"encoding/json"
	"fmt"

	"google.golang.org/api/kgsearch/v1"
)

type ItemList struct {
	Items []ItemListElement `json:"itemListElement"`
}
type ItemListElement struct {
	Result EntitySearchResult `json:"result"`
}
type EntitySearchResult struct {
	Name         string       `json:"name"`
	Description  string       `json:"description"`
	DetailedDesc DetailedDesc `json:"detailedDescription"`
	URL          string       `json:"url"`
	Image        Image
}
type DetailedDesc struct {
	ArticleBody string
	URL         string
}
type Image struct {
	ContentURL string
}

func formatSlackMessage(query string, response *kgsearch.SearchResponse) (*Message, error) {
	if response == nil {
		return nil, fmt.Errorf("empty response")
	}

	if response.ItemListElement == nil || len(response.ItemListElement) == 0 {
		message := &Message{
			ResponseType: "in_channel",
			Text:         fmt.Sprintf("Query: %s", query),
			Attachments: []Attachment{
				{
					Color: "#d6334b",
					Text:  "No results match your query.",
				},
			},
		}
		return message, nil
	}

	// The KnowledgeGraph API returns an empty interface. To make this more
	// useful, we convert it back to json, and unmarshal into specific types.
	jsonstring, err := response.MarshalJSON()
	if err != nil {
		return nil, err
	}
	r := &ItemList{}
	if err := json.Unmarshal(jsonstring, r); err != nil {
		return nil, fmt.Errorf("failed to unmarshal json: %w", err)
	}
	result := r.Items[0].Result

	attach := Attachment{Color: "#3367d6"}
	attach.Title = result.Name
	attach.TitleLink = result.DetailedDesc.URL
	attach.Text = result.DetailedDesc.ArticleBody
	attach.ImageURL = result.Image.ContentURL

	message := &Message{
		ResponseType: "in_channel",
		Text:         fmt.Sprintf("Query: %s", query),
		Attachments:  []Attachment{attach},
	}
	return message, nil
}

Java

/**
 * Helper method to copy properties between {@link JsonObject}s
 */
void addPropertyIfPresent(
    JsonObject target, String targetName, JsonObject source, String sourceName) {
  if (source.has(sourceName)) {
    target.addProperty(targetName, source.get(sourceName).getAsString());
  }
}

/**
 * Format the Knowledge Graph API response into a richly formatted Slack message.
 *
 * @param kgResponse The response from the Knowledge Graph API as a {@link JsonObject}.
 * @param query The user's search query.
 * @return The formatted Slack message as a JSON string.
 */
String formatSlackMessage(JsonObject kgResponse, String query) {
  JsonObject attachmentJson = new JsonObject();

  JsonObject responseJson = new JsonObject();
  responseJson.addProperty("response_type", "in_channel");
  responseJson.addProperty("text", String.format("Query: %s", query));

  JsonArray entityList = kgResponse.getAsJsonArray("itemListElement");

  // Extract the first entity from the result list, if any
  if (entityList.size() == 0) {
    attachmentJson.addProperty("text", "No results match your query...");
    responseJson.add("attachments", attachmentJson);

    return gson.toJson(responseJson);
  }

  JsonObject entity = entityList.get(0).getAsJsonObject().getAsJsonObject("result");

  // Construct Knowledge Graph response attachment
  String title = entity.get("name").getAsString();
  if (entity.has("description")) {
    title = String.format("%s: %s", title, entity.get("description").getAsString());
  }
  attachmentJson.addProperty("title", title);

  if (entity.has("detailedDescription")) {
    JsonObject detailedDescJson = entity.getAsJsonObject("detailedDescription");
    addPropertyIfPresent(attachmentJson, "title_link", detailedDescJson, "url");
    addPropertyIfPresent(attachmentJson, "text", detailedDescJson, "articleBody");
  }

  if (entity.has("image")) {
    JsonObject imageJson = entity.getAsJsonObject("image");
    addPropertyIfPresent(attachmentJson, "image_url", imageJson, "contentUrl");
  }

  JsonArray attachmentList = new JsonArray();
  attachmentList.add(attachmentJson);

  responseJson.add("attachments", attachmentList);

  return gson.toJson(responseJson);
}

C#

private string FormatSlackMessage(SearchResponse kgResponse, string query)
{
    JObject attachment = new JObject();
    JObject response = new JObject();

    response["response_type"] = "in_channel";
    response["text"] = $"Query: {query}";

    var element = kgResponse.ItemListElement?.FirstOrDefault() as JObject;
    if (element is object && element.TryGetValue("result", out var entityToken) &&
        entityToken is JObject entity)
    {
        string title = (string) entity["name"];
        if (entity.TryGetValue("description", out var description))
        {
            title = $"{title}: {description}";
        }
        attachment["title"] = title;
        if (entity.TryGetValue("detailedDescription", out var detailedDescriptionToken) &&
            detailedDescriptionToken is JObject detailedDescription)
        {
            AddPropertyIfPresent(detailedDescription, "url", "title_link");
            AddPropertyIfPresent(detailedDescription, "articleBody", "text");
        }
        if (entity.TryGetValue("image", out var imageToken) &&
            imageToken is JObject image)
        {
            AddPropertyIfPresent(image, "contentUrl", "image_url");
        }
    }
    else
    {
        attachment["text"] = "No results match your query...";
    }
    response["attachments"] = new JArray { attachment };
    return response.ToString();

    void AddPropertyIfPresent(JObject parent, string sourceProperty, string targetProperty)
    {
        if (parent.TryGetValue(sourceProperty, out var propertyValue))
        {
            attachment[targetProperty] = propertyValue;
        }
    }
}

Ruby

# This is a method of the KGSearch class.
# It takes a raw SearchResponse from the Knowledge Graph Search Service,
# and formats a Slack message.
def format_slack_message query, response
  result = response.item_list_element&.first&.fetch "result", nil
  attachment =
    if result
      name = result.fetch "name", nil
      description = result.fetch "description", nil
      details = result.fetch "detailedDescription", {}
      { "title"      => name && description ? "#{name}: #{description}" : name,
        "title_link" => details.fetch("url", nil),
        "text"       => details.fetch("articleBody", nil),
        "image_url"  => result.fetch("image", nil)&.fetch("contentUrl", nil) }
    else
      { "text" => "No results match your query." }
    end
  { "response_type" => "in_channel",
    "text"          => "Query: #{query}",
    "attachments"   => [attachment.compact] }
end

PHP

/**
 * Format the Knowledge Graph API response into a richly formatted Slack message.
 */
function formatSlackMessage(Google_Service_Kgsearch_SearchResponse $kgResponse, string $query): string
{
    $responseJson = [
        'response_type' => 'in_channel',
        'text' => 'Query: ' . $query
    ];

    $entityList = $kgResponse['itemListElement'];

    // Extract the first entity from the result list, if any
    if (empty($entityList)) {
        $attachmentJson = ['text' => 'No results match your query...'];
        $responseJson['attachments'] = $attachmentJson;

        return json_encode($responseJson);
    }

    $entity = $entityList[0]['result'];

    // Construct Knowledge Graph response attachment
    $title = $entity['name'];
    if (isset($entity['description'])) {
        $title = $title . ' ' . $entity['description'];
    }
    $attachmentJson = ['title' => $title];

    if (isset($entity['detailedDescription'])) {
        $detailedDescJson = $entity['detailedDescription'];
        $attachmentJson = array_merge([
            'title_link' => $detailedDescJson[ 'url'],
            'text' => $detailedDescJson['articleBody'],
        ], $attachmentJson);
    }

    if (isset($entity['image'])) {
        $imageJson = $entity['image'];
        $attachmentJson['image_url'] = $imageJson['contentUrl'];
    }

    $responseJson['attachments'] = array($attachmentJson);

    return json_encode($responseJson);
}

Slack API 제한 시간

Slack API는 함수가 웹훅 요청 수신 후 3초 이내에 응답할 것으로 예상합니다.

이 튜토리얼의 명령어는 일반적으로 3초 이내에 응답합니다. 실행 시간이 더 긴 명령어의 경우 태스크 큐 역할을 하는 Pub/Sub 주제에 요청을 푸시(response_url 필드 포함)하도록 함수를 구성하는 것이 좋습니다.

그런 다음 Pub/Sub로 트리거되는 두 번째 함수를 만들어 작업을 처리하고 결과를 Slack의 response_url로 다시 보낼 수 있습니다.

슬래시 명령어 사용

  1. 함수 배포가 완료되면 이 명령어를 Slack 채널에 입력합니다.

    /kg giraffe

    'giraffe'에 대한 Knowledge Graph 항목이 표시됩니다.

  2. 로그를 확인하여 함수 실행 출력을 확인합니다.

    gcloud functions logs read --limit 100
    

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

프로젝트를 삭제하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

Cloud 함수 삭제

이 가이드에서 배포한 Cloud Function을 삭제하려면 다음 명령어를 실행합니다.

Node.js

gcloud functions delete nodejs-slack-function --gen2 --region REGION 

Python

gcloud functions delete python-slack-function --gen2 --region REGION 

Go

gcloud functions delete go-slack-function --gen2 --region REGION 

Java

gcloud functions delete java-slack-function --gen2 --region REGION 

C#

gcloud functions delete csharp-slack-function --gen2 --region REGION 

Ruby

gcloud functions delete ruby-slack-function --gen2 --region REGION 

PHP

gcloud functions delete php-slack-function --gen2 --region REGION 

Google Cloud 콘솔에서 Cloud Functions를 삭제할 수도 있습니다.