사용자에게 환영 메시지 보내기

적용 대상: SDK v4

봇을 만들 때의 주요 목표는 의미 있는 대화에 사용자를 참여시키는 것입니다. 이 목표를 달성하는 가장 좋은 방법 중 하나는 사용자가 처음 연결하는 순간부터 봇의 기본 목적과 기능, 봇이 만들어진 이유를 이해하는 것입니다. 이 문서에서는 봇에 사용자를 환영하는 데 도움이 되는 코드 예제를 제공합니다.

참고 항목

Bot Framework JavaScript, C#및 Python SDK는 계속 지원되지만 Java SDK는 2023년 11월에 종료되는 최종 장기 지원으로 사용 중지됩니다.

Java SDK를 사용하여 빌드된 기존 봇은 계속 작동합니다.

새 봇 빌드의 경우 Power Virtual Agents 사용을 고려하고 올바른 챗봇 솔루션을 선택하는 방법을 읽어 보세요.

자세한 내용은 봇 빌드의 미래를 참조 하세요.

필수 조건

이 샘플 코드 정보

이 샘플 코드는 봇에 처음 연결된 새 사용자를 검색하고 환영하는 방법을 보여 줍니다. 다음 다이어그램은 이 봇의 논리적 흐름을 보여줍니다.

봇에서 발생하는 두 기본 이벤트는 다음과 같습니다.

  • OnMembersAddedAsync새 사용자가 봇에 연결할 때 호출됩니다.
  • OnMessageActivityAsync은 봇이 새 사용자 입력을 받을 때 호출됩니다.

C# 샘플에 대한 논리 흐름 다이어그램입니다.

새 사용자가 연결될 때마다 봇과 함께 WelcomeMessageInfoMessagePatternMessage 제공됩니다. 새 사용자 입력이 수신되면 봇이 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;
}

속성 접근자 만들기

이제 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에서는 새 사용자가 대화에 추가되었는지 확인하고 3개의 초기 환영 메시지 InfoMessageWelcomeMessagePatternMessage집합을 보내도록 활동 OnMembersAddedAsync() 업데이트를 검사. 이 상호 작용의 전체 코드는 다음과 같습니다.

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

새 사용자 및 dis카드 초기 입력 시작

또한 사용자의 입력에 실제로 유용한 정보가 포함될 수 있는 경우를 고려해야 하며 채널마다 다를 수 있습니다. 사용자가 가능한 모든 채널에서 좋은 환경을 갖출 수 있도록 상태 플래그 didBotWelcomeUser를 검사 이 플래그가 "false"이면 초기 사용자 입력을 처리하지 않습니다. 대신 사용자에게 초기 환영 메시지를 제공합니다. bool welcomedUserProperty 는 UserState에 저장된 "true"로 설정되고 코드는 이제 모든 추가 메시지 활동에서 이 사용자의 입력을 처리합니다.

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

추가 입력 처리

새 사용자를 환영하면 각 메시지 턴에 대한 사용자 입력 정보가 평가되고 봇은 해당 사용자 입력의 컨텍스트에 따라 응답을 제공합니다. 다음 코드는 해당 응답을 생성하는 데 사용되는 결정 논리를 보여줍니다.

'소개' 또는 '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;
    }
}

hero 카드 인사말 사용

위에서 멘션 일부 사용자 입력은 요청에 대한 응답으로 Hero Card를 생성합니다. 소개 카드 보내기에서 영웅 카드 인사말에 대해 자세히 알아볼 수 있습니다. 다음은 이 봇의 hero 카드 응답을 만드는 데 필요한 코드입니다.

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. 머신에서 로컬로 샘플을 실행합니다. 지침이 필요한 경우 C# 샘플 또는 JavaScript 샘플에 대한 파일을 참조 README 하세요.
  2. 에뮬레이터를 열어 봇을 테스트합니다.
    1. 봇과 대화를 시작하면 일련의 환영 메시지가 전송됩니다.

    2. "hello" 메시지를 처음 보내면 봇이 몇 가지 조언으로 회신합니다.

    3. 후속 "hello" 메시지를 보내면 봇이 "Hello로 말했다"고 회신합니다.

      에뮬레이터에서 봇과의 초기 상호 작용 스크린샷.

    4. 봇에 "도움말" 메시지를 보냅니다. 그것은 영웅 카드 전송하여 응답합니다.

      에뮬레이터의 도움말 메시지 및 봇 응답 스크린샷.

추가 리소스

메시지에 미디어 추가에서 다양한 미디어 응답에 대해 자세히 알아봅니다.

다음 단계