継続は力なり

タイトル通り定期的な更新を心掛けるブログです。

The next-generation Slack platform に入門する[ローカルで動作編]

タダです.

タイトルの通り The next-generation Slack platform を使ってみたいというモチベーションから試してみた内容を備忘録で何回かに分けて記録していきます.今回はチュートリアルにある Hello World App の開発をやってみます.なお,他にもサンプルはありドキュメントから確認できます.

api.slack.com

事前準備

事前準備として有料の Slack のプランを契約している環境を用意する必要がありますが,加えて Slack の CLI を準備します.インストール後に対象のワークスペースとの認証を完了させ,slack auth listで対象のワークスペースが表示されれば事前準備完了です.

❯ slack version
Using slack v2.16.0
$ slack auth list

taddyteam (Team ID: hogehogehoge)
User ID: hogehoge
Last Updated: 2024-01-13 16:27:37 +09:00
Authorization Level: Workspace
❯ slack       
✨ CLI to create, run, and deploy Slack apps

📚 Get started by reading the docs:
    https://api.slack.com/automation

USAGE
  $ slack <command> <subcommand> [flags]

COMMANDS
  app
    delete      Delete the app
    install     Install the app to a team
    list        List all teams that have installed the app
    uninstall   Uninstall the app from a team
  auth
    list        List all authorized accounts
    login       Log in to a Slack account
    logout      Log out of a team
    revoke      Revoke an authentication token
    token       Collect a service token
  collaborator
    add         Add a collaborator to your app
    list        List all collaborators of an app
    remove      Remove a collaborator from an app
  datastore
    delete      Delete an item from a datastore
    get         Get an item from a datastore
    put         Create or replace an item in a datastore
    query       Query a datastore for items
    update      Create or update an item in a datastore
  env
    add         Add an environment variable to the app
    list        List all environment variables for the app
    remove      Remove an environment variable from the app
  external-auth
    add         Initiate the OAuth2 flow for a provider in your app
    add-secret  Add the client secret for a provider in your app
    remove      Remove provider token(s) from your app
    select-auth Set developer authentication to be used for a specific workflow
  function
    distribute  Manage who can view functions published by your app
  manifest
    info        Display the app manifest when run in a project directory
    validate    Validate the app manifest generated by a project
  platform
    activity    Display the app activity logs from the Slack Platform
    deploy      Deploy the app to the Slack Platform
    run         Start a local server to develop and run the app locally
  trigger
    access      Manage who can use your triggers
    create      Create a trigger for a workflow
    delete      Delete an existing trigger
    info        Get details for a specific trigger
    list        List details of existing triggers
    update      Updates an existing trigger
  create            Create a Slack project
  doctor            Check and report on system and app information
  feedback          Share feedback about your experience or project
  help              Help about any command
  samples           List available sample apps
  upgrade           Checks for available updates to the CLI or SDK
  version           Print the version number

FLAGS
  -a, --app string           use a specific app ID or environment
      --config-dir string    use a custom path for system config directory
  -e, --experiment strings   use the experiment(s) in the command
  -f, --force                ignore warnings and continue executing command
  -h, --help                 help for slack
      --no-color             remove styles and formatting from outputs
  -s, --skip-update          skip checking for latest version of CLI
  -w, --team string          select workspace or organization by team name or ID
      --token string         set the access token associated with a team
  -v, --verbose              print debug logging and additional info
      --version              version for slack

GLOBAL ALIASES
  activity           platform > activity
  delete             app   > delete
  deploy             platform > deploy
  install            app   > install
  list               auth  > list
  login              auth  > login
  logout             auth  > logout
  run                platform > run
  uninstall          app   > uninstall

EXAMPLE
  $ slack login   # Log in to your Slack account
  $ slack create  # Create a new Slack app
  $ slack run     # Start a local development server
  $ slack deploy  # Deploy to the Slack Platform

EXPERIMENTS
  None

ADDITIONAL HELP
  For more information about a specific command, run:
  $ slack <command> <subcommand> --help

  For guides and documentation, head over to https://api.slack.com/automation

インストールのドキュメント

api.slack.com

ローカルのプロジェクト環境構築

slack create hello-world-app --template https://github.com/slack-samples/deno-blank-template でローカルに空のプロジェクトを作ることができます.slack create hello-world-app --template https://github.com/slack-samples/deno-hello-world で pre-built の app も作れるようですが,今回は空のプロジェクトにしました.

❯ slack create hello-world-app --template https://github.com/slack-samples/deno-blank-template
⚙️  Creating a new Slack app in ~/tmp/hello-world-app

📦 Installed project dependencies

✨ hello-world-app successfully created

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

📋 Follow the steps below to begin development
   Change into your project directory with cd hello-world-app/
   Develop locally and see changes in real-time with slack run
   When you're ready to deploy for production use slack deploy
❯ cd hello-world-app;ls -l
total 56
-rw-r--r--@ 1 tady  staff  1090 Jan 13 16:42 LICENSE
-rw-r--r--@ 1 tady  staff  6280 Jan 13 16:42 README.md
drwxr-xr-x@ 3 tady  staff    96 Jan 13 16:42 assets
-rw-r--r--@ 1 tady  staff   624 Jan 13 16:42 deno.jsonc
-rw-r--r--@ 1 tady  staff   158 Jan 13 16:42 import_map.json
-rw-r--r--@ 1 tady  staff   505 Jan 13 16:42 manifest.ts
-rw-r--r--@ 1 tady  staff   127 Jan 13 16:42 slack.json

まず確認するのは functions, triggers, workflowsディレクトリです.役割は公式記事に解説があったのでそちらのリンクを貼ります.

qiita.com

Slack App のトリガーを作る

Slack App を実行するトリガーを作っていきます.slack trigger create --triger-def "triggers/greeting_trigger.ts" を実行すると事前準備で認証しているワークスペースhello-world-app (local) が表示されます.

❯ slack trigger create --trigger-def "triggers/greeting_trigger.ts"
? Select a team Install to a new team
? Install to a new team taddyteam hogehogehoge

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

? Choose an app environment Local 
📚 App Manifest
   Created app manifest for "hello-world-app (local)" in "taddyteam"

🏠 App Install
   Installing "hello-world-app (local)" app to "taddyteam"
   Finished in 2.8s

⚡ Trigger successfully created!

   Send a greeting (local) Ft06E4V2M2HF (shortcut)
   Created: 2024-01-13 17:04:06 +09:00 (1 second ago)
   Collaborators:
     Sadayoshi Tada @tada hogehoge
   Can be found and used by:
     everyone in the workspace
   https://slack.com/shortcuts/ABCD1234EFGH/01d8db3db6ea1a9e05012a90028ed678

また, https://slack.com/shortcuts/ABCD1234EFGH/01d8db3db6ea1a9e05012a90028ed678(これは偽のURLです) の URL をコピーしてワークスペースのパブリックチャンネルにポストするとアプリが反応します.

Start Window でメッセージを送る相手とその内容を選べるのですが,この段階でローカル側で slack run コマンドを実行してローカルのサーバーを立ち上げます.メッセージと送る相手を選択して実行するとメッセージが返ってきました.

レスポンスの内容を変えてみる

固定のレスポンスになっている箇所で追加のメッセージを入れてみました.オハヨウ って返すだけですが,追加のメッセージを返してくれるようになりました.

export default SlackFunction(
  GreetingFunctionDefinition,
  ({ inputs }) => {
    const { recipient, message } = inputs;
    const salutations = ["Hello", "Hi", "Howdy", "Hola", "Salut", "オハヨウ"];
    const salutation =
      salutations[Math.floor(Math.random() * salutations.length)];
    const greeting =
      `${salutation}, <@${recipient}>! :wave: Someone sent the following greeting: \n\n>${message}`;
    return { outputs: { greeting } };
  },
);

まとめ

ローカルで Slack App を動かしてみてました.次はデプロイをしてみたり,修正をいれてからの反映をやってみます.