mcpField
T
twilio-communications

twilio-communications

github.com/davila7開発33.0k213 回インストール1 日前に更新
リポジトリ

twilio-communications について

Twilio を使った通信機能を開発する人向けのスキルガイドです。SMS、Verify、TwiML による IVR の実装パターンと、配信やセキュリティ上の注意点を扱います。

主な機能

  1. 01SMS 送信と配信状況コールバック
  2. 02Verify による電話番号確認と MFA
  3. 03TwiML による音声メニュー
  4. 04認証情報・署名・レート制限の注意点

活用シーン

  1. 01通知、取引メッセージ、リマインダーの送信
  2. 02登録・ログイン・取引時の電話番号確認
  3. 03電話メニュー、音声サポート、留守番電話の構築

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/davila7/claude-code-templates --skill twilio-communications

インストール後、Claude Code で/twilio-communicationsを入力して読み込まれたか確認します。

詳細

Twilio Communications

Patterns

SMS Sending Pattern

Twilio で SMS メッセージを送信するための基本パターンです。 電話番号のフォーマット、メッセージ配信、配信ステータスのコールバックといった基本を扱います。

Key considerations:

  • 電話番号は E.164 形式(+1234567890)である必要があります
  • デフォルトのレート制限: 毎秒 80 メッセージ(MPS)
  • 160 文字を超えるメッセージは分割されます(そのぶん料金も高くなります)
  • キャリアのフィルタリングによってメッセージがブロックされる場合があります(特に米国の番号宛て)

When to use: ['Sending notifications to users', 'Transactional messages (order confirmations, shipping)', 'Alerts and reminders']

from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
import os
import re

class TwilioSMS:
    """
    SMS sending with proper error handling and validation.
    """

    def __init__(self):
        self.client = Client(
            os.environ["TWILIO_ACCOUNT_SID"],
            os.environ["TWILIO_AUTH_TOKEN"]
        )
        self.from_number = os.environ["TWILIO_PHONE_NUMBER"]

    def validate_e164(self, phone: str) -> bool:
        """Validate phone number is in E.164 format."""
        pattern = r'^\+[1-9]\d{1,14}$'
        return bool(re.match(pattern, phone))

    def send_sms(
        self,
        to: str,
        body: str,
        status_callback: str = None
    ) -> dict:
        """
        Send an SMS message.

        Args:
            to: Recipient phone number in E.164 format
            body: Message text (160 chars = 1 segment)
            status_callback: URL for delivery status webhooks

        Returns:
            Message SID and status
        """
        # Validate phone number format
        if not self.validate_e164(to):
            return {
                "success": False,
                "error": "Phone number must be in E.164 format (+1234567890)"
            }

        # Check message length (warn about segmentation)
        segment_count = (len(body) + 159) // 160
        if segment_count > 1:
            print(f"Warning: Message will be sent as {segment_count} segments")

        try:
            message = self.client.messages.create(
                to=to,
                from_=self.from_number,
                body=body,
                status_callback=status_callback
            )

            return {
                "success": True,
                "message_sid": message.sid,
                "status": message.status,
                "segments": segment_count
            }

        except TwilioRestException as e:
            return self._handle_error(e)

    def _handle_error(self, error: Twilio
Twilio Verify Pattern (2FA/OTP)

電話番号の確認や 2FA には Twilio Verify を使用します。 コードの生成、配信、レート制限、不正防止を扱います。

Key benefits over DIY OTP:

  • Twilio がコードの生成と有効期限を管理します
  • 組み込みの不正防止機能(747M 件の試行をブロックし、$82M 以上の損失を防ぎました)
  • レート制限を自動的に処理します
  • マルチチャネル対応: SMS、音声、メール、プッシュ、WhatsApp

Google の調査では、SMS 2FA によって「自動化されたボットの 100%、大量のフィッシング攻撃の 96%、標的型攻撃の 76%」をブロックできたとされています。

When to use: ['User phone number verification at signup', 'Two-factor authentication (2FA)', 'Password reset verification', 'High-value transaction confirmation']

from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
import os
from enum import Enum
from typing import Optional

class VerifyChannel(Enum):
    SMS = "sms"
    CALL = "call"
    EMAIL = "email"
    WHATSAPP = "whatsapp"

class TwilioVerify:
    """
    Phone verification with Twilio Verify.
    Never store OTP codes - Twilio handles it.
    """

    def __init__(self, verify_service_sid: str = None):
        self.client = Client(
            os.environ["TWILIO_ACCOUNT_SID"],
            os.environ["TWILIO_AUTH_TOKEN"]
        )
        # Create a Verify Service in Twilio Console first
        self.service_sid = verify_service_sid or os.environ["TWILIO_VERIFY_SID"]

    def send_verification(
        self,
        to: str,
        channel: VerifyChannel = VerifyChannel.SMS,
        locale: str = "en"
    ) -> dict:
        """
        Send verification code to phone/email.

        Args:
            to: Phone number (E.164) or email
            channel: SMS, call, email, or whatsapp
            locale: Language code for message

        Returns:
            Verification status
        """
        try:
            verification = self.client.verify \
                .v2 \
                .services(self.service_sid) \
                .verifications \
                .create(
                    to=to,
                    channel=channel.value,
                    locale=locale
                )

            return {
                "success": True,
                "status": verification.status,  # "pending"
                "channel": channel.value,
                "valid": verification.valid
            }

        except TwilioRestException as e:
            return self._handle_verify_error(e)

    def check_verification(self, to: str, code: str) -> dict:
        """
        Check if verification code is correct.

        Args:
            to: Phone number or email that received code
            code: The code entered by user

        R
TwiML IVR Pattern

TwiML を使用して対話型音声応答(IVR)システムを構築します。 TwiML(Twilio Markup Language)は、着信時に Twilio が実行すべき処理を指示する XML です。

Core TwiML verbs:

  • : テキスト読み上げ
  • : 音声ファイルの再生
  • : キーパッドまたは音声入力の収集
  • : 別の番号への接続
  • : 発信者の音声の録音
  • : 別の TwiML エンドポイントへの移動

Key insight: Twilio がお使いの Webhook に HTTP リクエストを送信し、お使いのアプリが TwiML を返し、Twilio がそれを実行します。ステートレスなので、URL パラメータまたはセッションを利用してください。

When to use: ['Phone menu systems (press 1 for sales...)', 'Automated customer support', 'Appointment reminders with confirmation', 'Voicemail systems']

from flask import Flask, request, Response
from twilio.twiml.voice_response import VoiceResponse, Gather
from twilio.request_validator import RequestValidator
import os

app = Flask(__name__)

def validate_twilio_request(f):
    """Decorator to validate requests are from Twilio."""
    def wrapper(*args, **kwargs):
        validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])

        # Get request details
        url = request.url
        params = request.form.to_dict()
        signature = request.headers.get("X-Twilio-Signature", "")

        if not validator.validate(url, params, signature):
            return "Invalid request", 403

        return f(*args, **kwargs)
    wrapper.__name__ = f.__name__
    return wrapper

@app.route("/voice/incoming", methods=["POST"])
@validate_twilio_request
def incoming_call():
    """Handle incoming call with IVR menu."""
    response = VoiceResponse()

    # Gather digits with timeout
    gather = Gather(
        num_digits=1,
        action="/voice/menu-selection",
        method="POST",
        timeout=5
    )
    gather.say(
        "Welcome to Acme Corp. "
        "Press 1 for sales. "
        "Press 2 for support. "
        "Press 3 to leave a message."
    )
    response.append(gather)

    # If no input, repeat
    response.redirect("/voice/incoming")

    return Response(str(response), mimetype="text/xml")

@app.route("/voice/menu-selection", methods=["POST"])
@validate_twilio_request
def menu_selection():
    """Route based on menu selection."""
    response = VoiceResponse()
    digit = request.form.get("Digits", "")

    if digit == "1":
        # Transfer to sales
        response.say("Connecting you to sales.")
        response.dial(os.environ["SALES_PHONE"])

    elif digit == "2":
        # Transfer to support
        response.say("Connecting you to support.")
        response.dial(os.environ["SUPPORT_PHONE"])

    elif digit == "3":
        # Voicemail
        response.say("Please leave a message after 

⚠️ Sharp Edges

IssueSeveritySolution
Issuehigh## Track opt-out status in your database
Issuemedium## Implement retry logic for transient failures
Issuehigh## Register for A2P 10DLC (US requirement)
Issuecritical## ALWAYS validate the signature
Issuehigh## Track session windows per user
Issuecritical## Never hardcode credentials
Issuemedium## Implement application-level rate limiting too

コメント