Creating Microsoft Bot Framework In Python 😍

Note
  • Python language support starts from Bot Framework SDK V4 and is in the preview stage.
  • Currently, the predefined template is not available for Visual Studio 2019. We are using Flask template to create the Bot Application.
This article focuses on how to write the “Hello World” application in Bot Framework using Python language. It has been divided into two sections. The first section focuses on the Project template changes and the next section focuses on the code changes.
  1. Project template changes
  2. Code file changes 
First, I will start Project template changes,
 

Project template changes

 
Prerequisites

Visual Studio 2019 Preview (Version 16.4.0) and make sure Python development is installed.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
Create a Project

The project type: “Blank Flask Web Project”.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
Project Name

Enter the project name “HelloWorld” and create a project.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
The project is successfully created.
 
Create a virtual environment
 
Go to the Solution Explorer and open the “requirements.txt” file and add the below namespace:
 
botbuilder-core>=4.4.0b1 ,botbuilder-dialogs>=4.4.0b1 save and close the file.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
In the tab, view header click the “Create virtual environment” and create the environment
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
Create a virtual environment,
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
The virtual environment was created successfully.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
For conformation check the module name displayed in the solution explorer in the ("Env") area.
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
Our Project template changes are done. Next, I am going to change the code files 
 

Code changes

 
Delete the default route function
 
Goto app.py file

Delete the hello() : function including app.route
  1. @app.route('/')  
  2. def hello():  
  3.     """Renders a sample page."""  
  4.     return "Hello World!"  
Port number update ( optional changes)

goto __main__ function and change the port number

  1. if __name__ == '__main__':  
  2.     import os  
  3.     HOST = os.environ.get('SERVER_HOST''localhost')  
  4.     try:  
  5.         PORT = int(os.environ.get('SERVER_PORT''5555'))  
  6.     except ValueError:  
  7.         PORT = 5555  
  8.     app.run(HOST, PORT)  
Delete the PORT = int(os.environ.get('SERVER_PORT', '5555')) line and hardcode the port value otherwise every time you run the application  anew port will be created, here I am using default bot framework port “PORT = 3978”
 
After changes the code looks like below:
  1. if __name__ == '__main__':  
  2.     import os  
  3.     HOST = os.environ.get('SERVER_HOST''localhost')  
  4.     try:  
  5.         PORT = 3978  
  6.     except ValueError:  
  7.         PORT = 5555  
  8.     app.run(HOST, PORT)  
Create on_turn function handling the IO operation.
 
Create a new Python class file (ex: file name is: “echobot.py”). Add the new class “EchoBot”,  this class adds the on_turn function. This function has two arguments
  1. Self, ref the current object 
  2. “context” object, This object handles the activity details.
In this sample, we are reading the string which is sent by the user and sends back to the user the same string with the length of string.
  1. from sys import exit  
  2.   
  3. class EchoBot:  
  4.     async def on_turn(self, context):  
  5.         if context.activity.type == "message" and context.activity.text:  
  6.             strlen = len(context.activity.text)  
  7.             sendInfo = "Hey you send text : " + context.activity.text + "  and  the lenght of the string is  " + str(strlen)  
  8.             await context.send_activity(sendInfo)  
asyn/await concept
 
Go to the “app.py” and add “import asyncio”, this has supported the async/await concept and "import sys" provides the information about constants, functions, and methods.  
  1. import asyncio  
  2. import sys  
Request and Response module
 
Add the request and response module in flask module. 
  1. from flask import Flask, request, Response  
Bot Framework module
 
Import the BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext from botbuilder.core to handle the Bot related queries. 
  1. from botbuilder.core import (  
  2.     BotFrameworkAdapter,  
  3.     BotFrameworkAdapterSettings,     
  4.     TurnContext,      
  5. )  
Import the Activity from botbuilder.schema,
  1. from botbuilder.schema import Activity  
Add the EchoBot class in the app.py file to handle the activity type,
  1. from echobot import*  
Object creation
 
Create the object for Echobot class and  
  1. bot = EchoBot()  
  2.   
  3. SETTINGS = BotFrameworkAdapterSettings("","")  
  4. ADAPTER = BotFrameworkAdapter(SETTINGS)   
Create an object for event loop, when called from a coroutine or a callback, this function will always return the running event loop.
  1. LOOP = asyncio.get_event_loop()  
Message handler function
 
This function is the heart of our application, and it handles all the requests and responses. Receiving the information from the request object as a JSON format and call the "await bot.on_turn(turn_context)" pass the turn_context as an argument.

In on_turn function we are checking the activity type. If its type is message, find the length of the string and send the information to the user using context.send_activity function.
  1. @app.route("/api/messages", methods=["POST"])  
  2. def messages():  
  3.     if "application/json" in request.headers["Content-Type"]:  
  4.         body = request.json  
  5.     else:  
  6.         return Response(status=415)  
  7.   
  8.     activity = Activity().deserialize(body)  
  9.     auth_header = (  
  10.         request.headers["Authorization"if "Authorization" in request.headers else ""  
  11.     )  
  12.   
  13.     async def aux_func(turn_context):  
  14.         await bot.on_turn(turn_context)  
  15.   
  16.     try:  
  17.         task = LOOP.create_task(  
  18.             ADAPTER.process_activity(activity, auth_header, aux_func)  
  19.         )  
  20.         LOOP.run_until_complete(task)  
  21.         return Response(status=201)  
  22.     except Exception as exception:  
  23.         raise exception  
That's it -- all the changes are done. Rebuild and run the application. 
 
Testing Steps
  1. Open the bot emulator and connect to the URL (http://localhost:3978/api/messages).
  2. Once it is connected, send the message
  3. Bot response to the channel and the information display in the emulator. 
Output
 
Let’s Start Microsoft Bot Framework Via Python 😍 Step By Step Guide
 
Please find the source from here

Conclusion


I hope you can understand the concept of how to create a bot application using Python. More articles are coming soon in Python languages, stay tuned.

Happy reading!!! Happy coding!!! 


Similar Articles