使用檢查中介軟體來對聊天機器人進行偵錯Debug a bot with inspection middleware

適用于: SDK v4APPLIES TO: SDK v4

本文說明如何使用檢查中介軟體來對 bot 進行 debug 錯。This article describes how to debug a bot using inspection middleware. 除了查看 Bot 目前的狀態以外,這項功能也可讓 Bot Framework Emulator 偵測 Bot 的輸入和輸出流量。This feature allows the Bot Framework Emulator to debug traffic into and out of the bot in addition to looking at the current state of the bot. 您可以使用追蹤訊息來將資料傳送至模擬器,然後在任何給定的交談回合中檢查 bot 的狀態。You can use a trace message to send data to the Emulator and then inspect the state of your bot in any given turn of the conversation.

我們會使用透過 Bot Framework v4 (C# | JavaScript | Python) 在本機建立的 EchoBot,來說明如何偵測和檢查 Bot 的訊息狀態。We use an EchoBot built locally using the Bot Framework v4 (C# | JavaScript | Python) to show how to debug and inspect the bot's message state. 您也可以使用 IDE 對 Bot 進行偵錯使用 Bot Framework Emulator 進行偵錯,但若要對狀態進行偵錯,則必須在 Bot 內新增檢查中介軟體。You can also Debug a bot using IDE or Debug with the Bot Framework Emulator, but to debug state you need to add inspection middleware to your bot. 這裡有提供檢查聊天機器人的範例:C#JavaScriptPythonThe Inspection bot samples are available here: C#, JavaScript and Python.

必要條件Prerequisites

將您的模擬器更新為最新版本Update your Emulator to the latest version

使用 bot 檢查中介軟體來偵測 bot 之前,您必須將模擬器更新為4.5 版或更新版本。Before using the bot inspection middleware to debug your bot, you need to update your Emulator to be version 4.5 or newer. 檢查最新版本以獲得更新。Check the latest version for updates.

若要檢查您的模擬器版本,請 選取 > 功能表中的 [說明]。To check the version of your Emulator, select Help > About in the menu. 您將會看到目前的模擬器版本。You will see the current version of your Emulator.

目前版本

更新聊天機器人的程式碼Update your bot's code

設定檢查狀態,並將檢查中介軟體新增至 Startup.cs 檔案中的配接器。Set up the inspection state and add the inspection middleware to the adapter in the Startup.cs file. 檢查狀態會透過插入相依性來提供。The inspection state is provided through dependency injection. 請參閱下面的程式碼更新,或參閱此處的檢查範例:C#See the code update below or refer to the inspection sample here: C#.

Startup.csStartup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient().AddControllers().AddNewtonsoftJson();

    services.AddSingleton<IStorage, MemoryStorage>();

    // The Inspection Middleware needs some scratch state to keep track of the (logical) listening connections.
    services.AddSingleton<InspectionState>();

    // You can inspect the UserState
    services.AddSingleton<UserState>();

    // You can inspect the ConversationState
    services.AddSingleton<ConversationState>();

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

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

AdapterWithInspection.csAdapterWithInspection.cs

public class AdapterWithInspection : CloudAdapter
{
    public AdapterWithInspection(IConfiguration configuration, IHttpClientFactory httpClientFactory, InspectionState inspectionState, UserState userState, ConversationState conversationState, ILogger<IBotFrameworkHttpAdapter> logger)
        : base(configuration, httpClientFactory, logger)
    {
        // Inspection needs credentiaols because it will be sending the Activities and User and Conversation State to the emulator
        var credentials = new MicrosoftAppCredentials(configuration["MicrosoftAppId"], configuration["MicrosoftAppPassword"]);

        Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));

        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");
        };
    }
}

更新 EchoBot.cs 檔案中的 Bot 類別。Update the bot class in the EchoBot.cs file.

EchoBot.csEchoBot.cs

private readonly ConversationState _conversationState;
private readonly UserState _userState;

public EchoBot(ConversationState conversationState, UserState userState)
{
    _conversationState = conversationState;
    _userState = userState;
}

public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
{
    await base.OnTurnAsync(turnContext, cancellationToken);

    await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);
    await _userState.SaveChangesAsync(turnContext, false, cancellationToken);
}

protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
    var conversationStateProp = _conversationState.CreateProperty<CustomState>("customState");
    var convProp = await conversationStateProp.GetAsync(turnContext, () => new CustomState { Value = 0 }, cancellationToken);

    var userStateProp = _userState.CreateProperty<CustomState>("customState");
    var userProp = await userStateProp.GetAsync(turnContext, () => new CustomState { Value = 0 }, cancellationToken);

    await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {turnContext.Activity.Text} conversation state: {convProp.Value} user state: {userProp.Value}"), cancellationToken);

    convProp.Value++;
    userProp.Value++;
}

在本機測試 BotTest your bot locally

更新程式碼之後,您可以在本機執行 bot,然後使用兩個模擬器來測試偵錯工具:一個用來傳送和接收訊息,另一個則是在偵測模式中檢查訊息的狀態。After updating the code you can run your bot locally and test the debugging feature using two Emulators: one to send and receive messages, and the other to inspect the state of messages in debugging mode. 若要在本機測試聊天機器人,請採取下列步驟:To test your bot locally take the following steps:

  1. 在終端機流覽至聊天機器人的目錄,然後執行下列命令以在本機執行聊天機器人:Navigate to your bot's directory in a terminal and execute the following command to run your bot locally:

    dotnet run
    
  2. 開啟您的模擬器。Open your Emulator. 按一下 [開啟聊天機器人]。Click Open Bot. 使用 http://localhost:3978/api/messages 和 MicrosoftAppIdMicrosoftAppPassword 值填入 [Bot URL]。Fill in Bot URL with http://localhost:3978/api/messages and the MicrosoftAppId and MicrosoftAppPassword values. 如果您有 JavaScript 聊天機器人,則可以在聊天機器人的 .env 檔案中找到這些值。If you have a JavaScript bot you can find these values in your bot's .env file. 如果您有 C# 聊天機器人,則可以在 appsettings.json 檔案中找到這些值。If you have a C# bot you can find these values in the appsettings.json file. 按一下 [ 連接]。Click Connect.

  3. 現在開啟另一個模擬器視窗。Now open another Emulator window. 第二個模擬器視窗將以偵錯工具的形式運作。This second Emulator window will work as a debugger. 遵循上一個步驟中所述的指示。Follow the instructions as described in the previous step. 核取 [以偵錯模式開啟],然後按一下 [連線]。Check Open in debug mode and then click Connect.

  4. 此時您會看到一個命令,其中包含唯一識別碼 (/INSPECT attach <identifier>) 在您的偵錯工具中。At this point you will see a command with a unique identifier (/INSPECT attach <identifier>) in your debugging Emulator. 從偵錯模擬器複製具有識別碼的整個命令,並將其貼到第一個模擬器的聊天方塊中。Copy the whole command with the identifier from the debugging Emulator and paste it into the chat box of the first Emulator.

    注意

    當您在 bot 的程式碼中新增檢查中介軟體之後,每次在偵測模式下啟動模擬器時,就會產生唯一的識別碼。A unique identifier is generated every time when the Emulator is launched in debug mode after you add the inspection middleware in your bot's code.

  5. 現在您可以在第一個模擬器的聊天方塊中傳送訊息,並在偵錯工具中檢查訊息。Now you can send messages in the chat box of your first Emulator and inspect the messages in the debugging Emulator. 若要檢查訊息的狀態,請按一下 [偵錯工具模擬器] 中的 [ Bot 狀態],然後在右邊的 JSON 視窗上展開 To inspect the state of the messages click Bot State in the debugging Emulator and unfold values on the right JSON window. 您將會在偵錯工具模擬器中看到 bot 的狀態:You will see the state of your bot in the debugging Emulator:

    Bot 狀態

檢查在 Azure 中設定的 Bot 所處的狀態Inspect the state of a bot configured in Azure

如果您想要檢查 Azure 中所設定且已連線至通道 (如 Teams) 的聊天機器人狀態,您必須安裝並執行 ngrokIf you want to inspect the state of your bot configured in Azure and connected to channels (like Teams) you will need to install and run ngrok.

執行 ngrokRun ngrok

至此,您已將模擬器更新為最新版本,並在 bot 的程式碼中新增檢查中介軟體。At this point you have updated your Emulator to the latest version and added the inspection middleware in your bot's code. 下一個步驟是執行 ngrok,並對 Azure Bot 通道註冊設定本機聊天機器人。The next step is to run ngrok and configure your local bot to your Azure Bot Channels Registration. 在執行 ngrok 之前,您必須在本機執行聊天機器人。Before running ngrok you need to run your bot locally.

若要在本機執行聊天機器人,請執行下列動作:To run your bot locally do the following:

  1. 在終端機流覽至聊天機器人的資料夾,並將 npm 註冊設定為使用最新組建Navigate to your bot's folder in a terminal and set your npm registration to use the latest builds

  2. 在本機執行您的 Bot。Run your bot locally. 您會看到 bot 公開端口號碼,例如 3978You will see your bot expose a port number like 3978.

  3. 開啟另一個命令提示字元,並瀏覽至聊天機器人的專案資料夾。Open another command prompt and navigate to your bot's project folder. 執行以下命令:Run the following command:

    ngrok http 3978
    
  4. ngrok 現已連線至在本機執行的聊天機器人。ngrok is now connected to your locally running bot. 複製公用 IP 位址。Copy the public IP address.

    ngrok-success

更新聊天機器人的通道註冊Update channel registrations for your bot

現在,本機聊天機器人已連線至 ngrok,因此接下來您可以在 Azure 中對 Bot 通道註冊設定本機聊天機器人。Now that your local bot is connected to ngrok you can configure your local bot to your Bot Channels Registration in Azure.

  1. 移至 Azure 中的 Bot 通道註冊。Go to your Bot Channels Registration in Azure. 按一下左側功能表上的 [設定],並使用 ngrok IP 來設定 [訊息端點]。Click Settings on the left menu and set the Messaging endpoint with your ngrok IP. 如有必要,請在 IP 位址後面新增 /api/messagesIf necessary add /api/messages after the IP address. (例如: https://e58549b6.ngrok.io/api/messages) 。(For example, https://e58549b6.ngrok.io/api/messages). 核取 [啟用串流端點] 和 [儲存]。Check Enable Streaming Endpoint and Save.

    端點

    提示

    如果 [儲存] 未啟用,則可以取消核取 [啟用串流端點],按一下 [儲存],然後再核取 [啟用串流端點] 並再次按一下 [儲存]。If Save is not enabled, you can uncheck Enable Streaming Endpoint and click Save, then check Enable Streaming Endpoint and click Save again. 您必須確定 [啟用串流端點] 已核取,且端點的設定也已儲存。You need to make sure that Enable Streaming Endpoint is checked and the configuration of the endpoint is saved.

  2. 移至聊天機器人的資源群組,按一下 [部署],然後選取先前成功部署的 Bot 通道註冊。Go to your bot's resource group, click Deployment, and select your Bot Channels Registration that previously deployed successfully. 按一下左側的 [輸入] 以取得 appIdappSecretClick Inputs on the left side to get the appId and appSecret. 使用 appIdappSecret 更新聊天機器人的 .env 檔案 (如果使用 C# 聊天機器人,則請更新 appsettings.json 檔案)。Update your bot's .env file (or appsettings.json file if you have a C# bot) with the appId and appSecret.

    get-inputs

  3. 啟動您的模擬器,按一下 [ 開啟 bot],並放入 http://localhost:3978/api/messages bot URLStart your Emulator, click Open Bot, and put http://localhost:3978/api/messages in the Bot URL. 使用您新增至聊天機器人 .env (appsettings.json) 檔案的相同 appIdappSecret 來填入 [Microsoft 應用程式識別碼] 和 [Microsoft 應用程式密碼]。Fill Microsoft App ID and Microsoft App password with the same appId and appSecret you added to our bot's .env (appsettings.json) file. 然後按一下 [ 連接]。Then click Connect.

  4. 執行中的聊天機器人現已連線至 Azure 中的 Bot 通道註冊。Your running bot is now connected to your Bot Channels Registration in Azure. 您可以按一下 [在網路聊天中測試] 並在聊天方塊中傳送訊息,以測試網路聊天。You can test the web chat by clicking Test in Web Chat and sending messages in the chat box.

    test-web-chat

  5. 現在讓我們在模擬器中啟用偵測模式。Now let's enable the debugging mode in the Emulator. 在模擬器中選取 [ Debug > 開始調試 程式]。In your Emulator select Debug > Start Debugging. 輸入 ngrok IP 位址 (別忘了為 BOT URL 新增 /api/messages) (例如 https://e58549b6.ngrok.io/api/messages) 。Enter the ngrok IP address (don't forget to add /api/messages) for the Bot URL (for example, https://e58549b6.ngrok.io/api/messages). 針對 [ Microsoft 應用程式識別碼],輸入 bot 的應用程式識別碼。For Microsoft App ID, enter your bot's app ID. 針對 Microsoft 應用程式密碼,請輸入 bot 的應用程式秘密。For Microsoft App password, enter your bot's app secret. 確定也已核取 [以偵錯模式開啟]。Make sure Open in debug mode is checked as well. 按一下 [ 連接]。Click Connect.

  6. 啟用偵錯工具模式時,會在您的模擬器中產生 UUID。When the debugging mode is enabled a UUID will be generated in your Emulator. UUID 是您每次在模擬器中啟動偵錯工具時所產生的唯一識別碼。A UUID is a unique ID generated every time you start the debugging mode in your Emulator. 將 UUID 複製並貼到 [在網路聊天中測試] 聊天方塊或通道的聊天方塊。Copy and paste the UUID to the Test in Web Chat chat box or your channel's chat box. 您會在聊天方塊中看到「已連結至工作階段,正在複寫所有流量以進行檢查」的訊息。You will see the message "Attached to session, all traffic is being replicated for inspection" in the chat box.

您可以藉由在所設定通道的聊天方塊中傳送訊息,來開始對聊天機器人進行偵錯。You can start debugging your bot by sending messages in the configured channel's chat box. 您的本機模擬器將會自動更新包含所有詳細資料的訊息,以進行偵錯工具。Your local Emulator will automatically update the messages with all the details for debugging. 若要檢查聊天機器人的訊息狀態,請按一下 [Bot 狀態],然後在右邊的 [JSON] 視窗中展開 [值]。To inspect your bot's state of messages click Bot State and unfold the values in the right JSON window.

debug-inspection-middleware

其他資源Additional resources