傳送歡迎訊息給使用者

適用于: SDK v4

建立任何 Bot 時的主要目標是讓您的使用者參與有意義的交談。 達成此目標的最佳方式之一是確保從使用者第一次連線的那一刻起,他們就會瞭解 Bot 的主要用途和功能,也就是 Bot 建立的原因。 本文提供程式碼範例,可協助您歡迎使用者使用 Bot。

注意

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

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

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

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

必要條件

關於此範例程式碼

此範例程式碼示範如何偵測並歡迎新使用者一開始連線到您的 Bot。 下圖顯示此 Bot 的邏輯流程。

Bot 遇到的兩個主要事件如下:

  • OnMembersAddedAsync,當新的使用者連線到 Bot 時呼叫。
  • OnMessageActivityAsync,會在 Bot 收到新的使用者輸入時呼叫。

Logic flow diagram for C# sample.

每當新使用者連線時,Bot 就會提供 WelcomeMessageInfoMessage 、 和 PatternMessage 。 收到新的使用者輸入時,會檢查 WelcomeUserState 是否 DidBotWelcomeUser 設定為 true 。 如果沒有,則會將初始歡迎使用者訊息傳回給使用者。

建立使用者狀態

使用者狀態物件會在啟動時建立,並將相依性插入 Bot 建構函式中。

Startup.cs


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

// Create the Bot Adapter with error handling enabled.

Bots\WelcomeUserBot.cs


// Initializes a new instance of the "WelcomeUserBot" class.
public WelcomeUserBot(UserState userState)
{
    _userState = userState;
}

建立屬性存取子

我們現在會建立屬性存取子,提供我們在 方法內的 OnMessageActivityAsync 控制碼 WelcomeUserState 。 然後呼叫 GetAsync 方法以取得適當範圍的索引鍵。 接著,我們會使用 SaveChangesAsync 方法,在每個使用者輸入反復專案之後儲存使用者狀態資料。

Bots\WelcomeUserState.cs

// Gets or sets whether the user has been welcomed in the conversation.
public bool DidBotWelcomeUser { get; set; } = false;

Bots\WelcomeUserBot.cs

var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState(), cancellationToken);

    await _userState.SaveChangesAsync(turnContext, cancellationToken: cancellationToken);
}

偵測並問候新連線的使用者

WelcomeUserBot 中,我們會使用 OnMembersAddedAsync() 檢查活動更新,以查看是否已將新使用者新增至交談,然後傳送一組三個初始歡迎訊息 WelcomeMessageInfoMessagePatternMessage 。 此互動的完整程式碼如下所示。

Bots\WelcomeUserBot.cs

public class WelcomeUserBot : ActivityHandler
{
    // Messages sent to the user.
    private const string WelcomeMessage = "This is a simple Welcome Bot sample. This bot will introduce you " +
                                            "to welcoming and greeting users. You can say 'intro' to see the " +
                                            "introduction card. If you are running this bot in the Bot Framework " +
                                            "Emulator, press the 'Start Over' button to simulate user joining " +
                                            "a bot or a channel";

    private const string InfoMessage = "You are seeing this message because the bot received at least one " +
                                        "'ConversationUpdate' event, indicating you (and possibly others) " +
                                        "joined the conversation. If you are using the emulator, pressing " +
                                        "the 'Start Over' button to trigger this event again. The specifics " +
                                        "of the 'ConversationUpdate' event depends on the channel. You can " +
                                        "read more information at: " +
                                        "https://aka.ms/about-botframework-welcome-user";

    private const string LocaleMessage = "You can use the activity's 'GetLocale()' method to welcome the user " +
                                         "using the locale received from the channel. " + 
                                         "If you are using the Emulator, you can set this value in Settings.";
{
    foreach (var member in membersAdded)
    {
        if (member.Id != turnContext.Activity.Recipient.Id)
        {
            await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken);
            await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken);
            await turnContext.SendActivityAsync($"{LocaleMessage} Current locale is '{turnContext.Activity.GetLocale()}'.", cancellationToken: cancellationToken);
            await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken);
        }
    }
}

歡迎新使用者並捨棄初始輸入

當您的使用者輸入實際上可能包含有用的資訊時,也請務必考慮,這可能會因每個通道而有所不同。 為了確保您的使用者在所有可能通道上都有良好的體驗,我們會檢查狀態旗標 didBotWelcomeUser ,如果這是 「false」,則不會處理初始使用者輸入。 相反地,我們會為使用者提供初始歡迎訊息。 bool welcomedUserProperty 接著會設定為 「true」,儲存在 UserState 中,我們的程式碼現在將處理來自所有其他訊息活動的此使用者的輸入。

Bots\WelcomeUserBot.cs

{
    var welcomeUserStateAccessor = _userState.CreateProperty<WelcomeUserState>(nameof(WelcomeUserState));
    var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState(), cancellationToken);

    if (didBotWelcomeUser.DidBotWelcomeUser == false)
    {
        didBotWelcomeUser.DidBotWelcomeUser = true;

        // the channel should sends the user name in the 'From' object
        var userName = turnContext.Activity.From.Name;

        await turnContext.SendActivityAsync("You are seeing this message because this was your first message ever to this bot.", cancellationToken: cancellationToken);
        await turnContext.SendActivityAsync($"It is a good practice to welcome the user and provide personal greeting. For example, welcome {userName}.", cancellationToken: cancellationToken);
    }
    else
    await _userState.SaveChangesAsync(turnContext, cancellationToken: cancellationToken);
}

處理其他輸入

歡迎新使用者之後,系統會針對每個訊息回合評估使用者輸入資訊,而 Bot 會根據該使用者輸入的內容提供回應。 下列程式碼顯示用來產生該回應的決策邏輯。

「簡介」或「說明」的輸入會呼叫 函 SendIntroCardAsync 式,向使用者呈現資訊主圖卡片。 本文的下一節會檢查該程式碼。

Bots\WelcomeUserBot.cs

    switch (text)
    {
        case "hello":
        case "hi":
            await turnContext.SendActivityAsync($"You said {text}.", cancellationToken: cancellationToken);
            break;
        case "intro":
        case "help":
            await SendIntroCardAsync(turnContext, cancellationToken);
            break;
        default:
            await turnContext.SendActivityAsync(WelcomeMessage, cancellationToken: cancellationToken);
            break;
    }
}

使用主圖卡片問候語

如上所述,某些使用者輸入會產生 主圖卡片 ,以回應其要求。 您可以在這裡 深入瞭解主圖卡片問候語傳送簡介卡片 。 以下是建立此 Bot 主圖卡片回應所需的程式碼。

Bots\WelcomeUserBot.cs

    {
        var card = new HeroCard
        {
            Title = "Welcome to Bot Framework!",
            Text = @"Welcome to Welcome Users bot sample! This Introduction card
                     is a great way to introduce your Bot to the user and suggest
                     some things to get them started. We use this opportunity to
                     recommend a few next steps for learning more creating and deploying bots.",
            Images = new List<CardImage>() { new CardImage("https://aka.ms/bf-welcome-card-image") },
            Buttons = new List<CardAction>()
            {
                new CardAction(ActionTypes.OpenUrl, "Get an overview", null, "Get an overview", "Get an overview", "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"),
                new CardAction(ActionTypes.OpenUrl, "Ask a question", null, "Ask a question", "Ask a question", "https://stackoverflow.com/questions/tagged/botframework"),
                new CardAction(ActionTypes.OpenUrl, "Learn how to deploy", null, "Learn how to deploy", "Learn how to deploy", "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"),
            }
        };

        var response = MessageFactory.Attachment(card.ToAttachment());
        await turnContext.SendActivityAsync(response, cancellationToken);
    }
}

測試聊天機器人

下載並安裝最新的 Bot Framework 模擬器

  1. 在本機電腦上執行範例。 如果您需要指示,請參閱 README C# 範例或 JavaScript 範例 的 檔案。
  2. 開啟模擬器以測試 Bot。
    1. 當您開始與 Bot 交談時,它會傳送一系列歡迎訊息。

    2. 當您第一次傳送 「hello」 訊息時,Bot 會以一些建議回復。

    3. 當您傳送後續的 「hello」 訊息時,Bot 會回復「您好」。

      Screenshot of initial interactions with your bot in the Emulator.

    4. 將「說明」訊息傳送至 Bot。 它會傳送主圖卡片來回應。

      Screenshot of the help message and the bot response in the Emulator.

其他資源

深入瞭解將媒體新增至訊息 中的 各種媒體回應。

下一步