瞭解回應 Bot 的結構

適用于: SDK v4

Bot Framework 範本和範例是針對 ASP.NET (C#)、restify (JavaScript) 和 aioHTTP (Python) 撰寫。 不過,Web 服務功能不是 Bot Framework SDK 的一部分,而是您選擇使用的 Web 架構的一部分。

所有 Bot 應用程式都會共用一些常見的功能。

功能 描述
資源佈建 Bot 作為 Web 應用程式需要建立 Web 服務、Bot 配接器和 Bot 物件。
訊息中心端點 Web 應用程式需要實作傳訊端點,以接收活動,並將活動轉送至 Bot 配接器。
Bot 配接器 配接器會從傳訊端點接收活動、將它們轉送至 Bot 的回合處理常式,並攔截 Bot 邏輯無法攔截的任何錯誤或例外狀況。
Bot 物件 Bot 物件會處理 Bot 的推理或回合邏輯。

您可以從範本建立回應 Bot,如建立 Bot 中所述 ,也可以從 Microsoft/BotBuilder-Samples 存放庫複製 Echo Bot 專案。

C# 和 JavaScript 範本內建支援串流連線。 不過,本文未涵蓋串流功能。 如需串流連線的相關資訊,請參閱如何將 Bot 連線到 Direct Line Speech

注意

Bot Framework JavaScript、C# 和 Python SDK 將會繼續受到支援,不過,JAVA SDK 即將淘汰,最終長期支援將于 2023 年 11 月結束。 只會執行此存放庫中的重要安全性和錯誤修正。

使用 JAVA SDK 建置的現有 Bot 將繼續運作。

針對新的 Bot 建置,請考慮使用 Power Virtual Agents ,並閱讀 選擇正確的聊天機器人解決方案

如需詳細資訊,請參閱 Bot 建置 的未來。

必要條件

Bot 範本

Bot 是 Web 應用程式,而且會為每個語言提供範本。

Bot Framework 同時包含 VSIX 和 .NET 範本。

範本會產生 ASP.NET MVC Core Web 應用程式。 如果您查看 ASP.NET 基本概念,您會在 Program.cs Startup.cs 檔案中看到類似的程式碼。 所有 Web 應用程式都需要這些檔案,而且不是 Bot 特定的檔案。

注意

您可以從 Visual Studio 內安裝範本。

  1. 在功能表中,選取 [擴充功能 ],然後 選取 [管理擴充功能 ]。
  2. 在 [ 管理延伸模組 ] 對話方塊中,搜尋並安裝 適用于 Visual Studio 的 Bot Framework v4 SDK 範本。

如需將 .NET Bot 部署至 Azure 的相關資訊,請參閱如何 布建和發佈 Bot

appsettings.json 檔案會指定 Bot 的組態資訊,例如其應用程式識別碼和密碼等。 如果使用特定技術或在生產環境中使用此 Bot,您必須將特定金鑰或 URL 新增至此組態。 不過,對於這個回應 Bot,您現在不需要在這裡執行任何動作;應用程式識別碼和密碼目前可能保持未定義。

EchoBot.csproj 檔案會指定 Bot 的相依性及其相關聯的版本。 這一切都是由範本和您的系統所設定。 您可以使用 NuGet 套件管理員或 dotnet add package 命令來安裝其他相依性。

資源佈建

若要作為 Web 應用程式運作,您的 Bot 必須建立 Web 服務、Bot 配接器和 Bot 物件。

對於大部分的 Bot,您也會為 Bot 建立儲存層和記憶體管理物件。 不過,回應 Bot 不需要在回合之間保存狀態。 對於某些 Bot,您可能需要建立 Bot 物件或配接器需要的其他物件。

在 ASP.NET 中,您會在 Startup.cs 檔案中 註冊物件和物件建立方法。 方法 ConfigureServices 會從 appsettings.json 載入已連線的服務及其金鑰(如果有的話),並連接狀態等等。 在這裡,系統會定義配接器和 Bot,以透過相依性插入來取得。 然後, Configure 方法會完成應用程式的設定。

ConfigureServicesConfigure 會在應用程式啟動時由執行時間呼叫。

訊息中心端點

此範本會使用傳訊端點實作 Web 服務。 收到要求時,服務會擷取驗證標頭並要求承載,並將其轉送至配接器。

C# 和 JavaScript SDK 支援串流連線。 雖然回應 Bot 不會使用任何串流功能,但 C# 和 JavaScript 範本中的配接器是設計來支援它們。

每個傳入要求都代表新回合的開始。

Controllers\BotController.cs

// This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
// implementation at runtime. Multiple different IBot implementations running at different endpoints can be
// achieved by specifying a more specific type for the bot constructor argument.
[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 PostAsync()
    {
        // Delegate the processing of the HTTP POST to the adapter.
        // The adapter will invoke the bot.
        await _adapter.ProcessAsync(Request, Response, _bot);
    }
}

Bot 配接器

配接器會從傳訊端點接收活動、將它們轉送至 Bot 的回合處理常式,並攔截 Bot 邏輯無法攔截的任何錯誤或例外狀況。 配接器也會將活動從 Bot 轉送至使用者的通道。

配接器可讓您在開啟錯誤 處理常式時自行新增

Startup.cs

要使用的配接器定義于 方法中 ConfigureServices

// Create the Bot Framework Authentication to be used with the Bot Adapter.
services.AddSingleton<BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>();

AdapterWithErrorHandler.cs

public class AdapterWithErrorHandler : CloudAdapter
{
    public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger<IBotFrameworkHttpAdapter> logger)
        : base(auth, logger)
    {
        OnTurnError = async (turnContext, exception) =>
        {
            // Log any leaked exception from the application.
            // NOTE: In production environment, you should consider logging this to
            // Azure Application Insights. Visit https://aka.ms/bottelemetry to see how
            // to add telemetry capture to your bot.
            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");
        };
    }
}

Bot 邏輯

回應 Bot 會使用 活動處理常式 ,並針對它辨識並回應的活動類型實作處理常式,在此案例中為 交談更新 訊息 活動。

  • 交談更新活動包含已加入或離開交談的人員資訊。 針對非群組交談,Bot 和使用者在啟動時都會加入交談。 對於群組交談,每當有人加入或離開交談時,就會產生交談更新,無論是 Bot 或使用者。
  • 訊息活動代表使用者傳送至 Bot 的訊息。

回應 Bot 會在使用者加入交談時歡迎使用者,並回應他們傳送給 Bot 的任何訊息。

Startup.cs

要使用的 Bot 定義于 方法中 ConfigureServices

// Create the Bot Adapter with error handling enabled.
services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

Bots\EchoBot.cs

public class EchoBot : ActivityHandler
{
    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var replyText = $"Echo: {turnContext.Activity.Text}";
        await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
    }

    protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
    {
        var welcomeText = "Hello and welcome!";
        foreach (var member in membersAdded)
        {
            if (member.Id != turnContext.Activity.Recipient.Id)
            {
                await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText, welcomeText), cancellationToken);
            }
        }
    }
}

下一步