フリーランスWebエンジニア Omori

Next.js Logo

Slack API chat.postMessageを使って、メッセージの送信

プログラムからメッセージを送信する方法は、2種類のSlack APIがあります。

  1. incoming webhooks
  2. chat.postMessage

今回は、chat.postMessageの使い方を紹介します。

Incoming webhooksについてはこちら

Slack Appの作成

  1. https://api.slack.com/apps へアクセス
  2. 「Create New App」を押下
  3. Create an appで「From scratch」を選択
  4. 「App Name」と「Workspace」を選択し、Create Appを押下
  5. サイドバーFeaturesからOAuth&Permissionsを選択
  6. Scopes > Bot Token ScopesからAdd an OAuth scopeを押下
  7. 「chat:write」を選択
  8. OAuth Tokens for Your WorkspaceからInstall to Workspaceを押下
  9. Allowを押下
  10. OAuth Tokens for Your Workspace > Bot User OAuth Token にトークンが発行される
  11. メッセージを送りたいチャンネル詳細 > Integration からAdd appsで、作成したアプリをチャンネルに追加

Node.js Slack SDKを利用して、chat.postMessageをコールし、Slackへメッセージ送信

bash
npm install @slack/web-api
npm install dotenv
.env
SLACK_TOKEN=取得したBot User OAuth Token
CHANNEL_ID=チェンネルID.Slackのチェンネル詳細モーダルから取得できる
index.js
require('dotenv').config();
const { WebClient } = require("@slack/web-api");
const client = new WebClient(process.env.SLACK_TOKEN, {})
 
async function main() {
  try {
    const result = await client.chat.postMessage({
      channel: process.env.CHANNEL_ID,
      //▼ シンプルテキスト: text
      //text: "Hello world via Slack API",
      //▼ 構造化テキスト: blocks  
      blocks: [
        {
          "type": "header",
          "text": {
            "type": "plain_text",
            "text": "お問合せがありました!",
          }
        },
        {
          "type": "section",
          "text": {
            "type": "mrkdwn",
            "text": `>${heading("*会社名*")}: テスト株式会社\n>${heading("*氏名*")}: テスト太郎\n>${heading("*メールアドレス*")}: test@test.com\n>${heading("*問合せ内容*")}: テストです\n`
          }
        },
      ]
    });
  } catch(error) {
    console.log(error);
  }
}
 
main();
 
function heading(word) {
  return word.padStart(9, " ")
}
bash
node index.js

以下のようなメッセージを確認できました。padStartを用いて、文字列を整形しています。 画像

©Omori

MEOW!