ユーザーへのウェルカム メッセージの送信

この記事の対象: SDK v4

ボットを作成する主な目的は、有意義な会話によってユーザー エンゲージメントを高めることです。 この目標を達成するための効果的な方法の 1 つは、ユーザーが最初にアクセスした瞬間から、ボットの主な目的と機能 (ボットが作られた理由) をユーザーがわかるようにすることです。 この記事では、ボットのユーザーを歓迎するのに役立つコード サンプルを紹介します。

Note

Bot Framework JavaScript SDK、C#、Python SDK は引き続きサポートされますが、Java SDK については、最終的な長期サポートは 2023 年 11 月に終了する予定です。 このリポジトリ内の重要なセキュリティとバグの修正のみが行われます。

Java SDK を使用して構築された既存のボットは引き続き機能します。

新しいボットの構築については、Power Virtual Agents の使用を検討し、適切なチャットボット ソリューションの選択についてお読みください。

詳細については、「The future of bot building」をご覧ください。

前提条件

このサンプル コードについて

このサンプル コードは、新しいユーザーを検出し、そのユーザーがボットに最初に接続されたときにウェルカム メッセージを表示する方法を示しています。 次の図は、このボットのロジック フローです。

ボットの 2 つの主要なイベントを次に示します。

  • OnMembersAddedAsync: 新しいユーザーがボットに接続したときに呼び出されます。
  • OnMessageActivityAsync: ボットが新しいユーザー入力を受け取ったときに呼び出されます。

Logic flow diagram for C# sample.

接続された新しいユーザーには必ず、WelcomeMessageInfoMessage、および PatternMessage がボットから提供されます。 新しいユーザー入力を受信すると、WelcomeUserState で DidBotWelcomeUsertrue に設定されているかどうかが確認されます。 設定されていない場合、最初のウェルカム メッセージがユーザーに返されます。

ユーザーの状態を作成する

ユーザー状態オブジェクトはスタートアップ時に作成され、依存関係がボット コンストラクターに挿入されます。

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

プロパティ アクセサーを作成する

ここで、WelcomeUserState へのハンドルを返すプロパティ アクセサーを OnMessageActivityAsync メソッド内に作成します。 次に、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() を使用してアクティビティ更新をチェックし、会話に新しいユーザーが追加されたかどうかを確認して、そのユーザーに最初の 3 つのウェルカム メッセージ WelcomeMessageInfoMessage、および PatternMessage を送信します。 このインタラクションの完全なコードを以下に示します。

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" の場合、最初のユーザー入力は処理されません。 代わりに、ユーザーに最初のウェルカム メッセージを表示します。 ブール値 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);
}

追加入力を処理する

新しいユーザーにウェルカム メッセージが表示されると、メッセージ ターンごとにユーザー入力情報が評価され、そのユーザー入力のコンテキストに基づいてボットが応答します。 次のコードは、その応答の生成に使用する意思決定ロジックを示しています。

"Intro" または "help" の入力により関数 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;
    }
}

ヒーロー カード グリーティングを使用する

既に説明したように、一部のユーザー入力では、要求の応答として "ヒーロー カード" が生成されます。 ヒーロー カード グリーティングの詳細については、概要カードの送信に関するページをご覧ください。 このボットのヒーロー カード応答の作成に必要なコードを次に示します。

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 Emulator をダウンロードしてインストールします

  1. ご自身のマシンを使ってローカルでサンプルを実行します。 手順が必要な場合は、README ファイル内の C# サンプルまたは JavaScript サンプルを参照してください。
  2. エミュレーターを開いてボットをテストします。
    1. ボットとの会話を開始すると、一連のウェルカム メッセージが送信されます。

    2. "hello" メッセージを初めて送信すると、ボットは何らかのアドバイスで応答します。

    3. もう一度 "hello" メッセージを送信すると、ボットは "You said hello" (もう hello と言っていましたよ) と応答します。

      Screenshot of initial interactions with your bot in the Emulator.

    4. "help" メッセージをボットに送信します。 ヒーロー カードを送信して応答します。

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

その他のリソース

さまざまなメディアの応答の詳細については、「メッセージにメディアを追加する」を参照してください。

次のステップ