Site cover image

Site icon imageおかしんワークス

ビジネステクノロジーエンジニア @okash1n のブログです

Slack Platform触ってみた

何番煎じかわかりませんが、Slack Platformのチュートリアルを触ってみます。

今までのSlack APIを使ったアプリとは違い、Slackのクラウド環境で実行されるので、GASやAWS Lambdaなどを利用する必要がありません。

各種ドキュメント

Slack Platformの構成を理解する

Slack Platformアプリケーションの構成要素

Image in a image block
manifest.ts

アプリの名前や、スコープを設定したりするTypescriptファイルです。

// manifest.ts
import { Manifest } from "deno-slack-sdk/mod.ts";
// Import your workflow
import GreetingWorkflow from "./workflows/greeting_workflow.ts";

export default Manifest({
  
  // This is the internal name for your app.
  // It can contain spaces (e.g., "My App")
  name: "deno-hello-world",

  // A description of your app that will help users decide whether to use it.
  description: "A sample that demonstrates using a function, workflow and trigger to send a greeting",

  // Your app's profile picture that will appear in the Slack client.
  icon: "assets/default_new_app_icon.png",

  // A list of all workflows your app will use.
  workflows: [GreetingWorkflow],

  // If your app communicates to any external domains, list them here.
  outgoingDomains: [], // e.g., myapp.tld

  // Bot scopes can be declared here.
  // For the beta, you can keep these as-is.
  botScopes: ["commands", "chat:write", "chat:write.public"],
});

slack.json

後述するSlack CLIがSDKの依存関係とやり取りする際に利用され、SDKによって実装されるスクリプトフックが含まれている。

/functions

関数は、「チャンネル作成」や「メッセージ送信」などの単体のSlackAPIで行えるようなアクションが定義されたBuilt-in functionsと、自身で定義するCustom functionsがあります。

Built-in functions

Built-in functionsは以下のようにSchema.slack.functionsの子になっており、単独で使用したり、後述するワークフローのステップとして利用することができます。

import { DefineWorkflow, Schema } from "deno-slack-sdk/mod.ts";

// Define a workflow that can pass the parameters for the built-in function
const myWorkflow = DefineWorkflow({
  callback_id: "channel-creator",
  title: "Channel Creator",
  input_parameters: {
    properties: { channel_name: { type: Schema.types.string } },
    required: ["channel_name"],
  },
});

const createChannelStep = myWorkflow.addStep(
  Schema.slack.functions.CreateChannel,
  {
    channel_name: myWorkflow.inputs.channel_name,
    is_private: false,
  },
);

export default myWorkflow;
CreateChannel という Built-in function を使って、チャンネルを作成するワークフロー
Custom functions

Custom functionsは以下の6つの要素を指定して定義します

FieldDescription
callback_idコールバックIDは、関数を一意に識別するための文字列で、他の関数と共有できず、変更することは推奨されない。変更すると、関数がアプリから削除され、新しいコールバックIDで作成され、古い関数を参照するワークフローが破損する可能性がある
title関数をわかりやすく識別するための文字列
source_file関数ハンドラファイルへの相対パスであり、フォルダに関数をネストする場合は更新する必要がある
description(Optional) 関数が何をするかを簡潔にまとめた説明
input_parameters(Optional) 関数で利用可能な入力パラメータを定義するオブジェクトであり、各トップレベルのプロパティが1つの入力パラメータの名前を定義する
output_parameters(Optional) 関数が返す出力パラメータを定義するオブジェクトであり、各トップレベルのプロパティが1つの出力パラメータの名前を定義する
// /slack-samples/deno-hello-world/functions/greeting_function.ts
import { DefineFunction, Schema, SlackFunction } from "deno-slack-sdk/mod.ts";

export const GreetingFunctionDefinition = DefineFunction({
  callback_id: "greeting_function",
  title: "Generate a greeting",
  description: "Generate a greeting",
  source_file: "functions/greeting_function.ts",
  input_parameters: {
    properties: {
      recipient: {
        type: Schema.slack.types.user_id,
        description: "Greeting recipient",
      },
      message: {
        type: Schema.types.string,
        description: "Message to the recipient",
      },
    },
    required: ["message"],
  },
  output_parameters: {
    properties: {
      greeting: {
        type: Schema.types.string,
        description: "Greeting for the recipient",
      },
    },
    required: ["greeting"],
  },
});

/workflows

ワークフローを使用すると、関数のチェーンを構築することで複雑で適応性の高い自動化を作成できます。

Custom functionsを使用したり、Built-in functionsから選択したり、両方を組み合わせることで、必要なワークフローを取得できます。

/triggers

トリガーを追加して、ワークフローの開始方法とタイミングをカスタマイズできます。

Slack内のイベントに反応したり、スケジュールに基づいて実行したり、Webhookを使用して外部サービスからトリガーを受けたりすることができます。

WebhookをGASに飛ばして、GASで処理して、Slackに返す、というような処理はよくやるかと思いますが、Slack Platformでは最初からトリガーが用意されているので、そこの処理が書きやすそうです。

/datastores

DatastoresはSlack Platformが提供するデータベースで、DynamoDBで動いています。

table, items, attributes で構成され、itemsattributesのコレクションであり、tableitemsのコレクションになっています。

うまく作ってあげれば問い合わせシステムなんかもSlack Platformだけで完結できそうな気がします。

早速やってみる

以下の通りにSlack CLIの準備をします

brewcaskにも存在してるのでbrew install slack-cli でもインストールできます。インストールしたら、slack loginでログインします。

アプリの作成

Scaffolded projectを選択して作成します

$ slack create slack-app-test
? Select a template to build from: [Use arrows to move]

  Hello World
  A simple workflow that sends a greeting

> Scaffolded project
  A solid foundational project that uses a Slack datastore

  Blank project
  A, well.. blank project

  Check out more samples at api.slack.com/future/samples
? Select a template to build from: Scaffolded project

⚙️  Creating a new Slack app in ~/slack-app-test

📦 Installed project dependencies

✨ my-app successfully created

🧭 Explore the documentation to learn more
   Read the README.md or peruse the docs over at api.slack.com/future
   Find available commands and usage info with slack help

📋 Follow the steps below to begin development
   Change into your project directory with cd my-app
   Develop locally and see changes in real-time with slack run
   When you're ready to deploy for production use slack deploy
   Create a trigger to invoke your workflows slack trigger create

トリガーの作成

slack createコマンドでアプリを作成するとアプリ名のディレクトが作成されるので、そこにcdして作業します

まずは以下のコマンドでトリガーを作成します。今回はLocalを利用。

❯ slack trigger create       
⚡ Searching for trigger definition files under 'triggers/*'...
   Found 1 trigger definition file

? Choose a trigger definition file: triggers/sample_trigger.ts
? Select a workspace Install to a new workspace
? Pick a workspace for the app {スペース名} {スペースID}

🔔 If you leave this workspace, you can no longer manage the installed apps
   Installed apps will belong to the workspace if you leave the workspace

? Choose an app environment Local Not installed

⚠️  Breaking Changes Announced (February 2023)
   Impacts apps using datastores, external auth, interactivity, and built-in functions
   Learn more: https://api.slack.com/future/changelog

📚 App Manifest
   Created app manifest for "slack-app-test (dev)" in "スペース名" workspace

🏠 Workspace Install
   Installed "slack-app-test (dev)" app to "スペース名" workspace
   Finished in 1.6s

⚡ Trigger created
   Trigger ID:   Ft0********
   Trigger Type: shortcut
   Trigger Name: Sample trigger
   Trigger Created Time: 2023-03-14 16:06:26 +09:00
   Trigger Updated Time: 2023-03-14 16:06:26 +09:00
   URL: https://slack.com/shortcuts/Ft0********/afa*********************132f

この一番最後にあるURLを次のステップで使います。

ローカル開発モードでアプリを実行

slack runコマンドを実行すると、CLIがローカルサーバーを起動します。Connectedになるとイベント待ちの状態です。

この状態で、先のステップのURLを接続しているワークスペースのオープンチャンネルに貼ると、以下のようにショートカットがチャンネルに展開されます。

Image in a image block

スタートを押すと、フォームが開きます。

Image in a image block

フォームを送信すると、以下のように指定したチャンネルに投稿されます。

Image in a image block

とりあえずサンプルコードは(当然ですが)ローカルで動いたので、次はなんかアプリを作ってみたいと思います。

これがSlackのクラウド環境にデプロイできて、動かせるとなると非常に楽しみですね。Git管理して、GitHub Actionsでデプロイとか出来るのかな?