How to Build Microsoft Bot Framework with Python language

How to Build Microsoft Bot Framework with Python language

In this post, I'm explain the step by step How to Build Microsoft Bot Framework using Python language

Creating Microsoft Bot Framework In Python. In this post, I am going to explain the step by step execution of how to create a Bot Framework application in Python language using Visual Studio.

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
Project template changes

Prerequisites

Visual Studio 2019 Preview (Version 16.4.0) and make sure Python development is installed.

Create a Project

The project type: “Blank Flask Web Project”.

Project Name

Enter the project name “HelloWorld” and create a project.

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.

In the tab, view header click the “Create virtual environment” and create the environment

Create a virtual environment,

The virtual environment was created successfully.

For conformation check the module name displayed in the solution explorer in the ("Env") area.

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

@app.route('/')  
def hello():  
    """Renders a sample page."""  
    return "Hello World!"  

Port number update ( optional changes)

goto main function and change the port number

if __name__ == '__main__':  
    import os  
    HOST = os.environ.get('SERVER_HOST', 'localhost')  
    try:  
        PORT = int(os.environ.get('SERVER_PORT', '5555'))  
    except ValueError:  
        PORT = 5555  
    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:

if __name__ == '__main__':  
    import os  
    HOST = os.environ.get('SERVER_HOST', 'localhost')  
    try:  
        PORT = 3978  
    except ValueError:  
        PORT = 5555  
    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.

from sys import exit  
  
class EchoBot:  
    async def on_turn(self, context):  
        if context.activity.type == "message" and context.activity.text:  
            strlen = len(context.activity.text)  
            sendInfo = "Hey you send text : " + context.activity.text + "  and  the lenght of the string is  " + str(strlen)  
            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.

import asyncio  
import sys  

Request and Response module

Add the request and response module in flask module.

from flask import Flask, request, Response  

Bot Framework module

Import the BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext from botbuilder.core to handle the Bot related queries.

from botbuilder.core import (  
    BotFrameworkAdapter,  
    BotFrameworkAdapterSettings,     
    TurnContext,      
)  

Import the Activity from botbuilder.schema,

rom botbuilder.schema import Activity  

Add the EchoBot class in the app.py file to handle the activity type,

from echobot import*  

Object creation

Create the object for Echobot class and

bot = EchoBot()  
  
SETTINGS = BotFrameworkAdapterSettings("","")  
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.

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.

@app.route("/api/messages", methods=["POST"])  
def messages():  
    if "application/json" in request.headers["Content-Type"]:  
        body = request.json  
    else:  
        return Response(status=415)  
  
    activity = Activity().deserialize(body)  
    auth_header = (  
        request.headers["Authorization"] if "Authorization" in request.headers else ""  
    )  
  
    async def aux_func(turn_context):  
        await bot.on_turn(turn_context)  
  
    try:  
        task = LOOP.create_task(  
            ADAPTER.process_activity(activity, auth_header, aux_func)  
        )  
        LOOP.run_until_complete(task)  
        return Response(status=201)  
    except Exception as exception:  
        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

Please find the source from here

Conclusion

I hope you can understand the concept of how to create a bot application using Python.

Thank for reading and Happy coding!!!

Python in Visual Studio Code

Python in Visual Studio Code

Python in Visual Studio Code

This post was written by Luciana Abud, Program Manager for the Python Extension in Visual Studio Code

We are pleased to announce that the January 2019 release of the Python Extension for Visual Studio Code is now available. You can download the Python extension from the Marketplace, or install it directly from the extension gallery in Visual Studio Code. You can learn more about Python support in Visual Studio Code in the documentation.

In this release we have closed a total of 62 issues, including:

  • IPython console support in the Python Interactive window
  • Support for running an entire file in the Python Interactive window
  • Problems for failed tests when using pytest (thanks Chris NeJame)
  • Much faster outline when using the Python Language Server

Keep on reading to learn more!

IPython console support in the Python Interactive window

The data science experience was first introduced in the last October release, and one of the top feedback requests we’ve heard was to provide the ability to iterate rapidly by experimenting with code in an interactive console environment. In this update, we extended the Python Interactive window with IPython console support by allowing code to be typed in and executed directly in the window. You can now use the enhanced Interactive window standalone as an IPython console, or send code from the editor for execution.

Here’s how to use it in a nutshell:

  • IPython console support in the Python Interactive window
  • Support for running an entire file in the Python Interactive window
  • Problems for failed tests when using pytest (thanks Chris NeJame)
  • Much faster outline when using the Python Language Server

Run an entire file in the Python Interactive window without cells defined

Being able to run code in the Python Interactive window without having to define cells is no doubt one of the most requested features. This update enables running the entire files in the Interactive window without cell definitions.

To run the entire file, simply use the command Run Current File in Python Interactive window in the Command Palette. Your code will be executed with results displayed in the Python Interactive window.

We’ve also heard requests to run the current code selection / line in the editor, and this will be coming next in a future update.

Diagnostics for failed tests with pytest

This release also includes an enhancement to unit tests run with pytest: you can now see failed tests in the problems window. You can also double click lines to navigate to the failed test method and the exact failing line. The correspondent line in the editor will be selected, allowing you to easily identify and edit it.

As before, you can also see failed tests highlighted with pass/fail icons in the editor. You can hover these icons to see the errors navigate to the failing test method/line, just like in the problems window.

We’d like to thank community contributor Chris NeJame for implementing this new feature. Contributions to the Python extension are always welcome! If you’re interested, check our contributing guide to learn more.

Much faster outline view with the Python Language Server

We also made improvements to the outline view when using the Microsoft Python Language Server. The Outline view could often take a long time to load or even time out, and now with the Language Server It now loads consistently fast, and cases where symbols would appear duplicated were fixed.

As a reminder, the Language Server was released as a preview the last July release of the Python extension. To opt-in to the language server, change the python.jediEnabled setting to false in File > Preferences > User Settings. We are working towards making the language server the default in future releases.

Original source: https://blogs.msdn.microsoft.com

 ===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ The complete beginner’s guide to JSON

☞ The Complete Guide to JSON Web Tokens

☞ Python Programming For Beginners From Scratch

☞ Python Network Programming | Network Apps & Hacking Tools

☞ Intro To SQLite Databases for Python Programming

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

Visual Studio Code For Python Development

Visual Studio Code For Python Development

This video 'Visual Studio Code For Python Development' will help you understand how you can use the Python extension to write python code in the visual studio code editor.

This video 'Visual Studio Code For Python Development' will help you understand how you can use the Python extension to write python code in the visual studio code editor. Following are the topics discussed in this Visual Studio Code For Python Development tutorial:

  • What is Visual Studio Code?
  • Visual Studio Code Installation
  • Python Extension In VS Code
  • First Python Program In VS Code
  • Linting, Debugging Support
  • Jupyter Notebook Support
  • Python Interactive And Environments

Getting Started with Python in Visual Studio Code

Getting Started with Python in Visual Studio Code

Python is one of the most popular and easy to learn languages, which is why it is often one of the first languages you learn. Let’s see how to work with and run Python inside of Visual Studio Code!

Python is one of the most popular and easy to learn languages, which is why it is often one of the first languages you learn. Let’s see how to work with and run Python inside of Visual Studio Code!

Table of Contents

Install Python on Your Machine

The first thing you’ll need to take care of is installing Python on your machine. To do that, you can head to official Python download page and walk through the install process.

Mac Install Details

If you are using a Mac, you probably already have a version of Python installed, but it is an older version (2.7 for me). If you install the latest version (currently 3.x), you’ll have two different version installed. Applications on your mac are dependent on the older, so you can’t get rid of it.

Because of this, to run your python from the terminal you would need to use the “python3” command. Alternatively, you could set an alias, so that any time you type “python” you’re actually using the “python3” command. To setup this alias, you can type this into your terminal. You can use this post for reference.

alias python = 'python3'

Run Python From the Built in Terminal

A typical workflow for running your Python files will look like this.

To get started I recommend creating a folder on your Desktop (or a directory that you’re comfortable with) to put your Python files in for now. With that directory created and Python installed, now open up Visual Studio Code.

Inside of VS Code, open the folder/directory that you just created by going to File->Open and then choosing that directory. After that, you’ll see your folder open in the explorer window on the left.

With the directory open, you can create your first python file (.py extension) with some code to print “Hello World”.

Now that you have your Hello World code ready, we can run it by using the built-in temrinal in VS Code. If if is not open already, you can open it by going to View->Terminal or use the shortcut, Control+Tilde.

The terminal that you just opened will automatically start in the current directory that you are editing in VS Code. This is exactly why we created and opened a directory before getting started. We can prove this by running the following command (on Mac).

pwd

This command will print the path to the current directory. From there, you can verify that your python file is also inside of the current directory by running the following command (on Mac), which will print a list of files in the directory.

ls

Now, you can run your python file with the following command.

python <filename>

After running, you should see “Hello World” printed out in the console.

Install the Python Extension

That process wasn’t so bad, but working with Python gets a lot easier with the Python extension created by Microsoft. To install the extension, open up the extension menu on the left (the icon looks like a square inside of a square) and search Python.

The Python extension provides amazing intellisense, auto-completion, and muchmore!
It will be the first one that pops up, and you can click on it to view the extension details. Should look like this. Go ahead and click install.

After installing, you might need to reload, so go ahead and do that.

After you restart, you can now take advantage of several awesome features of this extension.

To get a sense for intellisense, create an empty array called “list”. Then type “list” followed by a period and notice that a bunch of information pops up. The extension is providing you all the functions and properties of a list that you can use.

If you want to use one of those functions, you can press enter or tab to auto-complete that function name. This means that don’t have to memorize every function in Python because the extension will give you hints as to what is available. Notice also that it shows you a brief description of what the function does and what parameters it takes.

You can also get intellisense when importing modules in Python. Notice that as I type “random”, intellisense pops up to complete the name of the module as well as providing some background info on what it does.

If you then start to use the random module, you’ll continue to get intellisense for functions that you can access with that module!

Lastly, you can hover on existing variables, module imports, etc. for additional information whenever you need it.

Use Shortcuts to Run Python Code

If you want to spice things up a bit in your Python file, here’s a short snippet for the Bubble Sort algorithm. It calls the Bubble Sort function and prints out the result. You can copy this code into your file if you’re interested.

def bubble_sort(list):
    sorted_list = list[:]
    is_sorted = False
    while is_sorted == False:
        swaps = 0
        for i in range(len(list) - 1):
        if sorted_list[i] > sorted_list[i + 1]: # swap
            temp = sorted_list[i]
            sorted_list[i] = sorted_list[i + 1]
            sorted_list[i + 1] = temp
            swaps += 1
            print(swaps)
        if swaps == 0:
        is_sorted = True
    return sorted_list

print(bubble_sort([2, 1, 3]))

With our fancy new piece of code taken care of, let’s explore a new way to run our python file. The typical first workflow for working with Python files (as we talked about previously) is to save your file and then run that python file in the terminal. With the Python extension, there are a few shortcuts to help with this process.

Inside of any Python file, you can right click in the editor and choose “Run Python File In Terminal”. This command will basically do each of the individual steps that we talked about before.

After using the shortcut, you can see the bubble sort output in your console.

You also have a shortcut to open the Python REPL where you can quickly type Python code directly into your console and see the output. Open the command pallette using the shortcut Command+Shift+P on Mac or Control+Shift+P on Windows and use the “Python Start REPL” command.

After typing in a print command, you will see “Hello World” immediately displayed in the console.

Recap

Python is incredibly popular language, and it has some really good support in VS Code. By installing the “Python” extension, you’ll get Python intellisense, auto-completion, and other useful misc. shortcuts.

Curious…Are you using Python? If so, are you using VS Code and the Python extension? Any other tools you’re using that you find useful?

Video from Youtube

Learn More

Complete Python: Go from zero to hero in Python

Python in Visual Studio Code

Computer Vision Using OpenCV

Learn Python 3 Programming for Beginners

An A-Z of useful Python tricks

A Complete Machine Learning Project Walk-Through in Python

Automated Machine Learning on the Cloud in Python

Learning Python: From Zero to Hero

Python Tutorial for Beginners (2019) - Learn Python for Machine Learning and Web Development

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science