將 Bot 連線至 TwilioConnect a bot to Twilio

適用于: SDK v4APPLIES TO: SDK v4

您可以設定您的 Bot 使用 Twilio 雲端通訊平台與其他人通訊。You can configure your bot to communicate with people using the Twilio cloud communication platform.

登入或建立 Twilio 帳戶來傳送和接收 SMS 訊息Log in to or create a Twilio account for sending and receiving SMS messages

如果您沒有 Twilio 帳戶,請建立新的帳戶If you don't have a Twilio account, create a new account.

建立 TwiML 應用程式Create a TwiML Application

依照指示建立 TwiML 應用程式Create a TwiML application following the instructions.

建立應用程式

在 [屬性] 之下,輸入 易記名稱Under Properties, enter a FRIENDLY NAME. 在本教學課程中,我們以「我的 TwiML 應用程式」為例。In this tutorial we use "My TwiML app" as an example. 語音之下的 [要求 URL] 可以保留空白。The REQUEST URL under Voice can be left empty. 在 [傳訊] 底下,[要求 URL] 應該是 https://sms.botframework.com/api/smsUnder Messaging, the Request URL should be https://sms.botframework.com/api/sms.

選取或新增電話號碼Select or add a phone number

請依照這裡的指示,透過主控台網站新增已驗證的呼叫端識別碼。Follow the instructions here to add a verified caller ID via the console site. 完成之後,您會在 [管理號碼] 之下的 [作用中號碼] 中看見您已驗證的號碼。After you finish, you will see your verified number in Active Numbers under Manage Numbers.

設定電話號碼

指定要用於語音和傳訊的應用程式Specify application to use for Voice and Messaging

按一下號碼並移至 [設定] 。Click the number and go to Configure. 在 [語音] 和 [傳訊] 之下,將 [設定方式] 設定為 TwiML 應用程式,以及將 [TWIML 應用程式] 設定為 [我的 TwiML 應用程式]。Under both Voice and Messaging, set CONFIGURE WITH to be TwiML App and set TWIML APP to be My TwiML app. 完成之後,按一下 [儲存] 。After you finish, click Save.

指定應用程式

請返回 [管理號碼] ,您會看見 [語音] 和 [傳訊] 的組態都變更為 TwiML 應用程式。Go back to Manage Numbers, you will see the configuration of both Voice and Messaging are changed to TwiML App.

指定的號碼

收集認證Gather credentials

請返回主控台首頁,您會在專案儀表板上看見您的帳戶 SID 和驗證權杖,如下所示。Go back to the console homepage, you will see your Account SID and Auth Token on the project dashboard, as shown below.

收集應用程式認證

提交認證Submit credentials

在另一個視窗中,返回 Bot Framework 網站 https://dev.botframework.com/In a separate window, return to the Bot Framework site at https://dev.botframework.com/.

  • 選取 [我的 Bot] ,然後選擇要連線至 Twilio 的 Bot。Select My bots and choose the Bot that you want to connect to Twilio. 這會將您導向 Azure 入口網站。This will direct you to the Azure portal.
  • 選取 [Bot 管理] 之下的 [通道] 。Select Channels under Bot Management. 按一下 Twilio (SMS) 圖示。Click the Twilio (SMS) icon.
  • 輸入電話號碼、帳戶 SID,以及您先前記錄的驗證權杖。Enter the Phone Number, Account SID, and Auth Token you record earlier. 完成之後,按一下 [儲存] 。After you finish, click Save.

提交認證

當您完成這些步驟時,您的 Bot 即已成功設定為使用 Twilio 與使用者進行通訊。When you have completed these steps, your bot will be successfully configured to communicate with users using Twilio.

使用 Twilio 配接器將 Bot 連線到 TwilioConnect a bot to Twilio using the Twilio adapter

此外,您也可以使用 Twilio 配接器,透過 Azure Bot Service 中可用的通道連接 Bot 與 Twilio。As well as the channel available in the Azure Bot Service to connect your bot with Twilio, you can also use the Twilio adapter. 在本文中,您將了解如何使用配接器,將 Bot 連線至 Twilio。In this article you will learn how to connect a bot to Twilio using the adapter. 本文將逐步引導您修改 EchoBot 範例,將其連線到 Twilio。This article will walk you through modifying the EchoBot sample to connect it to Twilio.

注意

下列指示涵蓋 Twilio 配接器的 C# 實作。The instructions below cover the C# implementation of the Twilio adapter. 如需使用 JS 配接器 (BotKit 程式庫的一部分) 的指示,請參閱 BotKit Twilio 文件For instructions on using the JS adapter, part of the BotKit libraries, see the BotKit Twilio documentation.

PrerequisitesPrerequisites

取得 Twilio 號碼並收集帳戶認證Get a Twilio number and gather account credentials

  1. 登入 TwilioLog into Twilio. 在頁面右側,您會看到帳戶的 [帳戶 SID] 和 [驗證權杖] ,請記下這些資訊,因為稍後在設定 Bot 應用程式時會用到這些資訊。On the right hand side of the page you will see the ACCOUNT SID and AUTH TOKEN for your account, make a note of these as you will need them later when configuring your bot application.

  2. 從 [開始使用 Twilio] 底下的選項中,選擇 [可程式化的語音] 。Choose Programmable Voice from the options under Get Started with Twilio.

開始使用可程式化的語音

  1. 在下一個頁面上,按一下 [取得您的第一個 Twilio 號碼] 按鈕。On the next page, click the Get your first Twilio number button. 快顯視窗會顯示新的號碼,您可以按一下 [選擇此號碼] 予以接受 (也可以遵循畫面上的指示來搜尋不同的號碼)。A pop-up window will show you a new number, which you can accept by clicking Choose this number (alternatively you can search for a different number by following the on screen instructions).

  2. 選擇您的號碼之後,請將其記下,因為在稍後步驟中設定 Bot 應用程式時需要用到。Once you have chosen your number, make a note of it, as you will need this when configuring your bot application in a later step.

連接 Bot 中的 Twilio 配接器Wiring up the Twilio adapter in your bot

現在您有自己的 Twilio 號碼和帳戶認證,您必須設定 Bot 應用程式。Now that you have your Twilio number and account credentials, you need to configure your bot application.

安裝 Twilio 配接器 NuGet 套件Install the Twilio adapter NuGet package

新增 Microsoft.Bot.Builder.Adapters.TwilioNuGet 套件。Add the Microsoft.Bot.Builder.Adapters.Twilio NuGet package. 如需如何使用 NuGet 的詳細資訊,請參閱在 Visual Studio 中安裝和管理套件For more information on using NuGet, see Install and manage packages in Visual Studio.

建立 Twilio 配接器類別Create a Twilio adapter class

建立繼承自 *TwilioAdapter _ 類別的新類別。Create a new class that inherits from the *TwilioAdapter _ class. 此類別將作為 Twilio 通道的介面卡,並包含錯誤處理功能 (類似于範例中已有的 *>botframeworkadapterwitherrorhandler_*_ 類別,用於處理來自 Azure Bot Service) 的其他要求。This class will act as our adapter for the Twilio channel and include error handling capabilities (similar to the BotFrameworkAdapterWithErrorHandler class already in the sample, used for handling other requests from Azure Bot Service).

public class TwilioAdapterWithErrorHandler : TwilioAdapter
{
    public TwilioAdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger)
            : base(configuration, logger)
        {
            OnTurnError = async (turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                await turnContext.SendActivityAsync("The bot encountered an error or bug.");
                await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
        }
}

建立用於處理 Twilio 要求的新控制器Create a new controller for handling Twilio requests

建立新的控制器,其會在新的端點 'api/twilio' (而不是預設 'api/messages',其用於處理來自 Azure Bot Service 通道的要求) 上處理來自 Twilio 應用程式的要求。Create a new controller which will handle requests from Twilio, on a new endpoing 'api/twilio' instead of the default 'api/messages' used for requests from Azure Bot Service Channels. 將額外的端點新增至您的 Bot,即可使用相同的 Bot,接受來自 Bot Service 通道以及來自 Twilio 的要求。By adding an additional endpoint to your bot, you can accept requests from Bot Service channels, as well as from Twilio, using the same bot.

[Route("api/twilio")]
[ApiController]
public class TwilioController : ControllerBase
{
    private readonly TwilioAdapter _adapter;
    private readonly IBot _bot;

    public TwilioController(TwilioAdapter adapter, IBot bot)
    {
        _adapter = adapter;
        _bot = bot;
    }

    [HttpPost]
    [HttpGet]
    public async Task PostAsync()
    {
        // Delegate the processing of the HTTP POST to the adapter.
        // The adapter will invoke the bot.
        await _adapter.ProcessAsync(Request, Response, _bot, default);
    }
}

在 Bot startup.cs 中插入 Twilio 配接器Inject the Twilio adapter in your bot startup.cs

將以下這一行新增至 startup.cs 檔案中的 ConfigureServices 方法。Add the following line to the ConfigureServices method within your startup.cs file. 這會註冊您的 Twilio 配接器並使其可供新的控制器類別使用。This will register your Twilio adapter and make it available for your new controller class. 此配接器會自動使用前一個步驟中新增的組態設定。The configuration settings you added in the previous step will be automatically used by the adapter.

services.AddSingleton<TwilioAdapter, TwilioAdapterWithErrorHandler>();

新增之後,您的 ConfigureServices 方法看起來應該像這樣。Once added, your ConfigureServices method shold look like this.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Create the default Bot Framework Adapter (used for Azure Bot Service channels and Emulator).
    services.AddSingleton<IBotFrameworkHttpAdapter, BotFrameworkAdapterWithErrorHandler>();

    // Create the Twilio Adapter
    services.AddSingleton<TwilioAdapter, TwilioAdapterWithErrorHandler>();

    // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
    services.AddTransient<IBot, EchoBot>();
}

取得 Bot 的 URLObtain a URL for your bot

既然您已在 Bot 專案中連接配接器,您必須識別要提供給 Twilio 的正確端點,以確保 Bot 會收到訊息。Now that you have wired up the adapter in your bot project, you need to identify the correct endpoint to provide to Twilio in order to ensure your bot receives messages. 您也需要此 URL 才能完成 Bot 應用程式的設定。You also require this URL to complete configuration of your bot application.

若要完成此步驟,請將您的 Bot 部署至 Azure,並記下已部署 Bot 的 URL。To complete this step, deploy your bot to Azure and make a note of the URL of your deployed bot.

注意

如果您尚未準備好將 bot 部署至 Azure,或想要在使用 Twilio 介面卡時對 bot 進行偵錯工具,您可以使用 ngrok (您可能已安裝的工具,如果您已 Bot Framework Emulator 使用先前) 的通道,將其傳遞至您在本機執行的 bot,並為此提供可公開存取的 URL。If you are not ready to deploy your bot to Azure, or wish to debug your bot when using the Twilio adapter, you can use a tool such as ngrok (which you will likely already have installed if you have used the Bot Framework Emulator previously) to tunnel through to your bot running locally and provide you with a publicly accessible URL for this.

如果您想要建立 ngrok 通道並取得 Bot 的 URL,請在終端機視窗中使用下列命令 (這假設本機 Bot 在連接埠 3978 上執行,如果 Bot 不是如此,請在命令中改變連接埠號碼)。If you wish create an ngrok tunnel and obtain a URL to your bot, use the following command in a terminal window (this assumes your local bot is running on port 3978, alter the port numbers in the command if your bot is not).

ngrok.exe http 3978 -host-header="localhost:3978"

將 Twilio 應用程式設定新增至 Bot 的組態檔Add Twilio app settings to your bot's configuration file

將下方顯示的設定新增至 Bot 專案中的 appSettings.json 檔案。Add the settings shown below to your appSettings.json file in your bot project. 您可以使用您在建立 Twilio 號碼時所收集的值,填入 _ * TwilioNumber * *、 >twilioaccountsid>twilioauthtokenYou populate _*TwilioNumber**, TwilioAccountSid and TwilioAuthToken using the values you gathered when creating your Twilio number. TwilioValidationUrl 應為 Bot 的 URL,再加上您在新建立的控制器中指定的 api/twilio 端點。TwilioValidationUrl should be your bot's URL, plus the api/twilio endpoint you specified in your newly created controller. 例如: https://yourboturl.com/api/twilioFor example, https://yourboturl.com/api/twilio.

  "TwilioNumber": "",
  "TwilioAccountSid": "",
  "TwilioAuthToken": "",
  "TwilioValidationUrl", ""

填入上述設定後,您應該重新部署 (如果使用 ngrok 在本機執行,則重新佈署) Bot。Once you have populated the settings above, you should redeploy (or restart if running locally with ngrok) your bot.

完成 Twilio 號碼的設定Complete configuration of your Twilio number

最後一個步驟是設定新 Twilio 號碼的傳訊端點,以確保Bot 會收到訊息。The final step is to configure your new Twilio number's messaging endpoint, to ensure your bot receives messages.

  1. 瀏覽至 Twilio 作用中號碼頁面Navigate to the Twilio Active Numbers page.

  2. 按一下您在先前步驟中建立的電話號碼。Click the phone number you created in the earlier step.

  3. 在 [訊息] 區段內,從下拉式方塊中選擇 [Webhook] ,並在文字方塊中填入您在上一個步驟中用來填入 TwilioValidationUrl 設定 (例如 https://yourboturl.com/api/twilio的 Bot 端點,以完成 [訊息傳入] 區段。Within the Messaging section, complete the A MESSAGE COMES IN section by chooisng Webhook from the drop down and populating the text box with your bot's endpoint that you used to populate the TwilioValidationUrl setting in the previous step, such as https://yourboturl.com/api/twilio.

設定 Twilio 號碼 Webhook

  1. 按一下 [儲存] 按鈕。Click the Save button.

使用 Twilio 中的配接器測試 BotTest your bot with adapter in Twilio

您現在可將簡訊訊息傳送至 Twilio 號碼,以測試 Bot 是否已正確連線至 Twilio。You can now test whether your bot is connected to Twilio correctly by sending an SMS message to your Twilio number. 當 Bot 收到該訊息後,其會將訊息傳回給您,並從您的訊息回應文字。Once the message is received by your bot it will send a message back to you, echoing the text from your message.

您也可以使用 Twilio 配接器的範例 Bot 來測試這項功能,做法是在 appSettings.json 中填入上面步驟中所述的相同值。You can also test this feature using the sample bot for the Twilio adapter by populating the appSettings.json with the same values described in the steps above.