Search code examples
botframeworkdirect-line-botframework

Updating properties of Bot Framework WebChat control after it has been instantiated?


I was wondering if there is any way to update properties of the Bot Framework WebChat control after it has been instantiated? I know I can update elements of the page the control is embedded on using DirectLine Backchannel, but I haven't figured out of if it's possible at all to update the BotChat.App properties via Backchannel.

(The idea is to update the user name property shown underneath the chat bubbles based on a response a user gives inside the bot.)

Grateful for any pointers, thanks!


Solution

  • update the user name property shown underneath the chat bubbles based on a response a user gives inside the bot.

    You can achieve the requirement via the backchannel mechanism, the following code snippet is for your reference.

    In your bot application:

    var replymes = activity.CreateReply();
    replymes.Type = "event";
    replymes.Name = "ChangeUnameEvent";
    
    replymes.Value = uname;
    
    await context.PostAsync(replymes);
    
    await context.PostAsync($"Your name is {uname}.");
    

    In your webchat client:

    var botConnection = new BotChat.DirectLine({ secret: 'your_directline_secret' });
    
    var userinfo = { id: 'You' };
    BotChat.App({
        botConnection: botConnection,
        user: userinfo,
        bot: { id: 'your_bot_id' },
        resize: 'detect'
    }, document.getElementById("bot"));
    
    
    botConnection.activity$
        .filter(activity => activity.type === "event" && activity.name === "ChangeUnameEvent")
        .subscribe(activity => changeUName(activity.value));
    
    function changeUName(val) {
        //alert(val);
        userinfo.id = val;
    }
    
    botConnection.activity$
        .filter(activity => activity.type === "message")
        .subscribe(activity => hidemessagesfordefaultuser(activity));
    
    function hidemessagesfordefaultuser(activity) {
        if (activity.from.id == "You") {
            activity.type = "event";
        }
    
        console.log(activity);
    }
    

    Test result:

    enter image description here

    Note:

    If you’d like to implement it in MessagesController, please try:

    else if (message.Type == ActivityTypes.Event && message.Name == "SendUserNameEvent")
    {
        var client = new ConnectorClient(new System.Uri(message.ServiceUrl), new MicrosoftAppCredentials());
    
        var reply = message.CreateReply();
        reply.Value = message.Value;
        reply.Type = "event";
        reply.Name = "ChangeUnameEvent";
    
        await client.Conversations.ReplyToActivityAsync(reply);
    }
    

    Send an event to bot:

    botConnection.postActivity({
        type: 'event',
        from: userinfo,
        name: 'SendUserNameEvent',
        value: "fei han"
    }).subscribe(function (id) { console.log('UName: fei han'); });