🕌

Twilio でのSMSをSlackで受け取る [functions]

2023/06/18に公開

Environment Variables に SLACK_WEBHOOK_PATH を設定して以下

const axios = require('axios'); // fetch APIは使えない

exports.handler = (context, event, callback) => {
  const twiml = new Twilio.twiml.VoiceResponse();
  const { To, From, Body } = event;
  const body = JSON.stringify({
    attachments: [
      {
        fallback: `${From}: ${Body}`,
        text: `Received SMS from ${From}`,
        fields: [
          {
            title: "Sender",
            value: From,
            short: true
          },
          {
            title: "Receiver",
            value: To,
            short: true
          },
          {
            title: "Message",
            value: Body.replace(/"/g, '\"'), // JSON内に " の存在を許す
            short: false
          }
        ],
        color: "#5555AA"
      }
    ]
  });

  const url = context.SLACK_WEBHOOK_PATH;
  const method = 'post'
  const headers = { 'Content-Type': 'application/json' };
  
  axios.post(url, body, { headers })
    .finally(() => callback(null, new Twilio.twiml.MessagingResponse()))
};

Discussion