> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# Twilio通話を登録する

> **上級者向け**
>
> このガイドでは、Twilioインフラを完全に制御する必要があるデベロッパー向けの高度なインテグレーションパターンを説明します。より簡単に設定するには、設定を自動的に処理する[ネイティブTwilioインテグレーション](/docs/ja/eleven-agents/phone-numbers/twilio-integration/native-integration)の使用をご検討ください。

## アプローチごとの使い分け

始める前に、ネイティブインテグレーションと通話登録アプローチの違いを確認しましょう。

| 機能             | ネイティブインテグレーション | 通話登録     |
| -------------- | -------------- | -------- |
| 設定の簡単さ         | より簡単           | より複雑     |
| 通話転送           | 対応済み           | 非対応      |
| カスタムTwilioロジック | 制限あり           | 完全に制御可能  |
| 電話番号管理         | ElevenLabs経由   | Twilio経由 |

## 概要

通話登録エンドポイントを使用すると、会話にはElevenLabsエージェントを活用しながら、独自のTwilioインフラを使用できます。Twilio番号をElevenLabsにインポートする代わりに、Twilio設定を完全に制御したまま、ElevenLabs APIで通話を登録し、エージェントへの接続に使用する[TwiML](https://www.twilio.com/docs/voice/twiml)を受け取れます。

このアプローチは、次の場合に適しています。

* 既存のTwilioインフラとワークフローを維持する必要がある
* 通話のルーティングと処理をプログラムで制御したい
* エージェントに接続する前にカスタムTwilioロジックが必要な複雑な通話フローがある
* ElevenLabsエージェントを既存の電話システムに統合する必要がある

## 仕組み

1. サーバーがTwilio経由で着信通話を受信するか、発信通話を開始します
2. サーバーがエージェントと通話の詳細を指定してElevenLabsの通話登録エンドポイントを呼び出します
3. ElevenLabsは、WebSocket経由で通話をエージェントに接続するTwiMLを返します
4. このTwiMLをTwilioに返して接続を確立します

> **Note**
>
> 通話登録エンドポイントを使用する場合、ElevenLabsはTwilioアカウントの認証情報に直接アクセスできないため、通話転送機能は利用できません。

## 前提条件

* [ElevenLabsアカウント](https://elevenlabs.io)
* 設定済みのElevenLabs会話型AIエージェント（[こちらから作成](/docs/ja/eleven-agents/quickstart)）
* 有効な電話番号を持つ[Twilioアカウント](https://www.twilio.com/try-twilio)
* μ-law 8000 Hzオーディオ形式で設定されたエージェント（[エージェント設定](#agent-configuration)を参照）

## エージェント設定

通話登録エンドポイントを使用する前に、Twilioがサポートする正しいオーディオ形式を使用するようエージェントを設定します。

#### TTS出力を設定

1. エージェント設定に移動します
2. Voiceセクションを開きます
3. ドロップダウンから「μ-law 8000 Hz」を選択します

![](/docs/_fern-img/b37196c36051755fb0b10a99b393501ec11573f963c83b6b092e1b5926c6617f.webp)

#### 入力形式を設定

1. エージェント設定に移動します
2. Advancedセクションを開きます
3. 入力形式として「μ-law 8000 Hz」を選択します

![](/docs/_fern-img/ec87531c38e26f2293b90126f1b91ee9acb4cc677c6f3e83a6e1b6029743d3f7.webp)

## APIリファレンス

通話登録エンドポイントでは、次のパラメータを受け付けます。

| パラメータ                                 | 型      | 必須  | 説明                                 |
| ------------------------------------- | ------ | --- | ---------------------------------- |
| `agent_id`                            | string | はい  | 通話を処理するエージェントのID                   |
| `from_number`                         | string | はい  | 発信者の電話番号                           |
| `to_number`                           | string | はい  | 宛先の電話番号                            |
| `direction`                           | string | いいえ | 通話方向：`inbound`（デフォルト）または`outbound` |
| `conversation_initiation_client_data` | object | いいえ | 動的変数と設定のオーバーライド                    |

エンドポイントは、Twilioに直接渡すTwiMLを返します。

## 実装

```python
import os
from fastapi import FastAPI, Request
from fastapi.responses import Response
from elevenlabs import ElevenLabs

app = FastAPI()

elevenlabs = ElevenLabs()
AGENT_ID = os.getenv("ELEVENLABS_AGENT_ID")

@app.post("/twilio/inbound")
async def handle_inbound_call(request: Request):
    form_data = await request.form()
    from_number = form_data.get("From")
    to_number = form_data.get("To")

    # Register the call with ElevenLabs
    twiml = elevenlabs.conversational_ai.twilio.register_call(
        agent_id=AGENT_ID,
        from_number=from_number,
        to_number=to_number,
        direction="inbound",
        conversation_initiation_client_data={
            "dynamic_variables": {
                "caller_number": from_number,
            }
        }
    )

    # Return the TwiML directly to Twilio
    return Response(content=twiml, media_type="application/xml")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

```typescript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import express from "express";

const app = express();
app.use(express.urlencoded({ extended: true }));

const elevenlabs = new ElevenLabsClient();
const AGENT_ID = process.env.ELEVENLABS_AGENT_ID;

// Handle incoming Twilio calls
app.post("/twilio/inbound", async (req, res) => {
  const { From: fromNumber, To: toNumber } = req.body;

  // Register the call with ElevenLabs
  const twiml = await elevenlabs.conversationalAi.twilio.registerCall({
    agentId: AGENT_ID,
    fromNumber,
    toNumber,
    direction: "inbound",
    conversationInitiationClientData: {
      dynamicVariables: {
        caller_number: fromNumber,
      },
    },
  });

  // Return the TwiML directly to Twilio
  res.type("application/xml").send(twiml);
});

app.listen(8000, () => {
  console.log("Server running on port 8000");
});
```

## 発信通話

発信通話の場合は、Twilio経由で通話を開始し、Webhook URLをサーバーに指定します。サーバーでElevenLabsへの登録を行います。

```python
from twilio.rest import Client
import os
from fastapi import Request
from fastapi.responses import Response
from elevenlabs import ElevenLabs

# Initialize clients
twilio_client = Client(
    os.getenv("TWILIO_ACCOUNT_SID"),
    os.getenv("TWILIO_AUTH_TOKEN")
)
elevenlabs = ElevenLabs()
AGENT_ID = os.getenv("ELEVENLABS_AGENT_ID")

def initiate_outbound_call(to_number: str):
    call = twilio_client.calls.create(
        from_=os.getenv("TWILIO_PHONE_NUMBER"),
        to=to_number,
        url="https://your-server.com/twilio/outbound"
    )
    return call.sid

@app.post("/twilio/outbound")
async def handle_outbound_webhook(request: Request):
    form_data = await request.form()
    from_number = form_data.get("From")
    to_number = form_data.get("To")

    twiml = elevenlabs.conversational_ai.twilio.register_call(
        agent_id=AGENT_ID,
        from_number=from_number,
        to_number=to_number,
        direction="outbound",
    )

    return Response(content=twiml, media_type="application/xml")
```

```typescript
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import Twilio from "twilio";

// Initialize clients
const twilioClient = new Twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const elevenlabs = new ElevenLabsClient();
const AGENT_ID = process.env.ELEVENLABS_AGENT_ID;

// Initiate an outbound call
async function initiateOutboundCall(toNumber: string) {
  const call = await twilioClient.calls.create({
    from: process.env.TWILIO_PHONE_NUMBER,
    to: toNumber,
    url: "https://your-server.com/twilio/outbound",
  });
  return call.sid;
}

// Handle the Twilio webhook for outbound calls
app.post("/twilio/outbound", async (req, res) => {
  const { From: fromNumber, To: toNumber } = req.body;

  const twiml = await elevenlabs.conversationalAi.twilio.registerCall({
    agentId: AGENT_ID,
    fromNumber,
    toNumber,
    direction: "outbound",
  });

  res.type("application/xml").send(twiml);
});
```

## 会話をパーソナライズする

`conversation_initiation_client_data`パラメータを使用して、動的変数を渡し、エージェント設定をオーバーライドします。

```json
{
  "agent_id": "your-agent-id",
  "from_number": "+1234567890",
  "to_number": "+0987654321",
  "direction": "inbound",
  "conversation_initiation_client_data": {
    "dynamic_variables": {
      "customer_name": "John Doe",
      "account_type": "premium",
      "order_id": "ORD-12345"
    }
  }
}
```

> **Info**
>
> 動的変数とオーバーライドの詳細については、[動的変数](/docs/ja/eleven-agents/customization/personalization/dynamic-variables)および[オーバーライド](/docs/ja/eleven-agents/customization/personalization/overrides)のドキュメントを参照してください。

## Twilioの設定

Twilioの電話番号がサーバーを指すように設定します。

#### パブリックURLを作成

ローカル開発では、[ngrok](https://ngrok.com)を使用してサーバーを公開します。

```bash
ngrok http 8000
```

#### Twilio番号を設定

1. [Twilio Console](https://console.twilio.com)にアクセスします
2. Phone Numbers > Manage > Active numbersに移動します
3. 電話番号を選択します
4. 「Voice Configuration」で、Webhook URLをサーバーエンドポイントに設定します（例：`https://your-ngrok-url.ngrok.app/twilio/inbound`）
5. HTTPメソッドをPOSTに設定します

![](/docs/_fern-img/510d09d492b0c6ac9966f8fe39a9da685df79e8108f6fbc55fe502f48f650084.webp)

## 制限事項

ネイティブインテグレーションではなく通話登録エンドポイントを使用する場合：

* **通話転送なし**：ElevenLabsはTwilio認証情報にアクセスできないため、転送機能は利用できません
* **手動設定**：オーディオ形式を設定し、TwiMLのルーティングを自身で処理する必要があります
* **ダッシュボードへのインポートなし**：この方法で登録した電話番号は、ElevenLabsの電話番号ダッシュボードに表示されません