Menu

Discord Notification Integration

このガイドでは、Discord webhookの設定方法と、ユーティリティメソッドsendDiscordNotificationの使用方法を説明し、Discordを通じてタイムリーな通知を受け取れるようにします。

Discord Webhookの作成

  1. Discordサーバーを開き、通知専用のチャンネルを作成します。

内部通知用の場合は、プライバシーチャンネルを有効にします。すべてのメンバーに表示される公開通知の場合は、無効にします。

create channel
  1. チャンネル設定を開きます
channel settings
  1. 新しいWebhookを作成し、Webhook URLをコピーします
create webhook
create webhook

Webhook URLを環境変数DISCORD_WEBHOOK_URLに貼り付けます。複数のWebhook URLを作成する場合は、追加の環境変数を追加するか、コードに直接ハードコーディングできます。

sendDiscordNotificationの概要と使用方法

sendDiscordNotificationlib/discord/notifications.tsに配置されており、2つのパラメータが必要です:

  • webhookUrl:前のステップでコピーしたWebhook URL。明示的なURLを提供しない場合は、process.env.DISCORD_WEBHOOK_URLにフォールバックします。
  • payload:これは通知コンテンツであり、表示したい内容に基づいて設計する必要があります。次のステップで例を示します。
lib/discord/notifications.ts
export async function sendDiscordNotification({
  webhookUrl,
  payload,
}: {
  webhookUrl: string;
  payload: DiscordWebhookPayload;
}): Promise<{ success: boolean; error?: string }> {
  webhookUrl = webhookUrl || process.env.DISCORD_WEBHOOK_URL || '';
 
  if (!webhookUrl) {
    const message = "Discord webhook URLが提供されていません";
    console.warn(message);
    return { success: false, error: message };
  }
 
  try {
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });
 
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Discord webhookが失敗しました:', response.status, errorText);
      return {
        success: false,
        error: `Discord webhookが失敗しました: ${response.status} ${errorText}`,
      };
    }
 
    console.log('Discord通知が正常に送信されました。');
    return { success: true };
  } catch (error) {
    const errorMessage = getErrorMessage(error);
    console.error('Discord通知の送信中にエラーが発生しました:', errorMessage);
    return { success: false, error: errorMessage };
  }
}

通知の送信

上記のメソッドを使用する際、送信機能の中核となる作業は通知コンテンツの設計です。

Discord Payloadは以下の要素をサポートしています:

  • content:プレーンテキスト(最大2000文字)。
  • embedstitledescriptioncolorfieldsfooterthumbnailを含むオブジェクトの配列。
  • fields:embedごとに最大25個。カラムレイアウトにはinline: trueを使用します。
  • timestamp:embedフッター用のISO文字列。

通常、payloadを自分で記述する必要はありません。AIに通知に表示したい情報を伝え、lib/discord/notifications.tsを選択するだけで、AIがこの作業を完了してくれます。

以下は簡単な使用例です:

  • 基本的なテキストアラート
import { sendDiscordNotification } from '@/lib/discord/notifications';
 
await sendDiscordNotification({
  webhookUrl: '', // オプション。空にするとDISCORD_WEBHOOK_URLを使用します
  payload: {
    content: `新規ユーザー: ${user.email}`,
  },
});
  • リッチembed例
await sendDiscordNotification({
  payload: {
    embeds: [
      {
        title: '新規サブスクリプションアップグレード',
        description: `ユーザー **${user.name}** が **${plan.title}** にアップグレードしました`,
        color: 0x00ff7f,
        fields: [
          { name: 'オーナー', value: user.email, inline: true },
          { name: 'プラン', value: plan.title, inline: true },
        ],
        timestamp: new Date().toISOString(),
        footer: { text: '課金サービス' },
      },
    ],
  },
});