PVA: Let chatbot start the conversation
Tags: powerplatform, powervirtualagent, chatbots, conversations
Published: 2021-02-09 16:46:43

---
title: PVA: Let chatbot start the conversation
published: true
date: 2021-01-28 11:00:00 UTC
tags: PowerPlatform,PowerVirtualAgent,Chatbots,Conversations
canonical_url: https://powermaverick.dev/2021/01/28/pva-let-chatbot-start-the-conversation/
---

In past we have seen [how we can embed chatbots on a Power Apps portals or a web page using client-side code and custom styling](https://powermaverick.dev/2020/04/08/add-styling-to-your-chat-bot/). We also looked at how to [add a chatbot on a WordPress site](https://dev.to/powermaverick/add-chat-bot-on-wordpress-site-2m5m-temp-slug-5948025) but all of these bots were created where the chatbot did not initiate the conversation but instead will wait for the users to initiate the conversation. This quickly becomes awkward for the users as they are not aware what to ask the bot and some help from the bot can go long way. This is where letting the bot start the conversation like “ **Hi, I am bot. I can help answering your question regarding ###** ” will provide directions to the user and have an interactive conversation which will feel natural.

As it has been a while I did not worked with Power Virtual Agent I didn’t get a chance to try out the improvements that was announced back in September, 2020 where we can use a custom code that can enable the bot to initiate the conversation. Link to the Microsoft documentation is [here](https://docs.microsoft.com/en-us/power-virtual-agents/configure-bot-greeting?WT.mc_id=BA-MVP-5003877).

In this post we are going to utilize a single page application where we will add our chatbot. First thing we will do is add a button inside our `<body>` tag that will resemble like a chat icon and upon clicking this button the chatbot will be surfaced. The following is the snippet for adding that button:

```

<button onclick="openChat()" role="openchatbutton" class="open-button">
    <i class="fa fa-4x fa-comments"></i>
</button>

```

Next we need to prepare the UI so that we can embed the chatbot:

```

<div role="openchat" id="chatWindow" class="chat-popup"
    style="order: 3; position: relative; width: 400px; min-width: 400px; height: 100%;">
    <div id="webchat-wrapper">
        <div id="webchat-header">Talk to TAB!!</div>
        <div id="webchat" role="main" id="webchat"></div>
    </div>
</div>

```

We have added the code but without style that won’t appear correctly, so let us add some styling to make sure position, visibility and UX is appropriate with the website design. The following styling needs to be added to your `.css` file and is only for demo purpose so feel free to change or experiment with it:

```

#webchat-wrapper {
  position: fixed;
  height: calc(100% - 230px);
  z-index: 9999;
  width: 400px;
  top: 140px;
  right: 30px;
  overflow: hidden;
}
#webchat {
  height: 90%;
}
#webchat-header {
  border-radius: 15px 15px 0px 0px;
  background: #f2f2f2;
  padding: 20px;
}
.chat-popup {
  display: none;
}
.open-button {
  background-color: transparent;
  color: white;
  border: none;
  cursor: pointer;
  opacity: 0.7;
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 9999;
} 

```

Similar to the process we used in [my previous post](https://powermaverick.dev/2020/04/08/add-styling-to-your-chat-bot/) we will be adding styling to the bot UI itself with the following css:

```

div[role="form"] {
  background: rgba(255,255,255,0.6);
}  
div[role="status"] {
  border-bottom: 1px solid rgb(230, 230, 230);
} 
div[role="status"] button {
  border-color: rgb(0, 0,0,0.4) !important;
  color: rgb(0, 0, 0) !important;
} 

```

Now, we have completed the design process and we need to add a logic to embed and invoke the chatbot. This is done using the following code:

```

<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>

<script>
const styleOptions = {

    // Add styleOptions to customize Web Chat canvas
    hideUploadButton: true,
    botAvatarInitials: 'TAB',
    userAvatarInitials: 'You',
    backgroundColor: 'rgba(255,255,255,0.85)'
};

// Add your BOT ID below 
var BOT_ID = "YOUR-BOT-ID-NEEDS-TO-GO-HERE";
var theURL = "https://powerva.microsoft.com/api/botmanagement/v1/directline/directlinetoken?botId=" + BOT_ID;

const store = window.WebChat.createStore(
    {},
    ({ dispatch }) => next => action => {
        if (action.type === "DIRECT_LINE/CONNECT_FULFILLED") {
            dispatch({
                meta: {
                    method: "keyboard",
                },
                payload: {
                    activity: {
                            channelData: {
                                postBack: true,
                            },
                            //Web Chat will show the 'Greeting' System Topic message which has a trigger-phrase 'hello'
                            name: 'startConversation',
                            type: "event"
                        },
                },
                type: "DIRECT_LINE/POST_ACTIVITY",
            });
        }
        return next(action);
    }
);

fetch(theURL)
    .then(response => response.json())
    .then(conversationInfo => {
        window.WebChat.renderWebChat(
            {
                directLine: window.WebChat.createDirectLine({
                    token: conversationInfo.token,
                }),
                store: store,
                styleOptions
            },
            document.getElementById('webchat')
        );
    })
    .catch(err => console.error("An error occurred: " + err));
</script>

```

As you can see from the highlighted code, we instantiated a variable to hold `window.WebChat.createStore` method which is then supplied to `window.WebChat.renderWebChat` method as one of the parameter. This piece of code enables the bot to start the conversation using the **Greetings** which is a system topic. If you wish to change the message that gets displayed when the bot loads you can change the messages in the **Greetings** system topic.

Now, the button we added is to show or hide the bot so it is not in the way of the user browsing your website. So initially, the `<div>` that holds the UI for bot is hidden and click of the button shows the `<div>` that has the bot. This is accomplished by the following code:

```

<script>
    function openChat() {
        var chatWindowElement = document.getElementById("chatWindow");
        if (window.getComputedStyle(chatWindowElement).display === "none") {
            document.getElementById("chatWindow").style.display = "block";
        } else {
            document.getElementById("chatWindow").style.display = "none";
        }
    }
</script>

```

Once you have all the pieces tied together you should have a working chatbot on your website. Below is the demo video of how the bot renders and works when embedded on this [demo website](http://pvademo.azurewebsites.net/):

<iframe width="750" height="368" src="https://video.wordpress.com/embed/MhEoWSVq?loop=1&amp;hd=1" frameborder="0" allowfullscreen></iframe><script src="https://v0.wordpress.com/js/next/videopress-iframe.js?m=1435166243"></script>

Hope this helps.

Don’t forget to subscribe to my [Power Platform Dev Newsletter](https://www.powerplatformdevelopersweekly.com/)