在 Bot 中使用 Direct Line SpeechUse Direct Line Speech in your bot

適用于: SDK v4APPLIES TO: SDK v4

Direct Line Speech 使用 Bot Framework 的新 WebSocket 型串流功能,在 Direct Line Speech 通道與您的 Bot 之間交換訊息。Direct Line Speech uses a new WebSocket based streaming capability of Bot Framework to exchange messages between the Direct Line Speech channel and your bot. 在 Azure 入口網站中啟用 Direct Line Speech 通道後,您必須更新 Bot 以接聽並接受這些 WebSocket 連線。After enabling the Direct Line Speech channel in the Azure Portal, you will need to update your bot to listen for and accept these WebSocket connections. 這些指示說明如何執行這項操作。These instructions explain how to do this.

步驟 1:升級到最新版本的 SDKStep 1: Upgrade to the latest version of the SDK

針對 Direct Line 語音,請確定您使用的是最新版的 Bot Builder SDK。For Direct Line Speech ensure you are using the latest version of Bot Builder SDK.

步驟 2:更新 .NET Core Bot 程式碼 (如果 Bot 使用 AddBot 和 UseBotFramework 而非 BotController)Step 2: Update your .NET Core bot code if your bot uses AddBot and UseBotFramework instead of a BotController

如果您已使用 4.3.2 版之前的 Bot Builder SDK v4 建立 Bot,Bot 可能不包含 BotController,但在 Startup.cs 檔案中改為使用 AddBot() 和 UseBotFramework() 方法來公開 Bot 接收訊息的 POST 端點。If you have created a bot using v4 of the Bot Builder SDK prior to version 4.3.2, your bot likely does not include a BotController but instead uses the AddBot() and UseBotFramework() methods in the Startup.cs file to expose the POST endpoint where the bot receives messages. 若要公開新的串流端點,您必須新增 BotController 及移除 AddBot() 和 UseBotFramework() 方法。To expose the new streaming endpoint, you will need to add a BotController and remove the AddBot() and UseBotFramework() methods. 這些指示會逐步引導需要進行的變更。These instructions walk through the changes that need to be made. 如果您已經有這些變更,請繼續進行下一個步驟。If you already have these changes, continue to the next step.

藉由新增名為 BotController.cs 的檔案,將新的 MVC 控制器新增至 Bot 專案。Add a new MVC controller to your bot project by adding a file called BotController.cs. 將此檔案中新增控制器程式碼:Add the controller code to this file:


[Route("api/messages")]

[ApiController]

public class BotController : ControllerBase
{
    private readonly IBotFrameworkHttpAdapter _adapter;
    private readonly IBot _bot;
    public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
    {
        _adapter = adapter;

        _bot = bot;
    }

    [HttpPost, HttpGet]
    public async Task ProcessMessageAsync()
    {
        await _adapter.ProcessAsync(Request, Response, _bot);
    }
}

Startup.cs 檔案中,找出 Configure 方法。In the Startup.cs file, locate the Configure method. 移除 UseBotFramework() 行並確定您有 UseWebSockets 的這幾行:Remove the UseBotFramework() line and make sure you have these lines to UseWebSockets:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseWebSockets();
    app.UseMvc();
    ...
}

同時在 Startup.cs 檔案中,找出 ConfigureServices 方法。Also in the Startup.cs file, locate the ConfigureServices method. 移除 AddBot() 行,並確定您有用來新增 IBotBotFrameworkHttpAdapter 的這幾行:Remove the AddBot() line and make sure you have lines for adding your IBot and a BotFrameworkHttpAdapter:


public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSingleton<ICredentialProvider, ConfigurationCredentialProvider>();
    services.AddSingleton<IChannelProvider, ConfigurationChannelProvider>();

    // Create the Bot Framework Adapter.
    services.AddSingleton<IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>();

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

您 Bot 程式碼的其餘部分維持不變!The remainder of your bot code stays the same!

步驟 3:確定已啟用 WebsocketStep3: Ensure WebSockets are enabled

當您在 Azure 入口網站中使用其中一個範本 (例如 EchoBot) 建立新的 Bot 時,您會收到一個 Bot,其中包含可公開 GET 和 POST 端點的 ASP.NET MVC 控制器,而且將會使用 WebSocket。When you create a new bot from the Azure Portal using one of the templates such as EchoBot, you will get a bot that includes an ASP.NET MVC controller that exposes a GET and POST endpoint and will also use WebSockets. 這些指示會說明當您要進行升級或未從範本建立 Bot 時,如何將這些元素新增至 Bot。These instructions explain how to add these elements to your bot if you are upgrading or did not make your bot from a template.

在您解決方案的 Controllers 資料夾之下開啟 BotController.csOpen BotController.cs under the Controllers folder in your solution

在類別中找到 PostAsync 方法,並將其裝飾從 [HttpPost] 更新為 [HttpPost, HttpGet]:Find the PostAsync method in the class and update its decoration from [HttpPost] to [HttpPost, HttpGet]:


[HttpPost, HttpGet]
public async Task PostAsync()
{
    await _adapter.ProcessAsync(Request, Response, _bot);
}

儲存並關閉 BotController.csSave and close BotController.cs

在您解決方案的根目錄中開啟 Startup.csOpen Startup.cs in the root of your solution.

在 Startup.cs 中,瀏覽至 Configure 方法的底部。In Startup.cs, navigate to the bottom of the Configure method. 在呼叫  app.UseMvc() 之前,請先將呼叫新增至  app.UseWebSockets()Before the call to app.UseMvc(), add a call to app.UseWebSockets(). 這很重要,因為這些使用呼叫的順序很重要。This is important as the order of these use calls matters. 方法結尾應該類似這樣:The end of the method should look something like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseWebSockets();
    app.UseMvc();
    ...
}

您 Bot 程式碼的其餘部分維持不變!The remainder of your bot code stays the same!

步驟 4:(選擇性) 設定活動的 [說話] 欄位,以自訂要對使用者說的話Step 4: Optionally set the Speak field on Activities to customize what is spoken to the user

根據預設,說話內容是透過 Direct Line Speech 傳送給使用者的所有訊息。By default, all messages sent through Direct Line Speech to the user will be spoken.

您可以藉由對 Bot 所傳送的任何活動設定 [說話] 欄位,選擇性地自訂說出的訊息方式:You can optionally customize how the message is spoken by setting the Speak field of any Activity sent from the bot:


public IActivity Speak(string message)
{
    var activity = MessageFactory.Text(message);
    string body = @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='en-US'>

        <voice name='Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'>" +
        $"{message}" + "</voice></speak>";

    activity.Speak = body;
    return activity;
}

下列程式碼片段示範如何使用先前的 Speak 函式:The following snippet shows how to use the previous Speak function:


protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
    await turnContext.SendActivityAsync(Speak($"Echo: {turnContext.Activity.Text}"), cancellationToken);
}

其他資訊Additional information