Search code examples
botframework

MS bot reply twice


At localhost in the emulator, as soon as I connect to the bot I get the sign in card but in the azure registered channel web chat I don't get the sign in card instead I need to type something then I get it twice. webchat screenshot How do I get the sign in card without the need to type something in chat. I've turned the always on option and it still didn't help.

The sign in card come from the community auth middleware Link here and i use the following code in the onTurn's bot class:

public async Task OnTurn(ITurnContext turnContext)
    {
        if (turnContext.Activity.UserHasJustJoinedConversation() || turnContext.Activity.UserHasJustSentMessage())
        {
            var state = turnContext.GetConversationState<Dictionary<string, object>>();
            var dialogCtx = dialogs.CreateContext(turnContext, state);


            await dialogCtx.Continue();
            if (!turnContext.Responded)
            {

                await dialogCtx.Begin("mainDialog", new Dictionary<string, object>
                {
                    ["Value"] = turnContext.Activity.Text
                });
            }
        }

    }

and i also use the following two functions

public static bool UserHasJustSentMessage(this Activity activity)
    {

        return activity.Type == ActivityTypes.Message;
    }

public static bool UserHasJustJoinedConversation(this Activity activity)
    {

        return activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.FirstOrDefault().Id != activity.Recipient.Id;
    }

Solution

  • There are two ConversationUpdates that get emitted when a conversation starts: one for the user joining the conversation and one for the bot joining the conversation so you need filter out the bot's one:

    public static bool UserHasJustJoinedConversation(this Activity activity)
    {
    
        return activity.Type == ActivityTypes.ConversationUpdate
            && activity.MembersAdded.Any(channelAccount => channelAccount.Id != "YourBotName");
    }