Teams Chatbot Flow
We will now use a Webhook Flow to develop a simple Teams Chatbot that will respond with inventory information when the bot is @mentioned. We will then use the message to extract inventory information from the database created in the Save To Database flow.
For this tutorial we will first build the Webhook Flow and then test it. Finally we will integrate it as the URL endpoint for a Teams Outbound Webhook. When a message such as @botname cpu" is received we will use the message contents (assumed to be the equipment id or name) to retrieve the inventory count for this equipment and post it back as a message to Teams.
Prerequisite - MS Teams
Section titled “Prerequisite - MS Teams”You will need access to an MS Teams and PowerApps environment. If your company is not using Teams, you can still sign up for a free account if you want to test this flow. Alternatively you can use a similar process (if the system supports it) to post a message to Turbo Apps from Slack or any other messaging tool as they all mostly follow the same process.
- Head over to Power Automate
- On the left side-bar choose
Createand search forwebhook. - From the list of entries shown, select
Post to a channel when a webhook request is received.and clickContinue. - Now select the
Teamand theChannelyou want to send the message to. - Complete the setup and close the pop-up window.
- We now need to get the webhook URL. For that click on the
Editbutton. - From the list of nodes displayed select the first node ie. “When a Teams webhook is received”.
- A properties window is displayed and you need to Copy the generated HTTP URL.
Thats it, we are now ready to build the flow.
You can also configure the Outgoing webhook temporarily to point to a Request Bin or equivalent service that can save the post data for you to process. If you want to use Turbo Apps to determine that you can simply add an Email node to your flow and send a mail to yourself with the Email message set to flowinput so that the entire JSON is emailed to you.
Flow Development
Section titled “Flow Development”- In the Forms list, click on the
Flowsicon on the Computer Inspection row - A list of Flows will be displayed. Now click on the
Createbutton and choose theWebhook Flowoption- Title - Enter Teams Chatbot Webhook
- Description - Enter description as Flow to query and post inventory to Teams on an @mention or similar
- Expiry Date - Enter the date until when the webhook should be valid
- Click on
Saveto create the flow
- You will now be navigated to the Flow Builder
Understanding the steps
Section titled “Understanding the steps”Before we develop the flow, let us draw a flow chart of the different steps we need to perform to return the inventory:
flowchart TD
A([Start]) -->|Webhook Flow Trigger| B[Extract Equipment]
B --> C{Error}
C --> |No| D[Query Master Data for Equipment Inventory]
C --> |Yes| E([ReturnError])
D --> F{Error}
F --> |No| G(Prepare MS Teams text message with count)
F --> |Yes| E
G --> H([Return Success])
Developing the Flow
Section titled “Developing the Flow”- Remember for webhook flow there is no strict data format imposed. Data can be posted as post parameters or in the post body. Turbo Apps Flows will receive the input via the special FlowInput parameter in separate attributes as below. The body is saved as
postbodyand all other post parameters using the parameter name.For the chatbot we are interested in the message posted in the body and hence we will be using the{flowinput : {"postparam_1":"some value","postparam_2":"some value","postbody": {"bodyparam_1":"some other value","bodyparam_2": {"key","value"}}}}flowinput->postbodyfor extraction. - In the Flow Builder, the
Add Nodedialog should already be open. If not, click on theWebhook Flowstart node and then click on the :fontawesome-solid-circle-plus: icon that is displayed below the node - Search for the
JSON Parsernode by typing in json and clicking on it - The
JSON Parsernode is now opened and you can configure it.- Change the title to
Extract Equipmentand remember to connect theWebhook Flowstart nodeSuccessconnector to this node (else the expression builder will not display all the possible fields and nodes) - Since we want to work with the Flow Input, click on the
Otherssection - For
Map Field NameselectFlow Input - We need the post message format which is documented here. We are primarily interested in the
textattribute. The format is documented in the Azure Bot SDK documentation{"flowinput": {"postbody": {"type": "message","serviceUrl": "https://smba.trafficmanager.net/amer/","channelId": "msteams","from": {},"conversation": {},"recipient": null,"textFormat": "plain","locale": "en-US","text": "<p><at>TurboApps</at> computer</p>","attachments": [{}],"entities": [{}],"channelData": {},"callerId": "urn:botframework:azure"}}} - Under
Expressionclick on the :fontawesome-solid-wrench: icon to open the Expression Builder - Copy and paste the Flow Input JSON above into the
JSONwindow on the left - The expression builder we use for JSON parsing is a tool called Jsonata
- We need to extract the name of the equipment from the
textfield. Additionally spaces are converted to the html when pasted. Use the following expression to extract:$trim($replace($substringBefore($substringAfter($.postbody.text, "</at>"), "</p>"), " ", " ")) - Paste the expression from the step above into the
Mapping Expressionwindow on the right. The extracted equipmentcomputeris now displayed at the bottom. Confirm that what is displayed is correct. - Now Click on
Saveand close the builder, - Now Click on the :fontawesome-solid-floppy-disk: icon and save the node
- Change the title to
- Add a
Master Data Readnode by typing in read row and add theRead Rowsnode. - The
Read Rowsnode is now opened and you can configure it.- Change the title to
Read Inventoryand remember to connect theExtract EquipmentnodeSuccessconnector to this node (else the expression builder will not display all the possible fields and nodes) - In the
Master Data Entitydropdown, select Equipment Inventory - Now for
Master Data Filter, we are going to use the Query Builder to build a condition to filter the inventory master data onequipmentIdequal to the extracted equipment - From the dropdown select
EquipmentIdand the condition asEquals. Choose theCustomtoggle and then click on the :fontawesome-solid-wrench: icon again to open the Expression Builder - From the Previous option choose *Extract Equipment and then Result
- Click on save to close the query builder.
- Now click on the :fontawesome-solid-floppy-disk: icon and save the node
- Change the title to
- We now need to prepare the Teams message response. Click on the
Read Inventorynode and click on the :fontawesome-solid-circle-plus: icon that is displayed below the node - Search for the
JSON Parsernode by typing in json and clicking on it - The
JSON Parsernode is now opened and you can configure it.- Change the title to
Prepare Teams Messageand remember to connect theRead RowsnodeSuccessconnector above to this node (else the expression builder will not display all the possible fields and nodes) - Since we want to work with the retrieved inventory, click on the
Previous Stepssection - For
Map Field Nameselect Read Inventory and then Result - We need the message format returned by the
Read Rowsmaster data method. To get this intermediate result you can just type $. for the expression, connect the node andRun Flow. This will display the result format in theTracewindow which you can copy and open this configuration again. The data will be similar to:{"data": [{"equipmentId": "computer","submit": true,"inventory": 10}]} - Under
Expressionclick on the :fontawesome-solid-wrench: icon to open the Expression Builder - Copy and paste the Flow Input JSON above into the
JSONwindow on the left - The expression builder we use for JSON parsing is a tool called Jsonata
- We need to extract the inventory now. However remember that if the equipment was not found an empty array will be returned. So we use the
$exists*()function to make sure that the attribute exists. Also we will be using data[0] as we want the first returned row.$.{"text" : $exists(data[0].inventory) ? "Inventory count is: " & $string(data[0].inventory) : "Equipment inventory not found for: " & "{'${'}extractequipment_result}"} - Paste the expression from the step above into the
Mapping Expressionwindow on the right. The extracted equipmentcomputeris now displayed at the bottom. Confirm that what is displayed is correct. - Now Click on
Saveand close the builder, - Now Click on the :fontawesome-solid-floppy-disk: icon and save the node
- Change the title to
- Last step, we need to return data exactly how the Teams bot framework expects. For this click on the
Prepare Teams Messageand click on the :fontawesome-solid-circle-plus: icon that is displayed below the node - Search for the
Responsenode by typing in response and clicking on it - The
Responsenode is now opened and you can configure it.- Change the title to
Send To Teamsand remember to connect thePrepare Teams MessagenodeSuccessconnector above to this node (else the expression builder will not display all the possible fields and nodes) - Select the Success option
- Set the
HTTP Codeto 200 to signify HTTP Success - For
Bodyclick on the :fontawesome-solid-wrench: icon to open the Expression Builder - Select Result below the
Prepare Teams Messageentry - Now Click on the :fontawesome-solid-floppy-disk: icon and save the node
- Change the title to
- Connect the
Send To Teamsnode to Success - Now click on Publish button to save and compile the Sub flow. If the compilation is successful it will also be published and we can run it to test.
Testing the Flow
Section titled “Testing the Flow”- Now that we have published the flow we are ready to test it. The Flow Builder has an integrated Run and Debug tool to help us troubleshoot the flow in case of errors.
- Now click on the Run Flow button. The Run dialog is now displayed. Since this is the first time we are running the flow we need to enter Form (test) data now by clicking on the
Form Databutton and saving it. - Still in the Run Flow screen, copy the Teams Message JSON from above and paste it into the Flow Input field. The Flow Input now has the message that we want to process as though we received it from the bot.
- Run the flow by clicking on the
Runbutton. The flow should run successfully. - If there are errors it could be due to some mistakes while configuring the system or copy/pasting the expression or similar. Check each step carefully with the documentation above.
- However we cannot check if Teams received your response yet. This is because we simulated the webhook call using Run Flow. We actually didn’t receive a call from MS Teams.
Testing with MS Teams
Section titled “Testing with MS Teams”- Login to the Teams App
- Navigate to the Team to which you added the Outbound Webhook in the prerequisite step. Choose any channel under that team and click on
New Post - In the new post type in @turboapps (or select it from the list that pops up) and then type in computer. What we are now going to do is to send a message to the Turbo Apps via the configured outbound webhook by clicking on
Send - Wait a few seconds and you should see a message Inventory count is: 10*
- Now send another message by typing in @turboapps watercooler
- You should now get the response Equipment inventory not found for: watercooler. If you recall we didn’t add it to the inventory to simulate an error which we have now done!
Assignment
Section titled “Assignment”The flow above uses a Json Parser step to extract the message from the Flow Input field and process the input. We have made a very simple assumption that the user will @mention and then type in the equipment id. In reality the user is most likely to type in **Hey @turboapps can you check the computer inventory” or something similar. This process can be made better by using an LLM.
This is your assignment:
- Copy the
Teams Chatbot Webookflow toTeams Chatbot Webhook v2using theCopy Flowoption - Use OpenAI or any other LLM to process the input text message and extract the equipment id we need to fetch the inventory for.
- Add a
HTTPnode and configure it to make a call to the LLM. Follow the OpenAI or the other LLM API docs to do this. - Use the returned entity to search in the
Read Rowsstep. If the data from the LLM is returned in the form of a JSON, use aJSON Parsernode to extract it and process. - You can also improve the process by searching for the inventory master data using Equipment Name or Equipment Id by adding an OR condition in the condition node.
- After building it remember to change the outbound webhook URL in Teams and then test it
Check the solution for this assignment: Assignment Solution
Topics Covered
Section titled “Topics Covered”- Configuring a webhook that can be involed from Teams to build a chatbot
- Adding HTTP Server and the other parameters to POST a REST message call to MS Teams
- Some more advanced JSONata expressions for no code JSON parsing
- Working with
Flow Input - Reading master data and filtering using conditions
- Running the flow and testing it
- Using JSON parser to prepare JSON output text message for Teams