[Twilio+Node.js+AWS Lambda] サーバー通知を SMS で自動配信する Web アプリケーションの作成

[Twilio+Node.js+AWS Lambda] サーバー通知を SMS で自動配信する Web アプリケーションの作成

AWS Lambda で動作するアプリケーションに対し、 Twilio API を使用した SMS 通知の自動配信機能を追加する方法について紹介します。
参考ページ: https://www.twilio.com/en-us/blog/server-notifications-node-express

作業環境

バージョン

node: 22.13.1
npm: 10.9.2
node_modules/twilio: 5.4.5

twilioNotifications.js ミドルウェアとは

twilioNotifications.js は、 Twilio を使った通知機能を提供するミドルウェアです。このミドルウェアを index.js でインポートし、エラー発生時に管理者へ SMS 通知を送る処理を実装します。

twilioNotifications.js の作成

以下の middleware/twilioNotifications.js を作成します。

middleware/twilioNotifications.js

const twilio = require("twilio");

// 各環境変数については本記事にて後述
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

const client = new twilio(accountSid, authToken);

/**
 * Twilio を使って SMS を送信するミドルウェア関数
 * @param {string} to - 送信先の電話番号
 * @param {string} message - 送信するメッセージ
 * @returns {Promise<string>} - 送信したメッセージの SID
 */
async function sendNotification(to, message) {
    if (!to || !message) {
        throw new Error("Missing 'to' or 'message' parameter");
    }

    try {
        const response = await client.messages.create({
            body: message,
            from: twilioPhoneNumber,
            to: to,
        });

        console.log(`SMS sent to ${to}: ${message}`);
        return response.sid;
    } catch (error) {
        console.error("Error sending SMS:", error);
        throw new Error("Failed to send SMS");
    }
}

module.exports = { sendNotification };

環境変数の設定

AWS Lambda の環境変数に Twilio の認証情報などを設定します。

環境変数 説明
TWILIO_ACCOUNT_SID Twilio のアカウント SID
TWILIO_AUTH_TOKEN Twilio の認証トークン
TWILIO_PHONE_NUMBER Twilio の送信元電話番号

twilioNotifications.js の使用例

このミドルウェアを Lambda 関数で使用します。今回は例外の通知をテストしたいので、わざと失敗するコードを書きます。

index.js

const twilioNotifications = require("./middleware/twilioNotifications");

exports.handler = async (event) => {
    let body;
    try {
        body = JSON.parse(event.body);
    } catch (error) {
        return {
            statusCode: 400,
            body: JSON.stringify({error: "Invalid JSON format"}),
        };
    }

    const {to, message} = body;

    if (!to || !message) {
        return {
            statusCode: 400,
            body: JSON.stringify({error: "Missing 'to' or 'message' in request body"}),
        };
    }

    try {
        // 何らかの処理(ここでは `message: "error"` の場合にエラーを発生)
        if (message.toLowerCase() === "error") {
            throw new Error("Intentional error for testing Twilio SMS notifications");
        }

        return {
            statusCode: 200,
            body: JSON.stringify({message: "Processing successful"}),
        };
    } catch (error) {
        console.error("Error occurred:", error.message);

        // Twilio ミドルウェアを使ってエラーメッセージを送信
        try {
            await twilioNotifications.sendNotification(to, `Lambda Error: ${error.message}`);
        } catch (twilioError) {
            console.error("Failed to send Twilio notification:", twilioError.message);
        }

        return {
            statusCode: 500,
            body: JSON.stringify({error: error.message}),
        };
    }
};

テスト用 JSON は以下の通りです。 to で送信先の電話番号を指定します。(例: `+811234567890)

{
  "body": "{\"to\": \"****\", \"message\": \"error\"}"
}

動作検証

API を通じた Lambda 関数の呼び出し後、次のメッセージが送信されるのを確認しました。

$ curl https://****.amazonaws.com/test-twilio-notification -H "Content-Type: application/json" -d '{"to": "****", "message": "error"}'
{"error":"Intentional error for testing Twilio SMS notifications"}

test-twilio-nortification

おわりに

Twilio API を利用すれば、 Web アプリケーションに対し容易にエラー時 SMS 通知の実装を追加できることが分かりました。

前回、 SMS に自動返信する Web アプリについては こちら
次回、未定。

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.