Giter Site home page Giter Site logo

microsoft / botbuilder-python Goto Github PK

View Code? Open in Web Editor NEW
659.0 64.0 265.0 8.74 MB

The Microsoft Bot Framework provides what you need to build and connect intelligent bots that interact naturally wherever your users are talking, from text/sms to Skype, Slack, Office 365 mail and other popular services.

Home Page: http://botframework.com

License: MIT License

Python 99.86% Batchfile 0.09% Shell 0.01% Dockerfile 0.05%
bot bots bot-framework microsoft microsoft-bot-framework python microsoft-cognitive-services

botbuilder-python's Introduction

Bot Framework SDK v4 Python

This repository contains code for the Python version of the Microsoft Bot Framework SDK, which is part of the Microsoft Bot Framework - a comprehensive framework for building enterprise-grade conversational AI experiences.

This SDK enables developers to model conversation and build sophisticated bot applications using Python. SDKs for JavaScript and .NET are also available.

To get started building bots using the SDK, see the Azure Bot Service Documentation.

For more information jump to a section below.

Build Status

Branch Description Build Status Coverage Status Code Style
Main 4.16.0 Builds Build Status Coverage Status Code style: black

Packages

Build Released Package
botbuilder-ai PyPI version
botbuilder-applicationinsights PyPI version
botbuilder-azure PyPI version
botbuilder-core PyPI version
botbuilder-dialogs PyPI version
botbuilder-schema PyPI version
botframework-connector PyPI version

|

Getting Started

To get started building bots using the SDK, see the Azure Bot Service Documentation.

The Bot Framework Samples includes a rich set of samples repository.

If you want to debug an issue, would like to contribute, or understand how the Bot Builder SDK works, instructions for building and testing the SDK are below.

Prerequisites

Python "Virtual Environments" allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally, as such it is common practice to use them. Click here to learn more about creating and activating Virtual Environments in Python.

Clone

Clone a copy of the repo:

git clone https://github.com/Microsoft/botbuilder-python.git

Change to the SDK's directory:

cd botbuilder-python

Using the SDK locally

To use a local copy of the SDK you can link to these packages with the pip -e option.

pip install -e ./libraries/botbuilder-schema
pip install -e ./libraries/botframework-connector
pip install -e ./libraries/botframework-streaming
pip install -e ./libraries/botbuilder-core
pip install -e ./libraries/botbuilder-ai
pip install -e ./libraries/botbuilder-applicationinsights
pip install -e ./libraries/botbuilder-dialogs
pip install -e ./libraries/botbuilder-azure
pip install -e ./libraries/botbuilder-integration-applicationinsights-aiohttp
pip install -e ./libraries/botbuilder-adapters-slack
pip install -e ./libraries/botbuilder-integration-aiohttp
pip install -e ./libraries/botbuilder-testing

Running unit tests

First execute the following command from the root level of the repo:

pip install -r ./libraries/botframework-connector/tests/requirements.txt
pip install -r ./libraries/botbuilder-core/tests/requirements.txt
pip install -r ./libraries/botbuilder-ai/tests/requirements.txt

Then enter run pytest by simply typing it into your CLI:

pytest

This is the expected output:

============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-3.4.0, py-1.5.2, pluggy-0.6.0
rootdir: C:\projects\botbuilder-python, inifile:
plugins: cov-2.5.1
...

Getting support and providing feedback

Below are the various channels that are available to you for obtaining support and providing feedback. Please pay carful attention to which channel should be used for which type of content. e.g. general "how do I..." questions should be asked on Stack Overflow, Twitter or Gitter, with GitHub issues being for feature requests and bug reports.

Github issues

Github issues should be used for bugs and feature requests.

Stack overflow

Stack Overflow is a great place for getting high-quality answers. Our support team, as well as many of our community members are already on Stack Overflow providing answers to 'how-to' questions.

Azure Support

If you issues relates to Azure Bot Service, you can take advantage of the available Azure support options.

Twitter

We use the @msbotframework account on twitter for announcements and members from the development team watch for tweets for @msbotframework.

Gitter Chat Room

The Gitter Channel provides a place where the Community can get together and collaborate.

Contributing and our code of conduct

We welcome contributions and suggestions. Please see our contributing guidelines for more information.

This project has adopted the Microsoft Open Source Code of Conduct.

For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Contributing Code

In order to create pull requests, submitted code must pass pylint and black checks. Run both tools on every file you've changed.

For more information and installation instructions, see:

Reporting Security Issues

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) at [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter.

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

botbuilder-python's People

Contributors

aacebo avatar axelsrz avatar ceciliaavila avatar clearab avatar cleemullins avatar congysu avatar daveta avatar denscollo avatar dependabot[bot] avatar eavanvalkenburg avatar emgrol avatar enzocano avatar ericdahlvang avatar gabog avatar garypretty avatar gurvsing avatar johnataylor avatar juanar avatar matthewshim-ms avatar mdrichardson avatar munozemilio avatar pcostantini avatar ramfattah avatar santgr11 avatar sgellock avatar stevengum avatar tracyboehrer avatar tsuwandy avatar virtual-josh avatar zerryth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

botbuilder-python's Issues

self._client.post takes from 1 to 3 positional arguments but 5 were given

Hello,

I'm trying to test the SDK using python, but I'm not able to run any of the samples through the emulator, nor the example as in Create a bot with the Bot Builder SDK for Python

I am able to run the Console-EchoBot, but this is very simple so I'm not able by myself to evolve the code to get to the other samples

I created a new Environment, cloned the release 4.0.0a5, installed the packages as per Bot Builder SDK v4 (Python) (Preview) and launched the emulator using the files *.bot to ensure I am not introducing any "error/variability"

Can anyone confirm if you can run the samples as per the current version?.

...botbuilder-python-4.0.0.a5\samples\Echo-Connector-Bot>python main.py

Error shown in console:
Started http server
127.0.0.1 - - [09/Jul/2018 16:31:10] "POST / HTTP/1.1" 202 -
127.0.0.1 - - [09/Jul/2018 16:31:10] "POST / HTTP/1.1" 202 -

Exception happened during processing of request from ('127.0.0.1', 49341)
Traceback (most recent call last):
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\socketserver.py", line 317, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\socketserver.py", line 348, in process_request
self.finish_request(request, client_address)
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\socketserver.py", line 361, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\socketserver.py", line 696, in init
self.handle()
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\http\server.py", line 418, in handle
self.handle_one_request()
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\http\server.py", line 406, in handle_one_request
method()
File "main.py", line 73, in do_POST
self.__handle_conversation_update_activity(activity)
File "main.py", line 36, in __handle_conversation_update_activity
connector.conversations.send_to_conversation(reply.conversation.id, reply)
File "C:\Users\plgrfer\AppData\Local\Continuum\anaconda3\envs\MSbot\lib\site-packages\botframework\connector\operations\conversations_operations.py", line 226, in send_to_conversation
request = self._client.post(url, query_parameters, header_parameters, body_content)
TypeError: post() takes from 1 to 3 positional arguments but 5 were given

BTW: I tested this in Windows 10 and in Ubuntu 16, but get the same error of 5 arguments given when takes from 1 to 3 positional...

Sample code snippets

add state
Simple Conversation Modeling (Echo Bot, primitives)
Complex Conversation Modeling (Alarm Bot, multi-dialogs, cards)
LUIS
QnA
Cards
Proactive Messages
Middleware
Directline
Support

'BotFrameworkAdapter.receive' was never awaited

I cloned the repo and tried to run main.py from echo bot (not async one) and this is what I get when I run the program:

main.py:82: RuntimeWarning: coroutine 'BotFrameworkAdapter.receive' was never awaited
  self._adapter.receive(self.headers.get("Authorization"), activity)

Unable to authenticate against Bot Framework

We tried to prototype a Skype Bot with a custom ubuntu server. As a basis we use the sample echo bot from this repository. We host the Server on Port 443 and wrap the Socket with the Python ssl module.

try:
    SERVER = http.server.HTTPServer(('', 443), BotRequestHandler)
    SERVER.socket = ssl.wrap_socket (SERVER.socket, 
        keyfile="server.key", 
        certfile='server.cert', server_side=True)
    print('Started http server')
    SERVER.serve_forever()
except KeyboardInterrupt:
    print('^C received, shutting down server')
SERVER.socket.close()

With our Setup we are able to connect our Bot to the Bot Framework and receive Messages. However, the Server does not answer (send response 401). We tried to Debug this Error and found that the error is within the authentication. We modified the Code to track the error and added some print Statements in the functions and print out the error in the authentication.

def do_POST(self):
        body = self.rfile.read(int(self.headers['Content-Length']))
        data = json.loads(str(body, 'utf-8'))
        activity = Activity.deserialize(data)
        
        print("do_post", activity.text)

        if not self.__handle_authentication(activity):
            print("handle_auth")
            return

        if activity.type == ActivityTypes.conversation_update.value:
            print("conv_upd")
            self.__handle_conversation_update_activity(activity)
        elif activity.type == ActivityTypes.message.value:
            print("msg_value")
            self.__handle_message_activity(activity)
        else:
            print("else")
            self.__unhandled_activity()

and

def __handle_authentication(self, activity):
        credential_provider = SimpleCredentialProvider(APP_ID, APP_PASSWORD)
        loop = asyncio.new_event_loop()
        try:
            loop.run_until_complete(JwtTokenValidation.authenticate_request(
                activity, self.headers.get("Authorization"), credential_provider))
            print("Try")
            return True
        except Exception as ex:
            print(ex)
            self.send_response(401, ex)
            self.end_headers()
            print("except")
            return False
        finally:
            print("fin")
            loop.close()

When we now send a message ("Hello Bot") to the Bot we get the following Output:

do_post Hello Bot

Task <Task pending coro=<JwtTokenValidation.authenticate_request() running at /home/ubuntu/.local/lib/python3.5/site-packages/botframework/connector/auth/jwt_token_validation.py:34> cb=[_run_until_complete_cb() at /usr/lib/python3.5/asyncio/base_events.py:164]> got Future <Task pending coro=<ChannelValidation.authenticate_token() running at /home/ubuntu/.local/lib/python3.5/site-packages/botframework/connector/auth/channel_validation.py:51>> attached to a different loop

52.164.229.112 - - [02/Aug/2018 07:44:41] "POST / HTTP/1.1" 401 -

except

fin

handle_auth

Is this an error from our Setup or in the sdk? How can we fix this error? Any help is appreciated.
AppId and password are handed over correct to the auth function and we also generated new passwords and tried with them -> No Change.
We use the latest stable releases installed via pip3.

Set inputHint in sendActivity()

We had agreed that we would by default set the inputHint to acceptingInput for all outgoing activities. We need to add this logic to TurnContext.sendActivity().

Custom State Data

Hi,
How do we implement custom state in V4 python. I used V3 Dotnet earlier it was pretty straightforward and regarding V4 python I don't know how far its possible

How to deploy Python chatbot SDK4 on Azure?

I've been playing around with the Botframework SDK4 for Python to create my simple chatbot. I'm trying to deploy it on Azure using the instructions at https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0

However, I've never worked with MS systems before (Azure/ VS) and I've been having problems following the instructions such as I can't find the 'publish' button as is said on that page.

Is there an easier way of doing this or any video tutorial?

Link to question asked on Stackoverflow

[Skype For Business] There was an error sending this message to your bot: HTTP status code InternalServerError

I understand that the SDK is still under development and might have issues. I just wanted to inform this issue. I've configure the Python SDK with a bot built on top of Flask. The web chat control works perfectly fine. But when I add the bot to Skype for Business, it show the following message.
skype

When I check the Azure channels page, the error is as follows

There was an error sending this message to your bot: HTTP status code InternalServerError

What I could see is that the Python backend is receiving the message perfectly from Skype For Business, but is failing to respond back. The python backend is hosted on Azure with domain *.azurewebsites.net which is https.

Suggest any area where I could check up on the issue !

M2 Python release

Middleware in a branch
publish packages in sync with master, update samples, wiki/ docs

Adaptive Cards for Web Chat

I've tried implementing Adaptive Cards based on this. I could see that Activity supports attachments parameter and accepts inputs as shown in the above link to implement Adaptive Cards. I could not understand the contentUrl though. I've filled in the remaining fields and tried this. i'm encountering the below issue.

My Activity

Activity(
        type=ActivityTypes.message,
        channel_id=request_activity.channel_id,
        conversation=request_activity.conversation,
        recipient=request_activity.from_property,
        from_property=request_activity.recipient,
        text=text,
        service_url=request_activity.service_url,
        attachments=Attachment(
            content_type="application/vnd.microsoft.card.adaptive",
            content={
                "type": "AdaptiveCard",
                "version": "1.0",
                "body": [
                    {
                    "type": "TextBlock",
                    "text": "Hello World!",
                    "size": "large"},
                    {
                    "type": "TextBlock",
                    "text": "*Sincerely yours,*"},
                    {
                    "type": "TextBlock",
                    "text": "Adaptive Cards",
                    "separation": "none"}],
                    "actions": [
                    {
                        "type": "Action.OpenUrl",
                        "url": "http://adaptivecards.io",
                        "title": "Learn More"
                    }
                    ]}),)

Error Log

ERROR:root:Error is:
Traceback (most recent call last):
File "D:\home\site\wwwroot\main.py", line 150, in messages
app.connector.conversations.send_to_conversation(activity['conversation']['id'], response_activity)
File "D:\home\python364x64\lib\site-packages\botframework\connector\operations\conversations_operations.py", line 224, in send_to_conversation
body_content = self._serialize.body(activity, 'Activity')
File "D:\home\python364x64\lib\site-packages\msrest\serialization.py", line 473, in body
errors = _recursive_validate(data_type, data_type, data)
File "D:\home\python364x64\lib\site-packages\msrest\serialization.py", line 124, in _recursive_validate
return data.validate()
File "D:\home\python364x64\lib\site-packages\msrest\serialization.py", line 184, in validate
validation_result += _recursive_validate(attr_name, attr_type, value)
File "D:\home\python364x64\lib\site-packages\msrest\serialization.py", line 116, in _recursive_validate
for content in data:
TypeError: 'Attachment' object is not iterable

My target is to have a card with a button. I've already implemented the SuggestedActions with buttons, but I need the button to be always available just in case the user wants to visit the link again. Is there any issue with the way I implemented this? Any samples towards this will be helpful.

The ConversationAccount doesn't have activity_id

Version

4.0

Describe the bug

In the bot_framework_adapter.py, update_activity method:

        try:
            client = self.create_connector_client(activity.service_url)
            return await client.conversations.update_activity_async(
                activity.conversation.id,
                activity.conversation.activity_id,
                activity)
        except Exception as e:
            raise e

The second parameter passed in the function seems wrong, the conversation is a type of ConversationAccount, which doesn't have activity_id attribute at all.

To Reproduce

Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

It should be

        try:
            client = self.create_connector_client(activity.service_url)
            return await client.conversations.update_activity_async(
                activity.conversation.id,
                activity.id,
                activity)
        except Exception as e:
            raise e

Screenshots

If applicable, add screenshots to help explain your problem.

Additional context

Add any other context about the problem here.

[bug]

SyntaxError: invalid syntax

After building from source all modules and just importing the following line:
from botbuilder.core import BotFrameworkAdapter
I get
image
Windows 10, x64, the same on Linux (CentOS)

Session Handling

๐Ÿšจ The issue tracker is not for questions ๐Ÿšจ

If you have a question, please ask it on https://stackoverflow.com/questions/tagged/botframework

async def messages(req: web.web_request) -> web.Response:
        
    session = await get_session(req) 
    User='None'
    if 'User_code' in session:
        User = session['User_code'] 
    else:
        random_id = ''.join([random.choice(string.ascii_letters 
            + string.digits) for n in range(16)]) 
        session['User_code'] = random_id
        User = session['User_code'] 
          text = 'User_code: {}'.format(User)
    print(text)
    body = await req.json()
    activity = Activity().deserialize(body)
    auth_header = req.headers['Authorization'] if 'Authorization' in req.headers else ''
    try:
        return await ADAPTER.process_activity(activity, auth_header, request_handler)
    except Exception as e:
        raise e

def make_app():
    app = web.Application()
    # app = web.Application(middlewares=[session_middleware_factory,])
    # secret_key must be 32 url-safe base64-encoded bytes
    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)
    setup(app, EncryptedCookieStorage(secret_key))
    app.router.add_post('/', messages)
    return app

try:
    web.run_app(make_app(), host='localhost', port=PORT)
except Exception as e:
    raise e

i'm testing on botframework emulator then session is always clear per question.
im not sure if problem is botframework , emulator or my code. what i want is if i save session name and value it must be kept. please check this issue. example result below (but value must be all same) i just used your Rich-Cards-Bot sample:

User_code: O6ZzukPijRcjY18w
User_code: 0E1nfH6m2tMuDRcW
User_code: erZyRVLMEiM2cS7I
User_code: 1lb4Kj5azHydF59K
User_code: PORfe9xn5M2beGuh
User_code: 9nZQxgocpJI32keb
User_code: GaCLP8FkyzgZOfp4
User_code: 0ykPMoFQzDC7rtap
User_code: p7EhxhMF4XFca7EL
User_code: Ys6V372dFuddG5Ol
User_code: LfIIMt05fMkldTE4

Operation returned an invalid status code 'Unauthorized'

I develop my bot locally, and I use Emulator to interact with my bot. But I got the exception "Operation returned an invalid status code 'Unauthorized'". I check the http status and I found '401'. But I read the documentation, it says if you test on your local machine, you needn't to fill in 'username' of 'password',
how can I do ?

Quick Reply not working

Hey,

I'm using botbuilder version 4.0.0a6 and I have a struggle with quick replies.
Quick replies are displayed in the emulator but not in any other Skype Client.

Here is the code I used :

def handle_request(self, request, channel_model):
    data = request.data

    activity = Activity.deserialize(data)

    if not self.__handle_authentication__(request, channel_model):
        return

    if activity.type == ActivityTypes.message.value:
        resp_activity = Activity(
            type=ActivityTypes.message,
            channel_id=activity.channel_id,
            conversation=activity.conversation,
            from_property=activity.recipient,
            recipient=activity.from_property,
            service_url=activity.service_url
        )

        replies = [
            {
                "title": "Test1",
                "type": ActionTypes.im_back,
                "value": "Test1",
            },
            {
                "title": "Test2",
                "type": ActionTypes.im_back,
                "value": "Test2",
            }
        ]

        resp_activity.text = "My text"
        resp_activity.suggested_actions = SuggestedActions(actions=replies, to=[activity.from_property.id])

        credentials = MicrosoftAppCredentials(channel_model.settings["app_id"], channel_model.settings["app_password"])

        try:
            connector = ConnectorClient(credentials, response_activity.service_url)
            connector.conversations.send_to_conversation(resp_activity.conversation.id, response_activity)
        except Exception as e:
            print("An error happened ! ")
            traceback.print_tb(e.__traceback__)
    else:
        return

Any help is really appreciated

async support and documentation

Hello, I'm trying to use the bot connector for python project using the example here and it works fine.

My project uses aiohttp framework, so I'm trying to use async methods in bot builder lib, but I can't make it work. I've tried just simply add "_async" to the methods and await them - this does not work. Then use the BotFrameworkAdapter and its methods. Both choices throws AttributeError exception, that the client object has no attribute "_session".

Traceback (most recent call last):
  File "/home/user/dev/myproject/.venv/lib/python3.6/site-packages/aiohttp/web_protocol.py", line 378, in start
    resp = await self._request_handler(request)
  File "/home/user/dev/myproject/.venv/lib/python3.6/site-packages/aiohttp/web_app.py", line 341, in _handle
    resp = await handler(request)
  File "/home/user/dev/myproject/.venv/lib/python3.6/site-packages/aiohttp/web_urldispatcher.py", line 740, in _iter
    resp = await method()
  File "/home/user/dev/myproject/simple-check/main_async.py", line 73, in post
    await self.__handle_conversation_update_activity(activity)
  File "/home/user/dev/myproject/simple-check/main_async.py", line 43, in __handle_conversation_update_activity
    await connector.conversations.send_to_conversation_async(reply.conversation.id, reply)
  File "/home/user/dev/myproject/.venv/lib/python3.6/site-packages/botframework/connector/operations/conversations_operations_async.py", line 214, in send_to_conversation_async
    request, header_parameters, body_content, stream=False, **operation_config)
  File "/home/user/dev/myproject/.venv/lib/python3.6/site-packages/botframework/connector/async_mixin/async_mixin.py", line 69, in async_send
    session = self.creds.signed_session(self._session)
AttributeError: 'ServiceClient' object has no attribute '_session'

In my opinion, the AsyncServiceClientMixin class adds support for await/async, but the connector needs to be initialized with async client with session to work. I can't find any documentation in the lib with information how to do that correctly.

Here is a code of aiohttp server (methods copied from Echo-Connector-Bot sample and server is replaced with aiohttp application):

from aiohttp.web import run_app
from aiohttp.web_app import Application
from aiohttp.web_response import json_response
from aiohttp.web_routedef import RouteTableDef
from aiohttp.web_urldispatcher import View
from botbuilder.schema import (Activity, ActivityTypes)
from botframework.connector import ConnectorClient
from botframework.connector.auth import (MicrosoftAppCredentials,
                                         JwtTokenValidation, SimpleCredentialProvider)

from os import getenv


APP_ID = getenv('MICROSOFT_BOT_BUILDER_APP_ID')
APP_PASSWORD = getenv('MICROSOFT_BOT_BUILDER_APP_PASSWORD')


routes = RouteTableDef()


@routes.view('/')
class BotView(View):
    def __create_reply_activity(self, request_activity, text):
        return Activity(
            type=ActivityTypes.message,
            channel_id=request_activity.channel_id,
            conversation=request_activity.conversation,
            recipient=request_activity.from_property,
            from_property=request_activity.recipient,
            text=text,
            service_url=request_activity.service_url)

    async def __handle_conversation_update_activity(self, activity):
        if activity.members_added[0].id != activity.recipient.id:
            credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
            reply = self.__create_reply_activity(activity, 'Hello and welcome to the echo bot!')
            connector = ConnectorClient(credentials, base_url=reply.service_url)
            connector.conversations.send_to_conversation(reply.conversation.id, reply)
            # Throws exception:
            # await connector.conversations.send_to_conversation_async(reply.conversation.id, reply)

    async def __handle_message_activity(self, activity):
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)
        reply = self.__create_reply_activity(activity, 'You said: "%s"' % activity.text)
        connector.conversations.send_to_conversation(reply.conversation.id, reply)
        # Throws exception:
        # await connector.conversations.send_to_conversation_async(reply.conversation.id, reply)

    async def __handle_authentication(self, activity):
        credential_provider = SimpleCredentialProvider(APP_ID, APP_PASSWORD)
        try:
            auth = self.request.headers.get("Authorization")
            await JwtTokenValidation.assert_valid_activity(activity, auth, credential_provider)
            return True
        except Exception as err:
            return False

    async def post(self):
        data = await self.request.json()
        activity = Activity.deserialize(data)

        is_authorized = await self.__handle_authentication(activity)
        if not is_authorized:
            return json_response(
                data={'status': 'not authorized'},
                status=400,
            )

        if activity.type == ActivityTypes.conversation_update.value:
            await self.__handle_conversation_update_activity(activity)
        elif activity.type == ActivityTypes.message.value:
            await self.__handle_message_activity(activity)

        return json_response(
            data={'status': 'ok'},
            status=200,
        )


if __name__ == '__main__':
    app = Application()
    app.add_routes(routes)
    run_app(app, host='0.0.0.0', port=8000)

requirements:

aiohttp==3.3.2
botbuilder-core==4.0.0a4
botbuilder-schema==4.0.0a3

TypeError: post() takes from 1 to 3 positional arguments but 5 were given

I am trying to run main.py from the folder - https://github.com/Microsoft/botbuilder-python/tree/master/samples/Echo-Connector-Bot/

I am getting this error when i send a message from the ms teams chat window.

Started http server
127.0.0.1 - - [19/Jul/2018 10:27:09] "POST / HTTP/1.1" 200 -
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46632)
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 317, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 348, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 696, in __init__
    self.handle()
  File "/usr/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "main.py", line 75, in do_POST
    self.__handle_message_activity(activity)
  File "main.py", line 44, in __handle_message_activity
    connector.conversations.send_to_conversation(reply.conversation.id, reply)
  File "/usr/local/lib/python3.6/dist-packages/botframework/connector/operations/conversations_operations.py", line 226, in send_to_conversation
    request = self._client.post(url, query_parameters, header_parameters, body_content)
TypeError: post() takes from 1 to 3 positional arguments but 5 were given

I am using these versions - (pip freeze output)

botbuilder==0.0.1
botbuilder-core==4.0.0a5
botbuilder-schema==4.0.0a5
botframework-connector==4.0.0a5

Am using any obsolete libraries?

Future plans for this project

First, thanks for this great initiative to make the botbuilder available using Python!

Seeing how the current roadmap seem to have been delayed and not a lot of recent development activity, it would be good to have an update on the current plans. Is there still a commitment to make this project suitable for production bot development in the near future? How stable is the current version considered?

Also happy to help out with development, if there are any particular parts where help is needed.

Thanks!

Phase 0 packages - connector, auth

Filing this issue to track work related to getting the Phase 0 packages for Python in. This should cover the connector and auth components

[ConnectorClient] Issue with KIK Channel - HTTPSConnectionPool(host='kik.botframework.com', port=443):

Hi Team,

I am using botbuilder-python sdk and its working fine for slack and skype channel but when i am running the "KIK" channel, I am getting the proper message from "KIK" but not able to send response back to "KIK" channel. Getting below error:

ERROR:
Exception in channel api send_reply- Error occurred in request., RetryError: HTTPSConnectionPool(host='kik.botframework.com', port=443): Max retries exceeded with url: /v3/conversations/{conversation_id}/activities (Caused by ResponseError('too many 500 error responses',))

CODE:

credentials = MicrosoftAppCredentials(
    os.environ.get('MICROSOFT_CLIENT_ID'), 
    os.environ.get('MICROSOFT_APP_SECRET')
)
connector = ConnectorClient(credentials, base_url=ActivityRequestObject['serviceUrl'])
activity = Activity(
    type=ActivityTypes.message,
    channel_id=ActivityRequestObject['channelId'],
    recipient=ChannelAccount(id=ActivityRequestObject['from']['id']),
    from_property=ChannelAccount(id=ActivityRequestObject['recipient']['id']),
    text=result_string
)
connector.conversations.send_to_conversation(ActivityRequestObject['conversation']['id'], activity)

While doing it manually by sending POST request it respond back with 400 error.

If any one have any idea what this issue is? As its working fine for slack and skype channel, I suppose either its a bug or data format for sending request to KIK channel is different.

Move Wiki to Docs?

Any chance the wiki information (like for building) gets moved to the repo so that others can edit/contribute? The current build/installation guide has some ambiguities when it comes to the virtual environment stuff. I've made a more explicit instruction set in a sample repo I'm building out, but would like to document items as I move along, and contribute back, if it's appropriate.

Issue with typing indicator (ActivityTypes.typing)

Hi Team,

Thanks for your continuous support.

I've used below code to send typing indicator. It works well but it continuously showing typing indicator for some duration after bot sends message to user.

activity = Activity(
    type=ActivityTypes.typing,
    channel_id=ActivityRequestObject['channelId'],
    recipient=ChannelAccount(id=ActivityRequestObject['from']['id'],
                             name=ActivityRequestObject['from']['name']),
    from_property=ChannelAccount(id=ActivityRequestObject['recipient']['id'],
                                 name=ActivityRequestObject['recipient']['name'])
)
connector.conversations.send_to_conversation(ActivityRequestObject['conversation']['id'], activity)

Can you please check if there is some issue with my code or add an example here for typing indicator? It will be really helpful.

Display HTML formatted table in Web Chat control

I'm trying to display a table in the web chat channel. I understand that Web Chat uses markdown for rendering text. But in the link suggests that we can pass textFormat to the activity to display a simple HTML table.

I tried passing the textFormat as 'xml' and a html table in the message content, but the web chat shows just the html content not the formatted table and I see the below in my log after the message is posted.

msrest.service_client:Accept header absent and forced to application/json

And I googled a bit and found that ms-rest for python==0.5.4 library has upgrades to support xml formatting and botbuilder-schema==4.0.0a6 currently uses msrest==0.4.29.

So is this the issue which is not rendering the html table properly. If not, what can be done so that I could send a clean table format to the bot in web chat. I tried sending markdown formatted tables using tabulate but it does not look good. Also tried using adaptive card, but with the amount of data I want to show, the adaptive cards does not seem to be a nice choice

async/await keyword is only used from Python 3.5 or above.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.
Kindly update README.md file (https://github.com/Microsoft/botbuilder-python/blob/master/samples/Rich-Cards-Bot/README.md) for Python3.5.
In Python lower version, it state error :--
File "main.py", line 32
async def create_reply_activity(request_activity, text) -> Activity:
^
SyntaxError: invalid syntax

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

[enhancement]

Phase 1 packages

This issue will track work to get the packages for the builder components including AI (LUIS, QnA, translator), table storage (state)

cant clone the requirements.txt

Command "git checkout -q a997e97cd926c1eedfe4e5a3a52a637313fbd4e4" failed with error code 128 in /private/var/folders/59/c59yst8s6dnd_gk0xdd4t_340000gn/T/pip-req-build-ZkQZiP

The bot referenced by the 'from' field is unrecognized - Unable to connect to Skype For Business channel

I'm trying to connect to Skype For Business channel using the Python SDK and could not. It returns the following error:

DEBUG:urllib3.connectionpool:https://webchat.botframework.com:443 "POST /v3/conversations/YmQ1MTkxZDkjc2lwOm1kbWJvdEBwZ29uZS5vbm1pY3Jvc29mdC5jb20%3D/activities HTTP/1.1" 400 128
DEBUG:msrest.exceptions:(MissingProperty) The bot referenced by the 'from' field is unrecognized
ERROR:root:Error is: 
Traceback (most recent call last):
  File "D:\home\site\wwwroot\main.py", line 127, in messages
    app.connector.conversations.send_to_conversation(activity['conversation']['id'], response_activity)
  File "D:\home\python364x64\lib\site-packages\botframework\connector\operations\conversations_operations.py", line 232, in send_to_conversation
    raise models.ErrorResponseException(self._deserialize, response)
botbuilder.schema.error_response_py3.ErrorResponseException: (MissingProperty) The bot referenced by the 'from' field is unrecognized

A conversation update activity from the bot:

{'type': 'conversationUpdate', 
'id': 'f5b9e798------', 
'timestamp': '2018-04-30T12:31:04.5652055Z', 
'serviceUrl': 'https://xxxxxxxx.lync.com/platformservice/tgt-xxxxxxxxxxxxxxxxxx/botframework', 
'channelId': 'skypeforbusiness', 
'from': {
  'id': 'sip:xxxxxxxxxx.com', 
  'name': 'xxxxxxxxxxxx'}, 
'conversation': 
{'isGroup': True,
'id': 'ZjJhYWZjZDYjcxxxxxxxxxxxxxxxxxxxxxxxxxxx'}, 
'recipient': 
{'id': 'sip:xxxxxxxxx.onmicrosoft.com', 
'name': 'sip:xxxxxx.onmicrosoft.com'}, 
'membersRemoved': 
[{'id': 'xxxxxxxxx', 
'name': 'xxxxxxxxxxxxxxx'}]}

I'm using the Flask sample from the link. This setup works well with the webchat but when I try talking to the bot from Skype For Business, I came accross this issue. There were similar issue logged in Bot builder SDK for .Net and node. The issues seems to be due to changes in v3.

I tried persisting the value from recipient field and sending it back with response but it didn't work. Am i missing something or is SFB channel not yet supported ?(REST API works fine with SFB using the same recipient and from values). Happy to provide more info if required.

Bot - Create new conversation

I'm using the botbuilder-python to build MS Teams bot. Following samples I am able to respond to messages. What I'm struggling with is creating completely new message, without existing activity passed from Teams. I modified some code from the tests (https://github.com/Microsoft/botbuilder-python/blob/62b0512a4dd918fa0d3837207012b31213aaedcc/libraries/botframework-connector/tests/test_conversations.py) but I'm getting:

botbuilder.schema.error_response_py3.ErrorResponseException: (BadSyntax) Could not parse tenant id

What is it, where can I find it (I can fish it out from request but it's not ideal, I need to be able to message user that has never interacted with the bot before) and how do I pass it? Can anyone point me at any Python samples of creating a completely new conversation with a user that has never interacted with the bot? There is a documentation page that's supposed to explain how to request it, but it only mentions that overload requiring tenant id is obsolete:

https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-context#fetching-the-team-roster

I realize it's not really an issue, but I asked it question on Stackoverflow (https://stackoverflow.com/questions/54994012/ms-teams-bot-create-new-conversation) and got a suggestion to post it here as well.

Message couldn't send, 401 response received

After following the documentation provided for developing a Python bot. All is fine until attempting to locally test the bot in the emulator (I've tried three different emulator versions including the two most recent V4 pre-releases and the latest stable version).

The code seems to run fine as in I get confirmation that the an http server is started on 'localhost:9000'. However, when configuring the bot to run on endpoint http://localhost:9000/api/messages, and sending a message in the emulator the message can't send. The response I receive in the terminal is "127.0.0.1 - - [18/Jul/2018 16:59:33] "POST /api/messages HTTP/1.1" 401 -". The error I receive in the emulator log in Emulator V.4.0.15-alpha is "POST 401 direct line.postActivity"

The error I receive in the emulator log in Emulator V 3 -Stable is POST Response code 401 (Unauthorized)

Am I missing a step? I followed the documentation word for word at https://docs.microsoft.com/en-us/azure/bot-service/python/bot-builder-python-quickstart?view=azure-bot-service-4.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.