🐈

Next.jsアプリにSlack通知機能を実装する

2024/10/03に公開

0.参考

https://zenn.dev/bje35149/articles/65bb53ffaf3875

1.Slack Appの作成

https://api.slack.com/apps?new_app=1

Slack APIの利用にはSlack Appの作成が必要です。
Slack API にアクセスし、新しいアプリを作成します。

Create an app

From scratch

Name app & choose workspace

OAuth & Permissions

Scopes

Install OAuth Token

2.ライブラリのインストール

npm install @slack/web-api

3.Slack通知用の関数

src/utils/slack.ts
import { WebClient } from '@slack/web-api';

const token = process.env.SLACK_BOT_TOKEN;
const channel = process.env.SLACK_CHANNEL || '#default-channel';
const web = new WebClient(token);

export async function sendSlackNotification(message: string): Promise<void> {
  try {
    const userIds = ['hoge', 'fuga', 'foo'];
    const mentions = userIds.map(id => `<@${id}>`).join(' ');

    const botUsername = "通知ボット";

    await web.chat.postMessage({
      channel: channel,
      text: `${mentions} ${message}`,
      username: botUsername,
      icon_emoji: ':robot_face:',
    });
    
    console.log('Slack notification sent successfully');
  } catch (error) {
    console.error('Failed to send Slack notification', error);
  }
}

Bot User OAuth Token を環境変数に設定

.env
SLACK_BOT_TOKEN="xoxp-xxxxxxx"
SLACK_CHANNEL="#hoge"

Discussion