diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 4ccfae130..b25735215 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -12,80 +12,4 @@
# This should make it easy to add new rules without breaking existing ones.
# Global rule:
-* @microsoft/bb-python
-
-# Functional tests
-/libraries/functional-tests/** @tracyboehrer
-
-# Adapters
-/libraries/botbuilder-adapters-slack/** @tracyboehrer @garypretty
-
-# Platform Integration Libaries (aiohttp)
-/libraries/botbuilder-integration-aiohttp/** @microsoft/bb-python-integration
-/libraries/botbuilder-integration-applicationinsights-aiohttp/** @microsoft/bb-python-integration @garypretty
-
-# Application Insights/Telemetry
-/libraries/botbuilder-applicationinsights/** @axelsrz @garypretty
-
-# AI: LUIS + QnA Maker
-/libraries/botbuilder-ai/** @microsoft/bf-cog-services
-
-# Azure (Storage)
-/libraries/botbuilder-azure/** @tracyboehrer @EricDahlvang
-
-# Adaptive Dialogs
-/libraries/botbuilder-dialogs-*/** @tracyboehrer @microsoft/bf-adaptive
-
-# AdaptiveExpressions & LanguageGeneration libraries
-/libraries/adaptive-expressions/** @axelsrz @microsoft/bf-adaptive
-/libraries/botbuilder-lg/** @axelsrz @microsoft/bf-adaptive
-
-# BotBuilder Testing
-/libraries/botbuilder-testing/** @axelsrz @gabog
-
-# Streaming library
-/libraries/botbuilder-streaming/** @microsoft/bf-streaming
-
-# BotBuilder library
-/libraries/botbuilder-core/** @axelsrz @gabog @johnataylor
-
-# BotBuilder Dialogs
-/libraries/botbuilder-dialogs/** @microsoft/bf-dialogs
-
-# Swagger
-/libraries/swagger/** @axelsrz @EricDahlvang
-
-# Bot Framework Schema
-/libraries/botbuilder-schema/** @EricDahlvang @johnataylor
-
-# Bot Framework connector
-libraries\botframework-connector/** @axelsrz @carlosscastro @johnataylor
-
-# Bot Framework Authentication
-/libraries/botbuilder-core/botbuilder/core/oauth/** @microsoft/bf-auth
-/libraries/botframework-connector/botframework/connector/auth/** @microsoft/bf-auth
-
-# Bot Framework Skills
-/libraries/botbuilder-core/botbuilder/core/skills/** @microsoft/bf-skills
-/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/** @microsoft/bf-skills
-/tests/skills/** @microsoft/bf-skills
-
-# Bot Framework & Microsoft Teams
-/libraries/botbuilder-core/botbuilder/core/teams/** @microsoft/bf-teams
-/libraries/botbuilder-schema/botbuilder/schema/teams/** @microsoft/bf-teams
-/tests/teams/** @microsoft/bf-teams
-
-# Ownership by specific files or file types
-# This section MUST stay at the bottom of the CODEOWNERS file. For more information, see
-# https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#example-of-a-codeowners-file
-
-# Shipped package files
-# e.g. READMEs, requirements.txt, setup.py, MANIFEST.in
-/libraries/**/README.rst @microsoft/bb-python
-/libraries/**/requirements.txt @microsoft/bb-python
-/libraries/**/setup.py @microsoft/bb-python
-/libraries/**/setup.cfg @microsoft/bb-python
-/libraries/**/MANIFEST.in @microsoft/bb-python
-
-# CODEOWNERS
-/.github/CODEOWNERS @stevengum @cleemullins @microsoft/bb-python
+* @microsoft/botframework-sdk
\ No newline at end of file
diff --git a/README.md b/README.md
index b9ad280ca..9fb0dfe61 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,6 @@
# 
+**The Bot Framework Python SDK is being retired with final long-term support ending in November 2023, after which this repository will be archived. There will be no further feature development, with only critical security and bug fixes within this repository being undertaken. Existing bots built with this SDK will continue to function. For all new bot development we recommend that you adopt [Power Virtual Agents](https://powervirtualagents.microsoft.com/en-us/blog/the-future-of-bot-building/).**
### [What's new with Bot Framework](https://docs.microsoft.com/en-us/azure/bot-service/what-is-new?view=azure-bot-service-4.0)
This repository contains code for the Python version of the [Microsoft Bot Framework SDK](https://github.com/Microsoft/botframework-sdk), which is part of the Microsoft Bot Framework - a comprehensive framework for building enterprise-grade conversational AI experiences.
@@ -21,7 +22,7 @@ For more information jump to a section below.
| Branch | Description | Build Status | Coverage Status | Code Style |
|----|---------------|--------------|-----------------|--|
-| Main | 4.14.* Builds | [](https://fuselabs.visualstudio.com/SDK_v4/_build/latest?definitionId=771&branchName=main) | [](https://coveralls.io/github/microsoft/botbuilder-python?branch=HEAD) | [](https://github.com/psf/black) |
+| Main | 4.15.0 Builds | [](https://fuselabs.visualstudio.com/SDK_v4/_build/latest?definitionId=771&branchName=main) | [](https://coveralls.io/github/microsoft/botbuilder-python?branch=HEAD) | [](https://github.com/psf/black) |
## Packages
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 000000000..869fdfe2b
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,41 @@
+
+
+## Security
+
+Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
+
+If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.
+
+## Reporting Security Issues
+
+**Please do not report security vulnerabilities through public GitHub issues.**
+
+Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
+
+If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).
+
+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. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc).
+
+Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
+
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
+ * Full paths of source file(s) related to the manifestation of the issue
+ * The location of the affected source code (tag/branch/commit or direct URL)
+ * Any special configuration required to reproduce the issue
+ * Step-by-step instructions to reproduce the issue
+ * Proof-of-concept or exploit code (if possible)
+ * Impact of the issue, including how an attacker might exploit the issue
+
+This information will help us triage your report more quickly.
+
+If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.
+
+## Preferred Languages
+
+We prefer all communications to be in English.
+
+## Policy
+
+Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
+
+
diff --git a/generators/LICENSE.md b/generators/LICENSE.md
new file mode 100644
index 000000000..506ab97e5
--- /dev/null
+++ b/generators/LICENSE.md
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/generators/README.md b/generators/README.md
new file mode 100644
index 000000000..6d90531c3
--- /dev/null
+++ b/generators/README.md
@@ -0,0 +1,215 @@
+# python-generator-botbuilder
+
+Cookiecutter generators for [Bot Framework v4](https://dev.botframework.com). Will let you quickly set up a conversational AI bot
+using core AI capabilities.
+
+## About
+
+`python-generator-botbuilder` will help you build new conversational AI bots using the [Bot Framework v4](https://dev.botframework.com).
+
+## Templates
+
+The generator supports three different template options. The table below can help guide which template is right for you.
+
+| Template | Description |
+| ---------- | --------- |
+| Echo Bot | A good template if you want a little more than "Hello World!", but not much more. This template handles the very basics of sending messages to a bot, and having the bot process the messages by repeating them back to the user. This template produces a bot that simply "echoes" back to the user anything the user says to the bot. |
+| Core Bot | Our most advanced template, the Core template provides 6 core features every bot is likely to have. This template covers the core features of a Conversational-AI bot using [LUIS](https://www.luis.ai). See the **Core Bot Features** table below for more details. |
+| Empty Bot | A good template if you are familiar with Bot Framework v4, and simply want a basic skeleton project. Also a good option if you want to take sample code from the documentation and paste it into a minimal bot in order to learn. |
+
+### How to Choose a Template
+
+| Template | When This Template is a Good Choice |
+| -------- | -------- |
+| Echo Bot | You are new to Bot Framework v4 and want a working bot with minimal features. |
+| Core Bot | You understand some of the core concepts of Bot Framework v4 and are beyond the concepts introduced in the Echo Bot template. You're familiar with or are ready to learn concepts such as language understanding using LUIS, managing multi-turn conversations with Dialogs, handling user initiated Dialog interruptions, and using Adaptive Cards to welcome your users. |
+| Empty Bot | You are a seasoned Bot Framework v4 developer. You've built bots before, and want the minimum skeleton of a bot. |
+
+### Template Overview
+
+#### Echo Bot Template
+
+The Echo Bot template is slightly more than the a classic "Hello World!" example, but not by much. This template shows the basic structure of a bot, how a bot recieves messages from a user, and how a bot sends messages to a user. The bot will "echo" back to the user, what the user says to the bot. It is a good choice for first time, new to Bot Framework v4 developers.
+
+#### Core Bot Template
+
+The Core Bot template consists of set of core features most every bot is likely to have. Building off of the core message processing features found in the Echo Bot template, this template adds a number of more sophisticated features. The table below lists these features and provides links to additional documentation.
+
+| Core Bot Features | Description |
+| ------------------ | ----------- |
+| [Send and receive messages](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-send-messages?view=azure-bot-service-4.0) | The primary way your bot will communicate with users, and likewise receive communication, is through message activities. Some messages may simply consist of plain text, while others may contain richer content such as cards or attachments. |
+| [Proactive messaging](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0) using [Adaptive Cards](https://docs.microsoft.com/azure/bot-service/bot-builder-send-welcome-message?view=azure-bot-service-4.0?#using-adaptive-card-greeting) | The primary goal when creating any bot is to engage your user in a meaningful conversation. One of the best ways to achieve this goal is to ensure that from the moment a user first connects to your bot, they understand your bot’s main purpose and capabilities. We refer to this as "welcoming the user." The Core template uses an [Adaptive Card](http://adaptivecards.io) to implement this behavior. |
+| [Language understanding using LUIS](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0) | The ability to understand what your user means conversationally and contextually can be a difficult task, but can provide your bot a more natural conversation feel. Language Understanding, called LUIS, enables you to do just that so that your bot can recognize the intent of user messages, allow for more natural language from your user, and better direct the conversation flow. |
+| [Multi-turn conversation support using Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0) | The ability to manage conversations is an important part of the bot/user interation. Bot Framework introduces the concept of a Dialog to handle this conversational pattern. Dialog objects process inbound Activities and generate outbound responses. The business logic of the bot runs either directly or indirectly within Dialog classes. |
+| [Managing conversation state](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-state?view=azure-bot-service-4.0) | A key to good bot design is to track the context of a conversation, so that your bot remembers things like the answers to previous questions. |
+| [How to handle user-initiated interruptions](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-handle-user-interrupt?view=azure-bot-service-4.0) | While you may think that your users will follow your defined conversation flow step by step, chances are good that they will change their minds or ask a question in the middle of the process instead of answering the question. Handling interruptions means making sure your bot is prepared to handle situations like this. |
+| [How to unit test a bot](https://aka.ms/cs-unit-test-docs) | Optionally, the Core Bot template can generate corresponding unit tests that shows how to use the testing framework introduced in Bot Framework version 4.5. Selecting this option provides a complete set of units tests for Core Bot. It shows how to write unit tests to test the various features of Core Bot. To add the Core Bot unit tests, run the generator and answer `yes` when prompted. See below for an example of how to do this from the command line. |
+
+#### Empty Bot Template
+
+The Empty Bot template is the minimal skeleton code for a bot. It provides a stub `on_turn` handler but does not perform any actions. If you are experienced writing bots with Bot Framework v4 and want the minimum scaffolding, the Empty template is for you.
+
+## Features by Template
+
+| Feature | Empty Bot | Echo Bot | Core Bot* |
+| --------- | :-----: | :-----: | :-----: |
+| Generate code in Python | X | X | X |
+| Support local development and testing using the [Bot Framework Emulator v4](https://www.github.com/microsoft/botframework-emulator) | X | X | X |
+| Core bot message processing | | X | X |
+| Deploy your bot to Microsoft Azure | | Pending | Pending |
+| Welcome new users using Adaptive Card technology | | | X |
+| Support AI-based greetings using [LUIS](https://www.luis.ai) | | | X |
+| Use Dialogs to manage more in-depth conversations | | | X |
+| Manage conversation state | | | X |
+| Handle user interruptions | | | X |
+| Unit test a bot using Bot Framework Testing framework (optional) | | | X |
+
+*Core Bot template is a work in progress landing soon.
+## Installation
+
+1. Install [cookiecutter](https://github.com/cookiecutter/cookiecutter) using [pip](https://pip.pypa.io/en/stable/) (we assume you have pre-installed [python 3](https://www.python.org/downloads/)).
+
+ ```bash
+ pip install cookiecutter
+ ```
+
+2. Verify that cookiecutter has been installed correctly by typing the following into your console:
+
+ ```bash
+ cookiecutter --help
+ ```
+
+
+## Usage
+
+### Creating a New Bot Project
+
+To create an Echo Bot project:
+
+```bash
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/echo.zip
+```
+
+To create a Core Bot project:
+
+```bash
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/core.zip
+```
+
+To create an Empty Bot project:
+
+```bash
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/empty.zip
+```
+
+When the generator is launched, it will prompt for the information required to create a new bot.
+
+### Generator Command Line Options and Arguments
+
+Cookiecutter supports a set of pre-defined command line options, the complete list with descriptions is available [here](https://cookiecutter.readthedocs.io/en/0.9.1/advanced_usage.html#command-line-options).
+
+Each generator can recieve a series of named arguments to pre-seed the prompt default value. If the `--no-input` option flag is send, these named arguments will be the default values for the template.
+
+| Named argument | Description |
+| ------------------- | ----------- |
+| project_name | The name given to the bot project |
+| bot_description | A brief bit of text that describes the purpose of the bot |
+| add_tests | **PENDING** _A Core Bot Template Only Feature_. The generator will add unit tests to the Core Bot generated bot. This option is not available to other templates at this time. To learn more about the test framework released with Bot Framework v4.5, see [How to unit test bots](https://aka.ms/js-unit-test-docs). This option is intended to enable automated bot generation for testing purposes. |
+
+#### Example Using Named Arguments
+
+This example shows how to pass named arguments to the generator, setting the default bot name to test_project.
+
+```bash
+# Run the generator defaulting the bot name to test_project
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/echo.zip project_name="test_project"
+```
+
+### Generating a Bot Using --no-input
+
+The generator can be run in `--no-input` mode, which can be used for automated bot creation. When run in `--no-input` mode, the generator can be configured using named arguments as documented above. If a named argument is ommitted a reasonable default will be used.
+
+#### Default Values
+
+| Named argument | Default Value |
+| ------------------- | ----------- |
+| bot_name | `my-chat-bot` |
+| bot_description | "Demonstrate the core capabilities of the Microsoft Bot Framework" |
+| add_tests | `False`|
+
+#### Examples Using --no-input
+
+This example shows how to run the generator in --no-input mode, setting all required options on the command line.
+
+```bash
+# Run the generator, setting all command line options
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/echo.zip --no-input project_name="test_bot" bot_description="Test description"
+```
+
+This example shows how to run the generator in --no-input mode, using all the default command line options. The generator will create a bot project using all the default values specified in the **Default Options** table above.
+
+```bash
+# Run the generator using all default options
+cookiecutter https://github.com/microsoft/botbuilder-python/releases/download/Templates/echo.zip --no-input
+```
+
+This example shows how to run the generator in --no-input mode, with unit tests.
+
+```bash
+# PENDING: Run the generator using all default options
+```
+
+## Running Your Bot
+
+### Running Your Bot Locally
+
+To run your bot locally, type the following in your console:
+
+```bash
+# install dependencies
+pip install -r requirements.txt
+```
+
+```bash
+# run the bot
+python app.py
+```
+
+Alternatively to the last command, you can set the file in an environment variable with `set FLASK_APP=app.py` in windows (`export FLASK_APP=app.py` in mac/linux) and then run `flask run --host=127.0.0.1 --port=3978`
+
+### Interacting With Your Bot Using the Emulator
+
+- Launch Bot Framework Emulator
+- File -> Open Bot
+- Enter a Bot URL of `http://localhost:3978/api/messages`
+
+Once the Emulator is connected, you can interact with and receive messages from your bot.
+
+#### Lint Compliant Code
+
+The code generated by the botbuilder generator is pylint compliant to our ruleset. To use pylint as your develop your bot:
+
+```bash
+# Assuming you created a project with the bot_name value 'my_chat_bot'
+pylint --rcfile=my_chat_bot/.pylintrc my_chat_bot
+```
+
+#### Testing Core Bots with Tests (Pending)
+
+Core Bot templates generated with unit tests can be tested using the following:
+
+```bash
+# launch pytest
+pytest
+```
+
+## Deploy Your Bot to Azure
+
+After creating the bot and testing it locally, you can deploy it to Azure to make it accessible from anywhere.
+To learn how, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete set of deployment instructions.
+
+If you are new to Microsoft Azure, please refer to [Getting started with Azure](https://azure.microsoft.com/get-started/) for guidance on how to get started on Azure.
+
+## Logging Issues and Providing Feedback
+
+Issues and feedback about the botbuilder generator can be submitted through the project's [GitHub Issues](https://github.com/Microsoft/botbuilder-python/issues) page.
diff --git a/generators/app/templates/core/cookiecutter.json b/generators/app/templates/core/cookiecutter.json
new file mode 100644
index 000000000..4a14b6ade
--- /dev/null
+++ b/generators/app/templates/core/cookiecutter.json
@@ -0,0 +1,4 @@
+{
+ "bot_name": "my_chat_bot",
+ "bot_description": "Demonstrate the core capabilities of the Microsoft Bot Framework"
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/.pylintrc b/generators/app/templates/core/{{cookiecutter.bot_name}}/.pylintrc
new file mode 100644
index 000000000..9c1c70f04
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/.pylintrc
@@ -0,0 +1,498 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-whitelist=
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Specify a configuration file.
+#rcfile=
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=missing-docstring,
+ too-few-public-methods,
+ bad-continuation,
+ no-self-use,
+ duplicate-code,
+ broad-except,
+ no-name-in-module
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit
+
+
+[LOGGING]
+
+# Format style used to check logging format string. `old` means using %
+# formatting, while `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package..
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+ XXX,
+ TODO
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+ _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Maximum number of characters on a single line.
+max-line-length=120
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# List of optional constructs for which whitespace checking is disabled. `dict-
+# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
+# `trailing-comma` allows a space between comma and closing bracket: (a, ).
+# `empty-line` allows space-only lines.
+no-space-check=trailing-comma,
+ dict-separator
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+ bar,
+ baz,
+ toto,
+ tutu,
+ tata
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+ j,
+ k,
+ ex,
+ Run,
+ _
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[STRING]
+
+# This flag controls whether the implicit-str-concat-in-sequence should
+# generate a warning on implicit string concatenation in sequences defined over
+# several lines.
+check-str-concat-over-line-jumps=no
+
+
+[IMPORTS]
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=optparse,tkinter.tix
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled).
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled).
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement.
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+ Exception
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/README-LUIS.md b/generators/app/templates/core/{{cookiecutter.bot_name}}/README-LUIS.md
new file mode 100644
index 000000000..b6b9b925f
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/README-LUIS.md
@@ -0,0 +1,216 @@
+# Setting up LUIS via CLI:
+
+This README contains information on how to create and deploy a LUIS application. When the bot is ready to be deployed to production, we recommend creating a LUIS Endpoint Resource for usage with your LUIS App.
+
+> _For instructions on how to create a LUIS Application via the LUIS portal, see these Quickstart steps:_
+> 1. _[Quickstart: Create a new app in the LUIS portal][Quickstart-create]_
+> 2. _[Quickstart: Deploy an app in the LUIS portal][Quickstart-deploy]_
+
+ [Quickstart-create]: https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-build-app
+ [Quickstart-deploy]:https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-deploy-app
+
+## Table of Contents:
+
+- [Prerequisites](#Prerequisites)
+- [Import a new LUIS Application using a local LUIS application](#Import-a-new-LUIS-Application-using-a-local-LUIS-application)
+- [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#How-to-create-a-LUIS-Endpoint-resource-in-Azure-and-pair-it-with-a-LUIS-Application)
+
+___
+
+## [Prerequisites](#Table-of-Contents):
+
+#### Install Azure CLI >=2.0.61:
+
+Visit the following page to find the correct installer for your OS:
+- https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
+
+#### Install LUIS CLI >=2.4.0:
+
+Open a CLI of your choice and type the following:
+
+```bash
+npm i -g luis-apis@^2.4.0
+```
+
+#### LUIS portal account:
+
+You should already have a LUIS account with either https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. To determine where to create a LUIS account, consider where you will deploy your LUIS applications, and then place them in [the corresponding region][LUIS-Authoring-Regions].
+
+After you've created your account, you need your [Authoring Key][LUIS-AKey] and a LUIS application ID.
+
+ [LUIS-Authoring-Regions]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-reference-regions#luis-authoring-regions]
+ [LUIS-AKey]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-concept-keys#authoring-key
+
+___
+
+## [Import a new LUIS Application using a local LUIS application](#Table-of-Contents)
+
+### 1. Import the local LUIS application to luis.ai
+
+```bash
+luis import application --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appName "FlightBooking" --in "./cognitiveModels/FlightBooking.json"
+```
+
+Outputs the following JSON:
+
+```json
+{
+ "id": "########-####-####-####-############",
+ "name": "FlightBooking",
+ "description": "A LUIS model that uses intent and entities.",
+ "culture": "en-us",
+ "usageScenario": "",
+ "domain": "",
+ "versionsCount": 1,
+ "createdDateTime": "2019-03-29T18:32:02Z",
+ "endpoints": {},
+ "endpointHitsCount": 0,
+ "activeVersion": "0.1",
+ "ownerEmail": "bot@contoso.com",
+ "tokenizerVersion": "1.0.0"
+}
+```
+
+For the next step, you'll need the `"id"` value for `--appId` and the `"activeVersion"` value for `--versionId`.
+
+### 2. Train the LUIS Application
+
+```bash
+luis train version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --wait
+```
+
+### 3. Publish the LUIS Application
+
+```bash
+luis publish version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --publishRegion "LuisAppPublishRegion"
+```
+
+> `--region` corresponds to the region you _author_ your application in. The regions available for this are "westus", "westeurope" and "australiaeast".
+> These regions correspond to the three available portals, https://luis.ai, https://eu.luis.ai, or https://au.luis.ai.
+> `--publishRegion` corresponds to the region of the endpoint you're publishing to, (e.g. "westus", "southeastasia", "westeurope", "brazilsouth").
+> See the [reference docs][Endpoint-API] for a list of available publish/endpoint regions.
+
+ [Endpoint-API]: https://westus.dev.cognitive.microsoft.com/docs/services/5819c76f40a6350ce09de1ac/operations/5819c77140a63516d81aee78
+
+Outputs the following:
+
+```json
+ {
+ "versionId": "0.1",
+ "isStaging": false,
+ "endpointUrl": "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/########-####-####-####-############",
+ "region": "westus",
+ "assignedEndpointKey": null,
+ "endpointRegion": "westus",
+ "failedRegions": "",
+ "publishedDateTime": "2019-03-29T18:40:32Z",
+ "directVersionPublish": false
+}
+```
+
+To see how to create an LUIS Cognitive Service Resource in Azure, please see [the next README][README-LUIS]. This Resource should be used when you want to move your bot to production. The instructions will show you how to create and pair the resource with a LUIS Application.
+
+ [README-LUIS]: ./README-LUIS.md
+
+___
+
+## [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#Table-of-Contents)
+
+### 1. Create a new LUIS Cognitive Services resource on Azure via Azure CLI
+
+> _Note:_
+> _If you don't have a Resource Group in your Azure subscription, you can create one through the Azure portal or through using:_
+> ```bash
+> az group create --subscription "AzureSubscriptionGuid" --location "westus" --name "ResourceGroupName"
+> ```
+> _To see a list of valid locations, use `az account list-locations`_
+
+
+```bash
+# Use Azure CLI to create the LUIS Key resource on Azure
+az cognitiveservices account create --kind "luis" --name "NewLuisResourceName" --sku "S0" --location "westus" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
+```
+
+The command will output a response similar to the JSON below:
+
+```json
+{
+ "endpoint": "https://westus.api.cognitive.microsoft.com/luis/v2.0",
+ "etag": "\"########-####-####-####-############\"",
+ "id": "/subscriptions/########-####-####-####-############/resourceGroups/ResourceGroupName/providers/Microsoft.CognitiveServices/accounts/NewLuisResourceName",
+ "internalId": "################################",
+ "kind": "luis",
+ "location": "westus",
+ "name": "NewLuisResourceName",
+ "provisioningState": "Succeeded",
+ "resourceGroup": "ResourceGroupName",
+ "sku": {
+ "name": "S0",
+ "tier": null
+ },
+ "tags": null,
+ "type": "Microsoft.CognitiveServices/accounts"
+}
+```
+
+
+
+Take the output from the previous command and create a JSON file in the following format:
+
+```json
+{
+ "azureSubscriptionId": "00000000-0000-0000-0000-000000000000",
+ "resourceGroup": "ResourceGroupName",
+ "accountName": "NewLuisResourceName"
+}
+```
+
+### 2. Retrieve ARM access token via Azure CLI
+
+```bash
+az account get-access-token --subscription "AzureSubscriptionGuid"
+```
+
+This will return an object that looks like this:
+
+```json
+{
+ "accessToken": "eyJ0eXAiOiJKVtokentokentokentokentokeng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsItokenI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUzODc3MTUwLCJuYmYiOjE1NTM4NzcxNTAsImV4cCI6MTU1Mzg4MTA1MCwiX2NsYWltX25hbWVzIjp7Imdyb3VwcyI6InNyYzEifSwiX2NsYWltX3NvdXJjZXMiOnsic3JjMSI6eyJlbmRwb2ludCI6Imh0dHBzOi8vZ3JhcGgud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3VzZXJzL2ZmZTQyM2RkLWJhM2YtNDg0Ny04NjgyLWExNTI5MDA4MjM4Ny9nZXRNZW1iZXJPYmplY3RzIn19LCJhY3IiOiIxIiwiYWlvIjoiQVZRQXEvOEtBQUFBeGVUc201NDlhVHg4RE1mMFlRVnhGZmxxOE9RSC9PODR3QktuSmRqV1FqTkkwbmxLYzB0bHJEZzMyMFZ5bWZGaVVBSFBvNUFFUTNHL0FZNDRjdk01T3M0SEt0OVJkcE5JZW9WU0dzd0kvSkk9IiwiYW1yIjpbIndpYSIsIm1mYSJdLCJhcHBpZCI6IjA0YjA3Nzk1LThkZGItNDYxYS1iYmVlLTAyZjllMWJmN2I0NiIsImFwcGlkYWNyIjoiMCIsImRldmljZWlkIjoiNDhmNDVjNjEtMTg3Zi00MjUxLTlmZWItMTllZGFkZmMwMmE3IiwiZmFtaWx5X25hbWUiOiJHdW0iLCJnaXZlbl9uYW1lIjoiU3RldmVuIiwiaXBhZGRyIjoiMTY3LjIyMC4yLjU1IiwibmFtZSI6IlN0ZXZlbiBHdW0iLCJvaWQiOiJmZmU0MjNkZC1iYTNmLTQ4NDctODY4Mi1hMTUyOTAwODIzODciLCJvbnByZW1fc2lkIjoiUy0xLTUtMjEtMjEyNzUyMTE4NC0xNjA0MDEyOTIwLTE4ODc5Mjc1MjctMjYwOTgyODUiLCJwdWlkIjoiMTAwMzdGRkVBMDQ4NjlBNyIsInJoIjoiSSIsInNjcCI6InVzZXJfaW1wZXJzb25hdGlvbiIsInN1YiI6Ik1rMGRNMWszN0U5ckJyMjhieUhZYjZLSU85LXVFQVVkZFVhNWpkSUd1Nk0iLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1bmlxdWVfbmFtZSI6InN0Z3VtQG1pY3Jvc29mdC5jb20iLCJ1cG4iOiJzdGd1bUBtaWNyb3NvZnQuY29tIiwidXRpIjoiT2w2NGN0TXY4RVNEQzZZQWRqRUFtokenInZlciI6IjEuMCJ9.kFAsEilE0mlS1pcpqxf4rEnRKeYsehyk-gz-zJHUrE__oad3QjgDSBDPrR_ikLdweynxbj86pgG4QFaHURNCeE6SzrbaIrNKw-n9jrEtokenlosOxg_0l2g1LeEUOi5Q4gQREAU_zvSbl-RY6sAadpOgNHtGvz3Rc6FZRITfkckSLmsKAOFoh-aWC6tFKG8P52rtB0qVVRz9tovBeNqkMYL49s9ypduygbXNVwSQhm5JszeWDgrFuVFHBUP_iENCQYGQpEZf_KvjmX1Ur1F9Eh9nb4yI2gFlKncKNsQl-tokenK7-tokentokentokentokentokentokenatoken",
+ "expiresOn": "2200-12-31 23:59:59.999999",
+ "subscription": "AzureSubscriptionGuid",
+ "tenant": "tenant-guid",
+ "tokenType": "Bearer"
+}
+```
+
+The value needed for the next step is the `"accessToken"`.
+
+### 3. Use `luis add appazureaccount` to pair your LUIS resource with a LUIS Application
+
+```bash
+luis add appazureaccount --in "path/to/created/requestBody.json" --appId "LuisAppId" --authoringKey "LuisAuthoringKey" --armToken "accessToken"
+```
+
+If successful, it should yield a response like this:
+
+```json
+{
+ "code": "Success",
+ "message": "Operation Successful"
+}
+```
+
+### 4. See the LUIS Cognitive Services' keys
+
+```bash
+az cognitiveservices account keys list --name "NewLuisResourceName" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
+```
+
+This will return an object that looks like this:
+
+```json
+{
+ "key1": "9a69####dc8f####8eb4####399f####",
+ "key2": "####f99e####4b1a####fb3b####6b9f"
+}
+```
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/README.md b/generators/app/templates/core/{{cookiecutter.bot_name}}/README.md
new file mode 100644
index 000000000..4581ecc5b
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/README.md
@@ -0,0 +1,60 @@
+# CoreBot
+
+Bot Framework v4 core bot sample.
+
+This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to:
+
+- Use [LUIS](https://www.luis.ai) to implement core AI capabilities
+- Implement a multi-turn conversation using Dialogs
+- Handle user interruptions for such things as `Help` or `Cancel`
+- Prompt for and validate requests for information from the user
+
+## Prerequisites
+
+This sample **requires** prerequisites in order to run.
+
+### Overview
+
+This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding.
+
+### Install Python 3.6
+
+
+### Create a LUIS Application to enable language understanding
+
+LUIS language model setup, training, and application configuration steps can be found [here](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=cs).
+
+If you wish to create a LUIS application via the CLI, these steps can be found in the [README-LUIS.md](README-LUIS.md).
+
+## Running the sample
+- Run `pip install -r requirements.txt` to install all dependencies
+- Update LuisAppId, LuisAPIKey and LuisAPIHostName in `config.py` with the information retrieved from the [LUIS portal](https://www.luis.ai)
+- Run `python app.py`
+
+
+## Testing the bot using Bot Framework Emulator
+
+[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
+
+- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
+
+### Connect to the bot using Bot Framework Emulator
+
+- Launch Bot Framework Emulator
+- Enter a Bot URL of `http://localhost:3978/api/messages`
+
+
+## Further reading
+
+- [Bot Framework Documentation](https://docs.botframework.com)
+- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
+- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
+- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
+- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
+- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
+- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
+- [.NET Core CLI tools](https://docs.microsoft.com/dotnet/core/tools/?tabs=netcore2x)
+- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
+- [Azure Portal](https://portal.azure.com)
+- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
+- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/handlers/__init__.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/__init__.py
similarity index 100%
rename from tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/handlers/__init__.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/__init__.py
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/adapter_with_error_handler.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/adapter_with_error_handler.py
new file mode 100644
index 000000000..af1f81d98
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/adapter_with_error_handler.py
@@ -0,0 +1,56 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+import sys
+import traceback
+from datetime import datetime
+
+from botbuilder.core import (
+ BotFrameworkAdapter,
+ BotFrameworkAdapterSettings,
+ ConversationState,
+ TurnContext,
+)
+from botbuilder.schema import ActivityTypes, Activity
+
+
+class AdapterWithErrorHandler(BotFrameworkAdapter):
+ def __init__(
+ self,
+ settings: BotFrameworkAdapterSettings,
+ conversation_state: ConversationState,
+ ):
+ super().__init__(settings)
+ self._conversation_state = conversation_state
+
+ # Catch-all for errors.
+ async def on_error(context: TurnContext, error: Exception):
+ # This check writes out errors to console log
+ # NOTE: In production environment, you should consider logging this to Azure
+ # application insights.
+ print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
+ traceback.print_exc()
+
+ # Send a message to the user
+ await context.send_activity("The bot encountered an error or bug.")
+ await context.send_activity(
+ "To continue to run this bot, please fix the bot source code."
+ )
+ # Send a trace activity if we're talking to the Bot Framework Emulator
+ if context.activity.channel_id == "emulator":
+ # Create a trace activity that contains the error object
+ trace_activity = Activity(
+ label="TurnError",
+ name="on_turn_error Trace",
+ timestamp=datetime.utcnow(),
+ type=ActivityTypes.trace,
+ value=f"{error}",
+ value_type="https://www.botframework.com/schemas/error",
+ )
+ # Send a trace activity, which will be displayed in Bot Framework Emulator
+ await context.send_activity(trace_activity)
+
+ # Clear out state
+ nonlocal self
+ await self._conversation_state.delete(context)
+
+ self.on_turn_error = on_error
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/app.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/app.py
new file mode 100644
index 000000000..8d2e9fc5d
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/app.py
@@ -0,0 +1,76 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+"""
+This sample shows how to create a bot that demonstrates the following:
+- Use [LUIS](https://www.luis.ai) to implement core AI capabilities.
+- Implement a multi-turn conversation using Dialogs.
+- Handle user interruptions for such things as `Help` or `Cancel`.
+- Prompt for and validate requests for information from the user.
+"""
+
+from aiohttp import web
+from aiohttp.web import Request, Response, json_response
+from botbuilder.core import (
+ BotFrameworkAdapterSettings,
+ ConversationState,
+ MemoryStorage,
+ UserState,
+)
+from botbuilder.core.integration import aiohttp_error_middleware
+from botbuilder.schema import Activity
+
+from config import DefaultConfig
+from dialogs import MainDialog, BookingDialog
+from bots import DialogAndWelcomeBot
+
+from adapter_with_error_handler import AdapterWithErrorHandler
+from flight_booking_recognizer import FlightBookingRecognizer
+
+CONFIG = DefaultConfig()
+
+# Create adapter.
+# See https://aka.ms/about-bot-adapter to learn more about how bots work.
+SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
+
+# Create MemoryStorage, UserState and ConversationState
+MEMORY = MemoryStorage()
+USER_STATE = UserState(MEMORY)
+CONVERSATION_STATE = ConversationState(MEMORY)
+
+# Create adapter.
+# See https://aka.ms/about-bot-adapter to learn more about how bots work.
+ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)
+
+# Create dialogs and Bot
+RECOGNIZER = FlightBookingRecognizer(CONFIG)
+BOOKING_DIALOG = BookingDialog()
+DIALOG = MainDialog(RECOGNIZER, BOOKING_DIALOG)
+BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
+
+
+# Listen for incoming requests on /api/messages.
+async def messages(req: Request) -> Response:
+ # Main bot message handler.
+ if "application/json" in req.headers["Content-Type"]:
+ body = await req.json()
+ else:
+ return Response(status=415)
+
+ activity = Activity().deserialize(body)
+ auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
+
+ response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
+ if response:
+ return json_response(data=response.body, status=response.status)
+ return Response(status=201)
+
+
+APP = web.Application(middlewares=[aiohttp_error_middleware])
+APP.router.add_post("/api/messages", messages)
+
+if __name__ == "__main__":
+ try:
+ web.run_app(APP, host="localhost", port=CONFIG.PORT)
+ except Exception as error:
+ raise error
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/booking_details.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/booking_details.py
new file mode 100644
index 000000000..53364aabc
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/booking_details.py
@@ -0,0 +1,18 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from typing import List
+
+
+class BookingDetails:
+ def __init__(
+ self,
+ destination: str = None,
+ origin: str = None,
+ travel_date: str = None,
+ unsupported_airports: List[str] = None,
+ ):
+ self.destination = destination
+ self.origin = origin
+ self.travel_date = travel_date
+ self.unsupported_airports = unsupported_airports or []
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/bots/__init__.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/__init__.py
similarity index 89%
rename from tests/experimental/101.corebot-bert-bidaf/bot/bots/__init__.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/bots/__init__.py
index 7c71ff86f..ee51d6cec 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/bots/__init__.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/__init__.py
@@ -1,6 +1,5 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""bots module."""
from .dialog_bot import DialogBot
from .dialog_and_welcome_bot import DialogAndWelcomeBot
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_and_welcome_bot.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_and_welcome_bot.py
similarity index 57%
rename from tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_and_welcome_bot.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_and_welcome_bot.py
index c6e63079c..6e1ef90d0 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_and_welcome_bot.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_and_welcome_bot.py
@@ -1,41 +1,39 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Main dialog to welcome users."""
+
import json
import os.path
+
from typing import List
-from botbuilder.core import TurnContext
-from botbuilder.schema import Activity, Attachment, ChannelAccount
-from helpers.activity_helper import create_activity_reply
+from botbuilder.core import MessageFactory, TurnContext
+from botbuilder.schema import Attachment, ChannelAccount
+
+from helpers import DialogHelper
from .dialog_bot import DialogBot
class DialogAndWelcomeBot(DialogBot):
- """Main dialog to welcome users implementation."""
async def on_members_added_activity(
self, members_added: List[ChannelAccount], turn_context: TurnContext
):
for member in members_added:
# Greet anyone that was not the target (recipient) of this message.
- # To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards
- # for more details.
+ # To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if member.id != turn_context.activity.recipient.id:
welcome_card = self.create_adaptive_card_attachment()
- response = self.create_response(turn_context.activity, welcome_card)
+ response = MessageFactory.attachment(welcome_card)
await turn_context.send_activity(response)
-
- def create_response(self, activity: Activity, attachment: Attachment):
- """Create an attachment message response."""
- response = create_activity_reply(activity)
- response.attachments = [attachment]
- return response
+ await DialogHelper.run_dialog(
+ self.dialog,
+ turn_context,
+ self.conversation_state.create_property("DialogState"),
+ )
# Load attachment from file.
def create_adaptive_card_attachment(self):
- """Create an adaptive card."""
relative_path = os.path.abspath(os.path.dirname(__file__))
- path = os.path.join(relative_path, "resources/welcomeCard.json")
+ path = os.path.join(relative_path, "../cards/welcomeCard.json")
with open(path) as card_file:
card = json.load(card_file)
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_bot.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_bot.py
similarity index 76%
rename from tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_bot.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_bot.py
index 2f161c4c7..caf39b3d9 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/bots/dialog_bot.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/bots/dialog_bot.py
@@ -1,15 +1,13 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Implements bot Activity handler."""
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
from botbuilder.dialogs import Dialog
-from helpers.dialog_helper import DialogHelper
+from helpers import DialogHelper
-class DialogBot(ActivityHandler):
- """Main activity handler for the bot."""
+class DialogBot(ActivityHandler):
def __init__(
self,
conversation_state: ConversationState,
@@ -28,14 +26,11 @@ def __init__(
self.conversation_state = conversation_state
self.user_state = user_state
self.dialog = dialog
- self.dialogState = self.conversation_state.create_property(
- "DialogState"
- ) # pylint: disable=C0103
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
- # Save any state changes that might have occured during the turn.
+ # Save any state changes that might have occurred during the turn.
await self.conversation_state.save_changes(turn_context, False)
await self.user_state.save_changes(turn_context, False)
@@ -44,4 +39,4 @@ async def on_message_activity(self, turn_context: TurnContext):
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
- ) # pylint: disable=C0103
+ )
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/bots/resources/welcomeCard.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/cards/welcomeCard.json
similarity index 80%
rename from tests/experimental/101.corebot-bert-bidaf/bot/bots/resources/welcomeCard.json
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/cards/welcomeCard.json
index d9a35548c..cc10cda9f 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/bots/resources/welcomeCard.json
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/cards/welcomeCard.json
@@ -1,46 +1,46 @@
-{
- "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
- "type": "AdaptiveCard",
- "version": "1.0",
- "body": [
- {
- "type": "Image",
- "url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
- "size": "stretch"
- },
- {
- "type": "TextBlock",
- "spacing": "medium",
- "size": "default",
- "weight": "bolder",
- "text": "Welcome to Bot Framework!",
- "wrap": true,
- "maxLines": 0
- },
- {
- "type": "TextBlock",
- "size": "default",
- "isSubtle": "true",
- "text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.",
- "wrap": true,
- "maxLines": 0
- }
- ],
- "actions": [
- {
- "type": "Action.OpenUrl",
- "title": "Get an overview",
- "url": "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
- },
- {
- "type": "Action.OpenUrl",
- "title": "Ask a question",
- "url": "https://stackoverflow.com/questions/tagged/botframework"
- },
- {
- "type": "Action.OpenUrl",
- "title": "Learn how to deploy",
- "url": "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
- }
- ]
+{
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
+ "type": "AdaptiveCard",
+ "version": "1.0",
+ "body": [
+ {
+ "type": "Image",
+ "url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
+ "size": "stretch"
+ },
+ {
+ "type": "TextBlock",
+ "spacing": "medium",
+ "size": "default",
+ "weight": "bolder",
+ "text": "Welcome to Bot Framework!",
+ "wrap": true,
+ "maxLines": 0
+ },
+ {
+ "type": "TextBlock",
+ "size": "default",
+ "isSubtle": "true",
+ "text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.",
+ "wrap": true,
+ "maxLines": 0
+ }
+ ],
+ "actions": [
+ {
+ "type": "Action.OpenUrl",
+ "title": "Get an overview",
+ "url": "https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0"
+ },
+ {
+ "type": "Action.OpenUrl",
+ "title": "Ask a question",
+ "url": "https://stackoverflow.com/questions/tagged/botframework"
+ },
+ {
+ "type": "Action.OpenUrl",
+ "title": "Learn how to deploy",
+ "url": "https://docs.microsoft.com/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
+ }
+ ]
}
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/training_data/FlightBooking.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/cognitiveModels/FlightBooking.json
similarity index 59%
rename from tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/training_data/FlightBooking.json
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/cognitiveModels/FlightBooking.json
index e2b881b21..f0e4b9770 100644
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/training_data/FlightBooking.json
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/cognitiveModels/FlightBooking.json
@@ -1,241 +1,339 @@
-{
- "luis_schema_version": "3.2.0",
- "versionId": "0.1",
- "name": "Airline Reservation",
- "desc": "A LUIS model that uses intent and entities.",
- "culture": "en-us",
- "tokenizerVersion": "1.0.0",
- "intents": [
- {
- "name": "Book flight"
- },
- {
- "name": "Cancel"
- },
- {
- "name": "None"
- }
- ],
- "entities": [],
- "composites": [
- {
- "name": "From",
- "children": [
- "Airport"
- ],
- "roles": []
- },
- {
- "name": "To",
- "children": [
- "Airport"
- ],
- "roles": []
- }
- ],
- "closedLists": [
- {
- "name": "Airport",
- "subLists": [
- {
- "canonicalForm": "Paris",
- "list": [
- "paris"
- ]
- },
- {
- "canonicalForm": "London",
- "list": [
- "london"
- ]
- },
- {
- "canonicalForm": "Berlin",
- "list": [
- "berlin"
- ]
- },
- {
- "canonicalForm": "New York",
- "list": [
- "new york"
- ]
- }
- ],
- "roles": []
- }
- ],
- "patternAnyEntities": [],
- "regex_entities": [],
- "prebuiltEntities": [
- {
- "name": "datetimeV2",
- "roles": []
- }
- ],
- "model_features": [],
- "regex_features": [],
- "patterns": [],
- "utterances": [
- {
- "text": "book flight from london to paris on feb 14th",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 27,
- "endPos": 31
- },
- {
- "entity": "From",
- "startPos": 17,
- "endPos": 22
- }
- ]
- },
- {
- "text": "book flight to berlin on feb 14th",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 15,
- "endPos": 20
- }
- ]
- },
- {
- "text": "book me a flight from london to paris",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "From",
- "startPos": 22,
- "endPos": 27
- },
- {
- "entity": "To",
- "startPos": 32,
- "endPos": 36
- }
- ]
- },
- {
- "text": "bye",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "cancel booking",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "exit",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "I don't want that",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "not this one",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "don't want that",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "flight to paris",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 10,
- "endPos": 14
- }
- ]
- },
- {
- "text": "flight to paris from london on feb 14th",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 10,
- "endPos": 14
- },
- {
- "entity": "From",
- "startPos": 21,
- "endPos": 26
- }
- ]
- },
- {
- "text": "fly from berlin to paris on may 5th",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 19,
- "endPos": 23
- },
- {
- "entity": "From",
- "startPos": 9,
- "endPos": 14
- }
- ]
- },
- {
- "text": "go to paris",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 6,
- "endPos": 10
- }
- ]
- },
- {
- "text": "going from paris to berlin",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 20,
- "endPos": 25
- },
- {
- "entity": "From",
- "startPos": 11,
- "endPos": 15
- }
- ]
- },
- {
- "text": "ignore",
- "intent": "Cancel",
- "entities": []
- },
- {
- "text": "travel to paris",
- "intent": "Book flight",
- "entities": [
- {
- "entity": "To",
- "startPos": 10,
- "endPos": 14
- }
- ]
- }
- ],
- "settings": []
+{
+ "luis_schema_version": "3.2.0",
+ "versionId": "0.1",
+ "name": "FlightBooking",
+ "desc": "Luis Model for CoreBot",
+ "culture": "en-us",
+ "tokenizerVersion": "1.0.0",
+ "intents": [
+ {
+ "name": "BookFlight"
+ },
+ {
+ "name": "Cancel"
+ },
+ {
+ "name": "GetWeather"
+ },
+ {
+ "name": "None"
+ }
+ ],
+ "entities": [],
+ "composites": [
+ {
+ "name": "From",
+ "children": [
+ "Airport"
+ ],
+ "roles": []
+ },
+ {
+ "name": "To",
+ "children": [
+ "Airport"
+ ],
+ "roles": []
+ }
+ ],
+ "closedLists": [
+ {
+ "name": "Airport",
+ "subLists": [
+ {
+ "canonicalForm": "Paris",
+ "list": [
+ "paris",
+ "cdg"
+ ]
+ },
+ {
+ "canonicalForm": "London",
+ "list": [
+ "london",
+ "lhr"
+ ]
+ },
+ {
+ "canonicalForm": "Berlin",
+ "list": [
+ "berlin",
+ "txl"
+ ]
+ },
+ {
+ "canonicalForm": "New York",
+ "list": [
+ "new york",
+ "jfk"
+ ]
+ },
+ {
+ "canonicalForm": "Seattle",
+ "list": [
+ "seattle",
+ "sea"
+ ]
+ }
+ ],
+ "roles": []
+ }
+ ],
+ "patternAnyEntities": [],
+ "regex_entities": [],
+ "prebuiltEntities": [
+ {
+ "name": "datetimeV2",
+ "roles": []
+ }
+ ],
+ "model_features": [],
+ "regex_features": [],
+ "patterns": [],
+ "utterances": [
+ {
+ "text": "book a flight",
+ "intent": "BookFlight",
+ "entities": []
+ },
+ {
+ "text": "book a flight from new york",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 19,
+ "endPos": 26
+ }
+ ]
+ },
+ {
+ "text": "book a flight from seattle",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 19,
+ "endPos": 25
+ }
+ ]
+ },
+ {
+ "text": "book a hotel in new york",
+ "intent": "None",
+ "entities": []
+ },
+ {
+ "text": "book a restaurant",
+ "intent": "None",
+ "entities": []
+ },
+ {
+ "text": "book flight from london to paris on feb 14th",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 17,
+ "endPos": 22
+ },
+ {
+ "entity": "To",
+ "startPos": 27,
+ "endPos": 31
+ }
+ ]
+ },
+ {
+ "text": "book flight to berlin on feb 14th",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 15,
+ "endPos": 20
+ }
+ ]
+ },
+ {
+ "text": "book me a flight from london to paris",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 22,
+ "endPos": 27
+ },
+ {
+ "entity": "To",
+ "startPos": 32,
+ "endPos": 36
+ }
+ ]
+ },
+ {
+ "text": "bye",
+ "intent": "Cancel",
+ "entities": []
+ },
+ {
+ "text": "cancel booking",
+ "intent": "Cancel",
+ "entities": []
+ },
+ {
+ "text": "exit",
+ "intent": "Cancel",
+ "entities": []
+ },
+ {
+ "text": "find an airport near me",
+ "intent": "None",
+ "entities": []
+ },
+ {
+ "text": "flight to paris",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 10,
+ "endPos": 14
+ }
+ ]
+ },
+ {
+ "text": "flight to paris from london on feb 14th",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 10,
+ "endPos": 14
+ },
+ {
+ "entity": "From",
+ "startPos": 21,
+ "endPos": 26
+ }
+ ]
+ },
+ {
+ "text": "fly from berlin to paris on may 5th",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 9,
+ "endPos": 14
+ },
+ {
+ "entity": "To",
+ "startPos": 19,
+ "endPos": 23
+ }
+ ]
+ },
+ {
+ "text": "go to paris",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 6,
+ "endPos": 10
+ }
+ ]
+ },
+ {
+ "text": "going from paris to berlin",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 11,
+ "endPos": 15
+ },
+ {
+ "entity": "To",
+ "startPos": 20,
+ "endPos": 25
+ }
+ ]
+ },
+ {
+ "text": "i'd like to rent a car",
+ "intent": "None",
+ "entities": []
+ },
+ {
+ "text": "ignore",
+ "intent": "Cancel",
+ "entities": []
+ },
+ {
+ "text": "travel from new york to paris",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "From",
+ "startPos": 12,
+ "endPos": 19
+ },
+ {
+ "entity": "To",
+ "startPos": 24,
+ "endPos": 28
+ }
+ ]
+ },
+ {
+ "text": "travel to new york",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 10,
+ "endPos": 17
+ }
+ ]
+ },
+ {
+ "text": "travel to paris",
+ "intent": "BookFlight",
+ "entities": [
+ {
+ "entity": "To",
+ "startPos": 10,
+ "endPos": 14
+ }
+ ]
+ },
+ {
+ "text": "what's the forecast for this friday?",
+ "intent": "GetWeather",
+ "entities": []
+ },
+ {
+ "text": "what's the weather like for tomorrow",
+ "intent": "GetWeather",
+ "entities": []
+ },
+ {
+ "text": "what's the weather like in new york",
+ "intent": "GetWeather",
+ "entities": []
+ },
+ {
+ "text": "what's the weather like?",
+ "intent": "GetWeather",
+ "entities": []
+ },
+ {
+ "text": "winter is coming",
+ "intent": "None",
+ "entities": []
+ }
+ ],
+ "settings": []
}
\ No newline at end of file
diff --git a/tests/teams/scenarios/conversation-update/config.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/config.py
similarity index 55%
rename from tests/teams/scenarios/conversation-update/config.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/config.py
index d66581d4c..46973c345 100644
--- a/tests/teams/scenarios/conversation-update/config.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/config.py
@@ -4,10 +4,13 @@
import os
-
class DefaultConfig:
""" Bot Configuration """
PORT = 3978
APP_ID = os.environ.get("MicrosoftAppId", "")
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
+ LUIS_APP_ID = os.environ.get("LuisAppId", "")
+ LUIS_API_KEY = os.environ.get("LuisAPIKey", "")
+ # LUIS endpoint host name, ie "westus.api.cognitive.microsoft.com"
+ LUIS_API_HOST_NAME = os.environ.get("LuisAPIHostName", "")
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
new file mode 100644
index 000000000..cc1800c0d
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
new file mode 100644
index 000000000..eea65b7c3
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "value": ""
+ },
+ "existingAppServicePlanName": {
+ "value": ""
+ },
+ "existingAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
new file mode 100644
index 000000000..f8f1d1e56
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
@@ -0,0 +1,28 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment group create --resource-group --template-file --parameters @
+---
+
+# parameters-for-template-BotApp-with-rg:
+
+**appServiceName**:(required) The Name of the Bot App Service.
+
+(choose an existingAppServicePlan or create a new AppServicePlan)
+**existingAppServicePlanName**: The name of the App Service Plan.
+**existingAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanName**: The name of the App Service Plan.
+**newAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+# parameters-for-template-AzureBot-with-rg:
+
+**azureBotId**:(required) The globally unique and immutable bot ID.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
new file mode 100644
index 000000000..f7d08b75d
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
@@ -0,0 +1,61 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "defaultValue": "S1",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default)."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": "Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope."
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2021-05-01-preview",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
new file mode 100644
index 000000000..9b1c79ae9
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
@@ -0,0 +1,209 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "existingAppServicePlanName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Name of the existing App Service Plan used to create the Web App for the bot."
+ }
+ },
+ "existingAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the new App Service Plan."
+ }
+ },
+ "newAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"."
+ }
+ }
+ },
+ "variables": {
+ "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlanName')), 'createNewAppServicePlan', parameters('existingAppServicePlanName'))]",
+ "useExistingServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
+ "servicePlanName": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanName'), parameters('newAppServicePlanName'))]",
+ "servicePlanLocation": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanLocation'), parameters('newAppServicePlanLocation'))]"
+ },
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
+ "type": "Microsoft.Web/serverfarms",
+ "condition": "[not(variables('useExistingServicePlan'))]",
+ "name": "[variables('servicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[parameters('newAppServicePlanLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('servicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using an App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "name": "[parameters('appServiceName')]",
+ "location": "[variables('servicePlanLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"
+ ],
+ "properties": {
+ "enabled": true,
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",
+ "reserved": true,
+ "scmSiteAlsoStopped": false,
+ "clientAffinityEnabled": false,
+ "clientCertEnabled": false,
+ "hostNamesDisabled": false,
+ "containerSize": 0,
+ "dailyMemoryTimeQuota": 0,
+ "httpsOnly": false,
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('servicePlanLocation')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f18061813
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
new file mode 100644
index 000000000..f3f07b497
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "appServiceName": {
+ "value": ""
+ },
+ "appServicePlanName": {
+ "value": ""
+ },
+ "appServicePlanLocation": {
+ "value": ""
+ },
+ "appServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
new file mode 100644
index 000000000..d88b160f1
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
@@ -0,0 +1,31 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment sub create --template-file --location --parameters @
+---
+
+# parameters-for-template-BotApp-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**appServiceName**:(required) The location of the App Service Plan.
+**appServicePlanName**:(required) The name of the App Service Plan.
+**appServicePlanLocation**: The location of the App Service Plan. Defaults to use groupLocation.
+**appServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required for MultiTenant and SingleTenant) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+
+# parameters-for-template-AzureBot-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**azureBotId**:(required) The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f79264452
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
@@ -0,0 +1,101 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "type": "string",
+ "defaultValue": "S1",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": ""
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "apiVersion": "2021-03-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
new file mode 100644
index 000000000..b33b21510
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
@@ -0,0 +1,226 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "appServiceName": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "appServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the App Service Plan."
+ }
+ },
+ "appServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "appServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types."
+ }
+ }
+ },
+ "variables": {
+ "appServicePlanName": "[parameters('appServicePlanName')]",
+ "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), parameters('groupLocation'), parameters('appServicePlanLocation'))]",
+ "appServiceName": "[parameters('appServiceName')]",
+ "resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]"
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan",
+ "type": "Microsoft.Web/serverfarms",
+ "name": "[variables('appServicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('resourcesLocation')]",
+ "sku": "[parameters('appServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('appServicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using the new App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
+ ],
+ "name": "[variables('appServiceName')]",
+ "properties": {
+ "name": "[variables('appServiceName')]",
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[variables('appServicePlanName')]",
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ },
+ "webSocketsEnabled": true
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('resourcesLocation')]",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ],
+ "outputs": {}
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/__init__.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/__init__.py
similarity index 92%
rename from tests/experimental/101.corebot-bert-bidaf/bot/dialogs/__init__.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/__init__.py
index d37afdc97..5c3aa9845 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/__init__.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/__init__.py
@@ -1,6 +1,6 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Dialogs module"""
+
from .booking_dialog import BookingDialog
from .cancel_and_help_dialog import CancelAndHelpDialog
from .date_resolver_dialog import DateResolverDialog
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/booking_dialog.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/booking_dialog.py
similarity index 57%
rename from tests/experimental/101.corebot-bert-bidaf/bot/dialogs/booking_dialog.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/booking_dialog.py
index 52b71eb30..a73e95d20 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/booking_dialog.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/booking_dialog.py
@@ -1,23 +1,23 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Flight booking dialog."""
from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
+from botbuilder.schema import InputHints
+
from datatypes_date_time.timex import Timex
+
from .cancel_and_help_dialog import CancelAndHelpDialog
from .date_resolver_dialog import DateResolverDialog
class BookingDialog(CancelAndHelpDialog):
- """Flight booking implementation."""
-
def __init__(self, dialog_id: str = None):
super(BookingDialog, self).__init__(dialog_id or BookingDialog.__name__)
self.add_dialog(TextPrompt(TextPrompt.__name__))
- # self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
+ self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(DateResolverDialog(DateResolverDialog.__name__))
self.add_dialog(
WaterfallDialog(
@@ -26,7 +26,7 @@ def __init__(self, dialog_id: str = None):
self.destination_step,
self.origin_step,
self.travel_date_step,
- # self.confirm_step,
+ self.confirm_step,
self.final_step,
],
)
@@ -37,41 +37,52 @@ def __init__(self, dialog_id: str = None):
async def destination_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
- """Prompt for destination."""
+ """
+ If a destination city has not been provided, prompt for one.
+ :param step_context:
+ :return DialogTurnResult:
+ """
booking_details = step_context.options
if booking_details.destination is None:
+ message_text = "Where would you like to travel to?"
+ prompt_message = MessageFactory.text(
+ message_text, message_text, InputHints.expecting_input
+ )
return await step_context.prompt(
- TextPrompt.__name__,
- PromptOptions(
- prompt=MessageFactory.text("To what city would you like to travel?")
- ),
- ) # pylint: disable=line-too-long,bad-continuation
- else:
- return await step_context.next(booking_details.destination)
+ TextPrompt.__name__, PromptOptions(prompt=prompt_message)
+ )
+ return await step_context.next(booking_details.destination)
async def origin_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
- """Prompt for origin city."""
+ """
+ If an origin city has not been provided, prompt for one.
+ :param step_context:
+ :return DialogTurnResult:
+ """
booking_details = step_context.options
# Capture the response to the previous step's prompt
booking_details.destination = step_context.result
if booking_details.origin is None:
+ message_text = "From what city will you be travelling?"
+ prompt_message = MessageFactory.text(
+ message_text, message_text, InputHints.expecting_input
+ )
return await step_context.prompt(
- TextPrompt.__name__,
- PromptOptions(
- prompt=MessageFactory.text("From what city will you be travelling?")
- ),
- ) # pylint: disable=line-too-long,bad-continuation
- else:
- return await step_context.next(booking_details.origin)
+ TextPrompt.__name__, PromptOptions(prompt=prompt_message)
+ )
+ return await step_context.next(booking_details.origin)
async def travel_date_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
- """Prompt for travel date.
- This will use the DATE_RESOLVER_DIALOG."""
-
+ """
+ If a travel date has not been provided, prompt for one.
+ This will use the DATE_RESOLVER_DIALOG.
+ :param step_context:
+ :return DialogTurnResult:
+ """
booking_details = step_context.options
# Capture the results of the previous step
@@ -81,39 +92,46 @@ async def travel_date_step(
):
return await step_context.begin_dialog(
DateResolverDialog.__name__, booking_details.travel_date
- ) # pylint: disable=line-too-long
- else:
- return await step_context.next(booking_details.travel_date)
+ )
+ return await step_context.next(booking_details.travel_date)
async def confirm_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
- """Confirm the information the user has provided."""
+ """
+ Confirm the information the user has provided.
+ :param step_context:
+ :return DialogTurnResult:
+ """
booking_details = step_context.options
# Capture the results of the previous step
booking_details.travel_date = step_context.result
- msg = (
- f"Please confirm, I have you traveling to: { booking_details.destination }"
- f" from: { booking_details.origin } on: { booking_details.travel_date}."
+ message_text = (
+ f"Please confirm, I have you traveling to: { booking_details.destination } from: "
+ f"{ booking_details.origin } on: { booking_details.travel_date}."
+ )
+ prompt_message = MessageFactory.text(
+ message_text, message_text, InputHints.expecting_input
)
# Offer a YES/NO prompt.
return await step_context.prompt(
- ConfirmPrompt.__name__, PromptOptions(prompt=MessageFactory.text(msg))
+ ConfirmPrompt.__name__, PromptOptions(prompt=prompt_message)
)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
- """Complete the interaction and end the dialog."""
+ """
+ Complete the interaction and end the dialog.
+ :param step_context:
+ :return DialogTurnResult:
+ """
if step_context.result:
booking_details = step_context.options
- booking_details.travel_date = step_context.result
return await step_context.end_dialog(booking_details)
- else:
- return await step_context.end_dialog()
+ return await step_context.end_dialog()
def is_ambiguous(self, timex: str) -> bool:
- """Ensure time is correct."""
timex_property = Timex(timex)
return "definite" not in timex_property.types
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/cancel_and_help_dialog.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/cancel_and_help_dialog.py
similarity index 53%
rename from tests/experimental/101.corebot-bert-bidaf/bot/dialogs/cancel_and_help_dialog.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/cancel_and_help_dialog.py
index 760ecc457..d11f65fd6 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/cancel_and_help_dialog.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/cancel_and_help_dialog.py
@@ -1,27 +1,17 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Handle cancel and help intents."""
+
from botbuilder.dialogs import (
ComponentDialog,
DialogContext,
DialogTurnResult,
DialogTurnStatus,
)
-from botbuilder.schema import ActivityTypes
+from botbuilder.schema import ActivityTypes, InputHints
+from botbuilder.core import MessageFactory
class CancelAndHelpDialog(ComponentDialog):
- """Implementation of handling cancel and help."""
-
- async def on_begin_dialog(
- self, inner_dc: DialogContext, options: object
- ) -> DialogTurnResult:
- result = await self.interrupt(inner_dc)
- if result is not None:
- return result
-
- return await super(CancelAndHelpDialog, self).on_begin_dialog(inner_dc, options)
-
async def on_continue_dialog(self, inner_dc: DialogContext) -> DialogTurnResult:
result = await self.interrupt(inner_dc)
if result is not None:
@@ -30,16 +20,25 @@ async def on_continue_dialog(self, inner_dc: DialogContext) -> DialogTurnResult:
return await super(CancelAndHelpDialog, self).on_continue_dialog(inner_dc)
async def interrupt(self, inner_dc: DialogContext) -> DialogTurnResult:
- """Detect interruptions."""
if inner_dc.context.activity.type == ActivityTypes.message:
text = inner_dc.context.activity.text.lower()
- if text == "help" or text == "?":
- await inner_dc.context.send_activity("Show Help...")
+ help_message_text = "Show Help..."
+ help_message = MessageFactory.text(
+ help_message_text, help_message_text, InputHints.expecting_input
+ )
+
+ if text in ("help", "?"):
+ await inner_dc.context.send_activity(help_message)
return DialogTurnResult(DialogTurnStatus.Waiting)
- if text == "cancel" or text == "quit":
- await inner_dc.context.send_activity("Cancelling")
+ cancel_message_text = "Cancelling"
+ cancel_message = MessageFactory.text(
+ cancel_message_text, cancel_message_text, InputHints.ignoring_input
+ )
+
+ if text in ("cancel", "quit"):
+ await inner_dc.context.send_activity(cancel_message)
return await inner_dc.cancel_all_dialogs()
return None
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/date_resolver_dialog.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/date_resolver_dialog.py
similarity index 60%
rename from tests/experimental/101.corebot-bert-bidaf/bot/dialogs/date_resolver_dialog.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/date_resolver_dialog.py
index bef1a94f3..c6b163f8c 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/date_resolver_dialog.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/date_resolver_dialog.py
@@ -1,6 +1,6 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Handle date/time resolution for booking dialog."""
+
from botbuilder.core import MessageFactory
from botbuilder.dialogs import WaterfallDialog, DialogTurnResult, WaterfallStepContext
from botbuilder.dialogs.prompts import (
@@ -9,13 +9,13 @@
PromptOptions,
DateTimeResolution,
)
+from botbuilder.schema import InputHints
from datatypes_date_time.timex import Timex
+
from .cancel_and_help_dialog import CancelAndHelpDialog
class DateResolverDialog(CancelAndHelpDialog):
- """Resolve the date"""
-
def __init__(self, dialog_id: str = None):
super(DateResolverDialog, self).__init__(
dialog_id or DateResolverDialog.__name__
@@ -37,46 +37,43 @@ def __init__(self, dialog_id: str = None):
async def initial_step(
self, step_context: WaterfallStepContext
) -> DialogTurnResult:
- """Prompt for the date."""
timex = step_context.options
- prompt_msg = "On what date would you like to travel?"
- reprompt_msg = (
- "I'm sorry, for best results, please enter your travel "
- "date including the month, day and year."
+ prompt_msg_text = "On what date would you like to travel?"
+ prompt_msg = MessageFactory.text(
+ prompt_msg_text, prompt_msg_text, InputHints.expecting_input
+ )
+
+ reprompt_msg_text = "I'm sorry, for best results, please enter your travel date " \
+ "including the month, day and year."
+ reprompt_msg = MessageFactory.text(
+ reprompt_msg_text, reprompt_msg_text, InputHints.expecting_input
)
if timex is None:
# We were not given any date at all so prompt the user.
return await step_context.prompt(
DateTimePrompt.__name__,
- PromptOptions( # pylint: disable=bad-continuation
- prompt=MessageFactory.text(prompt_msg),
- retry_prompt=MessageFactory.text(reprompt_msg),
- ),
+ PromptOptions(prompt=prompt_msg, retry_prompt=reprompt_msg),
+ )
+ # We have a Date we just need to check it is unambiguous.
+ if "definite" not in Timex(timex).types:
+ # This is essentially a "reprompt" of the data we were given up front.
+ return await step_context.prompt(
+ DateTimePrompt.__name__, PromptOptions(prompt=reprompt_msg)
)
- else:
- # We have a Date we just need to check it is unambiguous.
- if "definite" in Timex(timex).types:
- # This is essentially a "reprompt" of the data we were given up front.
- return await step_context.prompt(
- DateTimePrompt.__name__, PromptOptions(prompt=reprompt_msg)
- )
- else:
- return await step_context.next(DateTimeResolution(timex=timex))
+
+ return await step_context.next(DateTimeResolution(timex=timex))
async def final_step(self, step_context: WaterfallStepContext):
- """Cleanup - set final return value and end dialog."""
timex = step_context.result[0].timex
return await step_context.end_dialog(timex)
@staticmethod
async def datetime_prompt_validator(prompt_context: PromptValidatorContext) -> bool:
- """ Validate the date provided is in proper form. """
if prompt_context.recognized.succeeded:
timex = prompt_context.recognized.value[0].timex.split("T")[0]
- # TODO: Needs TimexProperty
return "definite" in Timex(timex).types
return False
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/main_dialog.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/main_dialog.py
new file mode 100644
index 000000000..c0e97da76
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/dialogs/main_dialog.py
@@ -0,0 +1,133 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from botbuilder.dialogs import (
+ ComponentDialog,
+ WaterfallDialog,
+ WaterfallStepContext,
+ DialogTurnResult,
+)
+from botbuilder.dialogs.prompts import TextPrompt, PromptOptions
+from botbuilder.core import MessageFactory, TurnContext
+from botbuilder.schema import InputHints
+
+from booking_details import BookingDetails
+from flight_booking_recognizer import FlightBookingRecognizer
+
+from helpers import LuisHelper, Intent
+from .booking_dialog import BookingDialog
+
+
+class MainDialog(ComponentDialog):
+ def __init__(
+ self, luis_recognizer: FlightBookingRecognizer, booking_dialog: BookingDialog
+ ):
+ super(MainDialog, self).__init__(MainDialog.__name__)
+
+ self._luis_recognizer = luis_recognizer
+ self._booking_dialog_id = booking_dialog.id
+
+ self.add_dialog(TextPrompt(TextPrompt.__name__))
+ self.add_dialog(booking_dialog)
+ self.add_dialog(
+ WaterfallDialog(
+ "WFDialog", [self.intro_step, self.act_step, self.final_step]
+ )
+ )
+
+ self.initial_dialog_id = "WFDialog"
+
+ async def intro_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
+ if not self._luis_recognizer.is_configured:
+ await step_context.context.send_activity(
+ MessageFactory.text(
+ "NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and "
+ "'LuisAPIHostName' to the appsettings.json file.",
+ input_hint=InputHints.ignoring_input,
+ )
+ )
+
+ return await step_context.next(None)
+ message_text = (
+ str(step_context.options)
+ if step_context.options
+ else "What can I help you with today?"
+ )
+ prompt_message = MessageFactory.text(
+ message_text, message_text, InputHints.expecting_input
+ )
+
+ return await step_context.prompt(
+ TextPrompt.__name__, PromptOptions(prompt=prompt_message)
+ )
+
+ async def act_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
+ if not self._luis_recognizer.is_configured:
+ # LUIS is not configured, we just run the BookingDialog path with an empty BookingDetailsInstance.
+ return await step_context.begin_dialog(
+ self._booking_dialog_id, BookingDetails()
+ )
+
+ # Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
+ intent, luis_result = await LuisHelper.execute_luis_query(
+ self._luis_recognizer, step_context.context
+ )
+
+ if intent == Intent.BOOK_FLIGHT.value and luis_result:
+ # Show a warning for Origin and Destination if we can't resolve them.
+ await MainDialog._show_warning_for_unsupported_cities(
+ step_context.context, luis_result
+ )
+
+ # Run the BookingDialog giving it whatever details we have from the LUIS call.
+ return await step_context.begin_dialog(self._booking_dialog_id, luis_result)
+
+ if intent == Intent.GET_WEATHER.value:
+ get_weather_text = "TODO: get weather flow here"
+ get_weather_message = MessageFactory.text(
+ get_weather_text, get_weather_text, InputHints.ignoring_input
+ )
+ await step_context.context.send_activity(get_weather_message)
+
+ else:
+ didnt_understand_text = (
+ "Sorry, I didn't get that. Please try asking in a different way"
+ )
+ didnt_understand_message = MessageFactory.text(
+ didnt_understand_text, didnt_understand_text, InputHints.ignoring_input
+ )
+ await step_context.context.send_activity(didnt_understand_message)
+
+ return await step_context.next(None)
+
+ async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
+ # If the child dialog ("BookingDialog") was cancelled or the user failed to confirm,
+ # the Result here will be null.
+ if step_context.result is not None:
+ result = step_context.result
+
+ # Now we have all the booking details call the booking service.
+
+ # If the call to the booking service was successful tell the user.
+ # time_property = Timex(result.travel_date)
+ # travel_date_msg = time_property.to_natural_language(datetime.now())
+ msg_txt = f"I have you booked to {result.destination} from {result.origin} on {result.travel_date}"
+ message = MessageFactory.text(msg_txt, msg_txt, InputHints.ignoring_input)
+ await step_context.context.send_activity(message)
+
+ prompt_message = "What else can I do for you?"
+ return await step_context.replace_dialog(self.id, prompt_message)
+
+ @staticmethod
+ async def _show_warning_for_unsupported_cities(
+ context: TurnContext, luis_result: BookingDetails
+ ) -> None:
+ if luis_result.unsupported_airports:
+ message_text = (
+ f"Sorry but the following airports are not supported:"
+ f" {', '.join(luis_result.unsupported_airports)}"
+ )
+ message = MessageFactory.text(
+ message_text, message_text, InputHints.ignoring_input
+ )
+ await context.send_activity(message)
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/flight_booking_recognizer.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/flight_booking_recognizer.py
new file mode 100644
index 000000000..744e26fc8
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/flight_booking_recognizer.py
@@ -0,0 +1,34 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from botbuilder.ai.luis import LuisApplication, LuisRecognizer
+from botbuilder.core import Recognizer, RecognizerResult, TurnContext
+
+from config import DefaultConfig
+
+
+class FlightBookingRecognizer(Recognizer):
+ def __init__(self, configuration: DefaultConfig):
+ self._recognizer = None
+
+ luis_is_configured = (
+ configuration.LUIS_APP_ID
+ and configuration.LUIS_API_KEY
+ and configuration.LUIS_API_HOST_NAME
+ )
+ if luis_is_configured:
+ luis_application = LuisApplication(
+ configuration.LUIS_APP_ID,
+ configuration.LUIS_API_KEY,
+ "https://" + configuration.LUIS_API_HOST_NAME,
+ )
+
+ self._recognizer = LuisRecognizer(luis_application)
+
+ @property
+ def is_configured(self) -> bool:
+ # Returns true if luis is configured in the appsettings.json and initialized.
+ return self._recognizer is not None
+
+ async def recognize(self, turn_context: TurnContext) -> RecognizerResult:
+ return await self._recognizer.recognize(turn_context)
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/__init__.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/__init__.py
new file mode 100644
index 000000000..39a6dd2b9
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from .luis_helper import Intent, LuisHelper
+from .dialog_helper import DialogHelper
+
+__all__ = [
+ "DialogHelper",
+ "LuisHelper",
+ "Intent"
+]
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/dialog_helper.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/dialog_helper.py
similarity index 81%
rename from tests/experimental/101.corebot-bert-bidaf/bot/helpers/dialog_helper.py
rename to generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/dialog_helper.py
index 56ba5b05f..062271fd8 100644
--- a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/dialog_helper.py
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/dialog_helper.py
@@ -1,18 +1,15 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-"""Utility to run dialogs."""
+
from botbuilder.core import StatePropertyAccessor, TurnContext
from botbuilder.dialogs import Dialog, DialogSet, DialogTurnStatus
class DialogHelper:
- """Dialog Helper implementation."""
-
@staticmethod
async def run_dialog(
dialog: Dialog, turn_context: TurnContext, accessor: StatePropertyAccessor
- ): # pylint: disable=line-too-long
- """Run dialog."""
+ ):
dialog_set = DialogSet(accessor)
dialog_set.add(dialog)
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/luis_helper.py b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/luis_helper.py
new file mode 100644
index 000000000..cc8a18be4
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/luis_helper.py
@@ -0,0 +1,104 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+from enum import Enum
+from typing import Dict
+from botbuilder.ai.luis import LuisRecognizer
+from botbuilder.core import IntentScore, TopIntent, TurnContext
+
+from booking_details import BookingDetails
+
+
+class Intent(Enum):
+ BOOK_FLIGHT = "BookFlight"
+ CANCEL = "Cancel"
+ GET_WEATHER = "GetWeather"
+ NONE_INTENT = "NoneIntent"
+
+
+def top_intent(intents: Dict[Intent, dict]) -> TopIntent:
+ max_intent = Intent.NONE_INTENT
+ max_value = 0.0
+
+ for intent, value in intents:
+ intent_score = IntentScore(value)
+ if intent_score.score > max_value:
+ max_intent, max_value = intent, intent_score.score
+
+ return TopIntent(max_intent, max_value)
+
+
+class LuisHelper:
+ @staticmethod
+ async def execute_luis_query(
+ luis_recognizer: LuisRecognizer, turn_context: TurnContext
+ ) -> (Intent, object):
+ """
+ Returns an object with pre-formatted LUIS results for the bot's dialogs to consume.
+ """
+ result = None
+ intent = None
+
+ try:
+ recognizer_result = await luis_recognizer.recognize(turn_context)
+
+ intent = (
+ sorted(
+ recognizer_result.intents,
+ key=recognizer_result.intents.get,
+ reverse=True,
+ )[:1][0]
+ if recognizer_result.intents
+ else None
+ )
+
+ if intent == Intent.BOOK_FLIGHT.value:
+ result = BookingDetails()
+
+ # We need to get the result from the LUIS JSON which at every level
+ # returns an array.
+ to_entities = recognizer_result.entities.get("$instance", {}).get(
+ "To", []
+ )
+ if len(to_entities) > 0:
+ if recognizer_result.entities.get("To", [{"$instance": {}}])[0][
+ "$instance"
+ ]:
+ result.destination = to_entities[0]["text"].capitalize()
+ else:
+ result.unsupported_airports.append(
+ to_entities[0]["text"].capitalize()
+ )
+
+ from_entities = recognizer_result.entities.get("$instance", {}).get(
+ "From", []
+ )
+ if len(from_entities) > 0:
+ if recognizer_result.entities.get("From", [{"$instance": {}}])[0][
+ "$instance"
+ ]:
+ result.origin = from_entities[0]["text"].capitalize()
+ else:
+ result.unsupported_airports.append(
+ from_entities[0]["text"].capitalize()
+ )
+
+ # This value will be a TIMEX. And we are only interested in a Date so
+ # grab the first result and drop the Time part.
+ # TIMEX is a format that represents DateTime expressions that include
+ # some ambiguity. e.g. missing a Year.
+ date_entities = recognizer_result.entities.get("datetime", [])
+ if date_entities:
+ timex = date_entities[0]["timex"]
+
+ if timex:
+ datetime = timex[0].split("T")[0]
+
+ result.travel_date = datetime
+
+ else:
+ result.travel_date = None
+
+ except Exception as err:
+ print(err)
+
+ return intent, result
diff --git a/generators/app/templates/core/{{cookiecutter.bot_name}}/requirements.txt b/generators/app/templates/core/{{cookiecutter.bot_name}}/requirements.txt
new file mode 100644
index 000000000..26674db81
--- /dev/null
+++ b/generators/app/templates/core/{{cookiecutter.bot_name}}/requirements.txt
@@ -0,0 +1,4 @@
+botbuilder-integration-aiohttp>=4.15.0
+botbuilder-dialogs>=4.15.0
+botbuilder-ai>=4.15.0
+datatypes-date-time>=1.0.0.a2
diff --git a/generators/app/templates/echo/cookiecutter.json b/generators/app/templates/echo/cookiecutter.json
new file mode 100644
index 000000000..4a14b6ade
--- /dev/null
+++ b/generators/app/templates/echo/cookiecutter.json
@@ -0,0 +1,4 @@
+{
+ "bot_name": "my_chat_bot",
+ "bot_description": "Demonstrate the core capabilities of the Microsoft Bot Framework"
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/.pylintrc b/generators/app/templates/echo/{{cookiecutter.bot_name}}/.pylintrc
new file mode 100644
index 000000000..1baee5edb
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/.pylintrc
@@ -0,0 +1,497 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-whitelist=
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Specify a configuration file.
+#rcfile=
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=missing-docstring,
+ too-few-public-methods,
+ bad-continuation,
+ no-self-use,
+ duplicate-code,
+ broad-except
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit
+
+
+[LOGGING]
+
+# Format style used to check logging format string. `old` means using %
+# formatting, while `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package..
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+ XXX,
+ TODO
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+ _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Maximum number of characters on a single line.
+max-line-length=120
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# List of optional constructs for which whitespace checking is disabled. `dict-
+# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
+# `trailing-comma` allows a space between comma and closing bracket: (a, ).
+# `empty-line` allows space-only lines.
+no-space-check=trailing-comma,
+ dict-separator
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+ bar,
+ baz,
+ toto,
+ tutu,
+ tata
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+ j,
+ k,
+ ex,
+ Run,
+ _
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[STRING]
+
+# This flag controls whether the implicit-str-concat-in-sequence should
+# generate a warning on implicit string concatenation in sequences defined over
+# several lines.
+check-str-concat-over-line-jumps=no
+
+
+[IMPORTS]
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=optparse,tkinter.tix
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled).
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled).
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement.
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+ Exception
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/README.md b/generators/app/templates/echo/{{cookiecutter.bot_name}}/README.md
new file mode 100644
index 000000000..cc26d0f4d
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/README.md
@@ -0,0 +1,42 @@
+# {{cookiecutter.bot_name}}
+
+{{cookiecutter.bot_description}}
+
+This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
+
+## Prerequisites
+
+This sample **requires** prerequisites in order to run.
+
+### Install Python 3.6
+
+## Running the sample
+- Run `pip install -r requirements.txt` to install all dependencies
+- Run `python app.py`
+
+
+## Testing the bot using Bot Framework Emulator
+
+[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
+
+- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
+
+### Connect to the bot using Bot Framework Emulator
+
+- Launch Bot Framework Emulator
+- Enter a Bot URL of `http://localhost:3978/api/messages`
+
+
+## Further reading
+
+- [Bot Framework Documentation](https://docs.botframework.com)
+- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
+- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
+- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
+- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
+- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
+- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
+- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
+- [Azure Portal](https://portal.azure.com)
+- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
+- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/__init__.py b/generators/app/templates/echo/{{cookiecutter.bot_name}}/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/teams/scenarios/link-unfurling/app.py b/generators/app/templates/echo/{{cookiecutter.bot_name}}/app.py
similarity index 83%
rename from tests/teams/scenarios/link-unfurling/app.py
rename to generators/app/templates/echo/{{cookiecutter.bot_name}}/app.py
index 709bffd0f..6a21648d0 100644
--- a/tests/teams/scenarios/link-unfurling/app.py
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/app.py
@@ -1,21 +1,21 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-import json
import sys
+import traceback
from datetime import datetime
from aiohttp import web
from aiohttp.web import Request, Response, json_response
-
from botbuilder.core import (
BotFrameworkAdapterSettings,
TurnContext,
BotFrameworkAdapter,
)
-
+from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.schema import Activity, ActivityTypes
-from bots import LinkUnfurlingBot
+
+from bot import MyBot
from config import DefaultConfig
CONFIG = DefaultConfig()
@@ -25,12 +25,14 @@
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
ADAPTER = BotFrameworkAdapter(SETTINGS)
+
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
+ traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
@@ -48,14 +50,15 @@ async def on_error(context: TurnContext, error: Exception):
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
-
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
+
ADAPTER.on_turn_error = on_error
# Create the Bot
-BOT = LinkUnfurlingBot()
+BOT = MyBot()
+
# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
@@ -68,15 +71,13 @@ async def messages(req: Request) -> Response:
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
- try:
- response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- if response:
- return json_response(data=response.body, status=response.status)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-APP = web.Application()
+ response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
+ if response:
+ return json_response(data=response.body, status=response.status)
+ return Response(status=201)
+
+
+APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__":
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/bot.py b/generators/app/templates/echo/{{cookiecutter.bot_name}}/bot.py
new file mode 100644
index 000000000..ca7562263
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/bot.py
@@ -0,0 +1,21 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from botbuilder.core import ActivityHandler, TurnContext
+from botbuilder.schema import ChannelAccount
+
+
+class MyBot(ActivityHandler):
+ # See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
+
+ async def on_message_activity(self, turn_context: TurnContext):
+ await turn_context.send_activity(f"You said '{ turn_context.activity.text }'")
+
+ async def on_members_added_activity(
+ self,
+ members_added: ChannelAccount,
+ turn_context: TurnContext
+ ):
+ for member_added in members_added:
+ if member_added.id != turn_context.activity.recipient.id:
+ await turn_context.send_activity("Hello and welcome!")
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/config.py b/generators/app/templates/echo/{{cookiecutter.bot_name}}/config.py
similarity index 96%
rename from tests/teams/scenarios/action-based-messaging-extension-fetch-task/config.py
rename to generators/app/templates/echo/{{cookiecutter.bot_name}}/config.py
index 6b5116fba..51e0988ed 100644
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/config.py
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/config.py
@@ -1,13 +1,12 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
+#!/usr/bin/env python3
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+import os
+
+class DefaultConfig:
+ """ Bot Configuration """
+
+ PORT = 3978
+ APP_ID = os.environ.get("MicrosoftAppId", "")
+ APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
new file mode 100644
index 000000000..cc1800c0d
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
new file mode 100644
index 000000000..eea65b7c3
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "value": ""
+ },
+ "existingAppServicePlanName": {
+ "value": ""
+ },
+ "existingAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
new file mode 100644
index 000000000..f8f1d1e56
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
@@ -0,0 +1,28 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment group create --resource-group --template-file --parameters @
+---
+
+# parameters-for-template-BotApp-with-rg:
+
+**appServiceName**:(required) The Name of the Bot App Service.
+
+(choose an existingAppServicePlan or create a new AppServicePlan)
+**existingAppServicePlanName**: The name of the App Service Plan.
+**existingAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanName**: The name of the App Service Plan.
+**newAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+# parameters-for-template-AzureBot-with-rg:
+
+**azureBotId**:(required) The globally unique and immutable bot ID.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
new file mode 100644
index 000000000..f7d08b75d
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
@@ -0,0 +1,61 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "defaultValue": "S1",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default)."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": "Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope."
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2021-05-01-preview",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
new file mode 100644
index 000000000..9b1c79ae9
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
@@ -0,0 +1,209 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "existingAppServicePlanName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Name of the existing App Service Plan used to create the Web App for the bot."
+ }
+ },
+ "existingAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the new App Service Plan."
+ }
+ },
+ "newAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"."
+ }
+ }
+ },
+ "variables": {
+ "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlanName')), 'createNewAppServicePlan', parameters('existingAppServicePlanName'))]",
+ "useExistingServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
+ "servicePlanName": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanName'), parameters('newAppServicePlanName'))]",
+ "servicePlanLocation": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanLocation'), parameters('newAppServicePlanLocation'))]"
+ },
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
+ "type": "Microsoft.Web/serverfarms",
+ "condition": "[not(variables('useExistingServicePlan'))]",
+ "name": "[variables('servicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[parameters('newAppServicePlanLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('servicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using an App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "name": "[parameters('appServiceName')]",
+ "location": "[variables('servicePlanLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"
+ ],
+ "properties": {
+ "enabled": true,
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",
+ "reserved": true,
+ "scmSiteAlsoStopped": false,
+ "clientAffinityEnabled": false,
+ "clientCertEnabled": false,
+ "hostNamesDisabled": false,
+ "containerSize": 0,
+ "dailyMemoryTimeQuota": 0,
+ "httpsOnly": false,
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('servicePlanLocation')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f18061813
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
new file mode 100644
index 000000000..f3f07b497
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "appServiceName": {
+ "value": ""
+ },
+ "appServicePlanName": {
+ "value": ""
+ },
+ "appServicePlanLocation": {
+ "value": ""
+ },
+ "appServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
new file mode 100644
index 000000000..d88b160f1
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
@@ -0,0 +1,31 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment sub create --template-file --location --parameters @
+---
+
+# parameters-for-template-BotApp-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**appServiceName**:(required) The location of the App Service Plan.
+**appServicePlanName**:(required) The name of the App Service Plan.
+**appServicePlanLocation**: The location of the App Service Plan. Defaults to use groupLocation.
+**appServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required for MultiTenant and SingleTenant) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+
+# parameters-for-template-AzureBot-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**azureBotId**:(required) The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f79264452
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
@@ -0,0 +1,101 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "type": "string",
+ "defaultValue": "S1",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": ""
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "apiVersion": "2021-03-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
new file mode 100644
index 000000000..b33b21510
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
@@ -0,0 +1,226 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "appServiceName": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "appServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the App Service Plan."
+ }
+ },
+ "appServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "appServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types."
+ }
+ }
+ },
+ "variables": {
+ "appServicePlanName": "[parameters('appServicePlanName')]",
+ "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), parameters('groupLocation'), parameters('appServicePlanLocation'))]",
+ "appServiceName": "[parameters('appServiceName')]",
+ "resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]"
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan",
+ "type": "Microsoft.Web/serverfarms",
+ "name": "[variables('appServicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('resourcesLocation')]",
+ "sku": "[parameters('appServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('appServicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using the new App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
+ ],
+ "name": "[variables('appServiceName')]",
+ "properties": {
+ "name": "[variables('appServiceName')]",
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[variables('appServicePlanName')]",
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ },
+ "webSocketsEnabled": true
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('resourcesLocation')]",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ],
+ "outputs": {}
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/echo/{{cookiecutter.bot_name}}/requirements.txt b/generators/app/templates/echo/{{cookiecutter.bot_name}}/requirements.txt
new file mode 100644
index 000000000..2b2e3ab57
--- /dev/null
+++ b/generators/app/templates/echo/{{cookiecutter.bot_name}}/requirements.txt
@@ -0,0 +1 @@
+botbuilder-integration-aiohttp>=4.15.0
diff --git a/generators/app/templates/empty/cookiecutter.json b/generators/app/templates/empty/cookiecutter.json
new file mode 100644
index 000000000..4a14b6ade
--- /dev/null
+++ b/generators/app/templates/empty/cookiecutter.json
@@ -0,0 +1,4 @@
+{
+ "bot_name": "my_chat_bot",
+ "bot_description": "Demonstrate the core capabilities of the Microsoft Bot Framework"
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/.pylintrc b/generators/app/templates/empty/{{cookiecutter.bot_name}}/.pylintrc
new file mode 100644
index 000000000..1baee5edb
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/.pylintrc
@@ -0,0 +1,497 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-whitelist=
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Specify a configuration file.
+#rcfile=
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=missing-docstring,
+ too-few-public-methods,
+ bad-continuation,
+ no-self-use,
+ duplicate-code,
+ broad-except
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit
+
+
+[LOGGING]
+
+# Format style used to check logging format string. `old` means using %
+# formatting, while `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package..
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+ XXX,
+ TODO
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+ _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Maximum number of characters on a single line.
+max-line-length=120
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# List of optional constructs for which whitespace checking is disabled. `dict-
+# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
+# `trailing-comma` allows a space between comma and closing bracket: (a, ).
+# `empty-line` allows space-only lines.
+no-space-check=trailing-comma,
+ dict-separator
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+ bar,
+ baz,
+ toto,
+ tutu,
+ tata
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+ j,
+ k,
+ ex,
+ Run,
+ _
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[STRING]
+
+# This flag controls whether the implicit-str-concat-in-sequence should
+# generate a warning on implicit string concatenation in sequences defined over
+# several lines.
+check-str-concat-over-line-jumps=no
+
+
+[IMPORTS]
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=optparse,tkinter.tix
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled).
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled).
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement.
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+ Exception
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/README.md b/generators/app/templates/empty/{{cookiecutter.bot_name}}/README.md
new file mode 100644
index 000000000..cc26d0f4d
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/README.md
@@ -0,0 +1,42 @@
+# {{cookiecutter.bot_name}}
+
+{{cookiecutter.bot_description}}
+
+This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
+
+## Prerequisites
+
+This sample **requires** prerequisites in order to run.
+
+### Install Python 3.6
+
+## Running the sample
+- Run `pip install -r requirements.txt` to install all dependencies
+- Run `python app.py`
+
+
+## Testing the bot using Bot Framework Emulator
+
+[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
+
+- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
+
+### Connect to the bot using Bot Framework Emulator
+
+- Launch Bot Framework Emulator
+- Enter a Bot URL of `http://localhost:3978/api/messages`
+
+
+## Further reading
+
+- [Bot Framework Documentation](https://docs.botframework.com)
+- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
+- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
+- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
+- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
+- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
+- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
+- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
+- [Azure Portal](https://portal.azure.com)
+- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
+- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/__init__.py b/generators/app/templates/empty/{{cookiecutter.bot_name}}/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/app.py b/generators/app/templates/empty/{{cookiecutter.bot_name}}/app.py
similarity index 80%
rename from tests/teams/scenarios/action-based-messaging-extension-fetch-task/app.py
rename to generators/app/templates/empty/{{cookiecutter.bot_name}}/app.py
index 103c5f31a..a6aa1bcd1 100644
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/app.py
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/app.py
@@ -1,93 +1,87 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import json
-import sys
-from datetime import datetime
-
-from aiohttp import web
-from aiohttp.web import Request, Response, json_response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-from bots import ActionBasedMessagingExtensionFetchTaskBot
-from config import DefaultConfig
-
-CONFIG = DefaultConfig()
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error(context: TurnContext, error: Exception):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = on_error
-
-# Create the Bot
-BOT = ActionBasedMessagingExtensionFetchTaskBot()
-
-
-# Listen for incoming requests on /api/messages
-async def messages(req: Request) -> Response:
- # Main bot message handler.
- if "application/json" in req.headers["Content-Type"]:
- body = await req.json()
- else:
- return Response(status=415)
-
- activity = Activity().deserialize(body)
- auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
-
- try:
- invoke_response = await ADAPTER.process_activity(
- activity, auth_header, BOT.on_turn
- )
- if invoke_response:
- return json_response(
- data=invoke_response.body, status=invoke_response.status
- )
- return Response(status=201)
- except PermissionError:
- return Response(status=401)
- except Exception:
- return Response(status=500)
-
-
-APP = web.Application()
-APP.router.add_post("/api/messages", messages)
-
-if __name__ == "__main__":
- try:
- web.run_app(APP, host="localhost", port=CONFIG.PORT)
- except Exception as error:
- raise error
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+import sys
+import traceback
+from datetime import datetime
+
+from aiohttp import web
+from aiohttp.web import Request, Response, json_response
+from botbuilder.core import (
+ BotFrameworkAdapterSettings,
+ TurnContext,
+ BotFrameworkAdapter,
+)
+from botbuilder.core.integration import aiohttp_error_middleware
+from botbuilder.schema import Activity, ActivityTypes
+
+from bot import MyBot
+from config import DefaultConfig
+
+CONFIG = DefaultConfig()
+
+# Create adapter.
+# See https://aka.ms/about-bot-adapter to learn more about how bots work.
+SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
+ADAPTER = BotFrameworkAdapter(SETTINGS)
+
+
+# Catch-all for errors.
+async def on_error(context: TurnContext, error: Exception):
+ # This check writes out errors to console log .vs. app insights.
+ # NOTE: In production environment, you should consider logging this to Azure
+ # application insights.
+ print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
+ traceback.print_exc()
+
+ # Send a message to the user
+ await context.send_activity("The bot encountered an error or bug.")
+ await context.send_activity(
+ "To continue to run this bot, please fix the bot source code."
+ )
+ # Send a trace activity if we're talking to the Bot Framework Emulator
+ if context.activity.channel_id == "emulator":
+ # Create a trace activity that contains the error object
+ trace_activity = Activity(
+ label="TurnError",
+ name="on_turn_error Trace",
+ timestamp=datetime.utcnow(),
+ type=ActivityTypes.trace,
+ value=f"{error}",
+ value_type="https://www.botframework.com/schemas/error",
+ )
+ # Send a trace activity, which will be displayed in Bot Framework Emulator
+ await context.send_activity(trace_activity)
+
+
+ADAPTER.on_turn_error = on_error
+
+# Create the main dialog
+BOT = MyBot()
+
+
+# Listen for incoming requests on /api/messages
+async def messages(req: Request) -> Response:
+ # Main bot message handler.
+ if "application/json" in req.headers["Content-Type"]:
+ body = await req.json()
+ else:
+ return Response(status=415)
+
+ activity = Activity().deserialize(body)
+ auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
+
+ response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
+ if response:
+ return json_response(data=response.body, status=response.status)
+ return Response(status=201)
+
+
+APP = web.Application(middlewares=[aiohttp_error_middleware])
+APP.router.add_post("/api/messages", messages)
+
+if __name__ == "__main__":
+ try:
+ web.run_app(APP, host="localhost", port=CONFIG.PORT)
+ except Exception as error:
+ raise error
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/bot.py b/generators/app/templates/empty/{{cookiecutter.bot_name}}/bot.py
new file mode 100644
index 000000000..598d68408
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/bot.py
@@ -0,0 +1,16 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+from botbuilder.core import ActivityHandler, TurnContext
+from botbuilder.schema import ChannelAccount
+
+
+class MyBot(ActivityHandler):
+ async def on_members_added_activity(
+ self,
+ members_added: ChannelAccount,
+ turn_context: TurnContext
+ ):
+ for member_added in members_added:
+ if member_added.id != turn_context.activity.recipient.id:
+ await turn_context.send_activity("Hello world!")
diff --git a/tests/teams/scenarios/create-thread-in-channel/config.py b/generators/app/templates/empty/{{cookiecutter.bot_name}}/config.py
similarity index 96%
rename from tests/teams/scenarios/create-thread-in-channel/config.py
rename to generators/app/templates/empty/{{cookiecutter.bot_name}}/config.py
index 6b5116fba..51e0988ed 100644
--- a/tests/teams/scenarios/create-thread-in-channel/config.py
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/config.py
@@ -1,13 +1,12 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
+#!/usr/bin/env python3
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License.
+
+import os
+
+class DefaultConfig:
+ """ Bot Configuration """
+
+ PORT = 3978
+ APP_ID = os.environ.get("MicrosoftAppId", "")
+ APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
new file mode 100644
index 000000000..cc1800c0d
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
new file mode 100644
index 000000000..eea65b7c3
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "value": ""
+ },
+ "existingAppServicePlanName": {
+ "value": ""
+ },
+ "existingAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanLocation": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
new file mode 100644
index 000000000..f8f1d1e56
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md
@@ -0,0 +1,28 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment group create --resource-group --template-file --parameters @
+---
+
+# parameters-for-template-BotApp-with-rg:
+
+**appServiceName**:(required) The Name of the Bot App Service.
+
+(choose an existingAppServicePlan or create a new AppServicePlan)
+**existingAppServicePlanName**: The name of the App Service Plan.
+**existingAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanName**: The name of the App Service Plan.
+**newAppServicePlanLocation**: The location of the App Service Plan.
+**newAppServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+# parameters-for-template-AzureBot-with-rg:
+
+**azureBotId**:(required) The globally unique and immutable bot ID.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
new file mode 100644
index 000000000..f7d08b75d
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json
@@ -0,0 +1,61 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "defaultValue": "S1",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default)."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": "Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope."
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2021-05-01-preview",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
new file mode 100644
index 000000000..9b1c79ae9
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json
@@ -0,0 +1,209 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appServiceName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "existingAppServicePlanName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Name of the existing App Service Plan used to create the Web App for the bot."
+ }
+ },
+ "existingAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the new App Service Plan."
+ }
+ },
+ "newAppServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"."
+ }
+ }
+ },
+ "variables": {
+ "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlanName')), 'createNewAppServicePlan', parameters('existingAppServicePlanName'))]",
+ "useExistingServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
+ "servicePlanName": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanName'), parameters('newAppServicePlanName'))]",
+ "servicePlanLocation": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanLocation'), parameters('newAppServicePlanLocation'))]"
+ },
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
+ "type": "Microsoft.Web/serverfarms",
+ "condition": "[not(variables('useExistingServicePlan'))]",
+ "name": "[variables('servicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[parameters('newAppServicePlanLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('servicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using an App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "name": "[parameters('appServiceName')]",
+ "location": "[variables('servicePlanLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"
+ ],
+ "properties": {
+ "enabled": true,
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",
+ "reserved": true,
+ "scmSiteAlsoStopped": false,
+ "clientAffinityEnabled": false,
+ "clientCertEnabled": false,
+ "hostNamesDisabled": false,
+ "containerSize": 0,
+ "dailyMemoryTimeQuota": 0,
+ "httpsOnly": false,
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('servicePlanLocation')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f18061813
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "azureBotId": {
+ "value": ""
+ },
+ "azureBotSku": {
+ "value": "S1"
+ },
+ "azureBotRegion": {
+ "value": "global"
+ },
+ "botEndpoint": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
new file mode 100644
index 000000000..f3f07b497
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json
@@ -0,0 +1,36 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "value": ""
+ },
+ "groupLocation": {
+ "value": ""
+ },
+ "appServiceName": {
+ "value": ""
+ },
+ "appServicePlanName": {
+ "value": ""
+ },
+ "appServicePlanLocation": {
+ "value": ""
+ },
+ "appServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
new file mode 100644
index 000000000..d88b160f1
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md
@@ -0,0 +1,31 @@
+Need deploy BotAppService before AzureBot
+---
+az login
+az deployment sub create --template-file --location --parameters @
+---
+
+# parameters-for-template-BotApp-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**appServiceName**:(required) The location of the App Service Plan.
+**appServicePlanName**:(required) The name of the App Service Plan.
+**appServicePlanLocation**: The location of the App Service Plan. Defaults to use groupLocation.
+**appServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
+**appSecret**:(required for MultiTenant and SingleTenant) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
+
+
+# parameters-for-template-AzureBot-new-rg:
+
+**groupName**:(required) Specifies the name of the new Resource Group.
+**groupLocation**:(required) Specifies the location of the new Resource Group.
+
+**azureBotId**:(required) The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable.
+**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
+**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
+**botEndpoint**: Use to handle client messages, Such as https://.azurewebsites.net/api/messages.
+
+**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
new file mode 100644
index 000000000..f79264452
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json
@@ -0,0 +1,101 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "azureBotId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID."
+ }
+ },
+ "azureBotSku": {
+ "type": "string",
+ "defaultValue": "S1",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "azureBotRegion": {
+ "type": "string",
+ "defaultValue": "global",
+ "metadata": {
+ "description": ""
+ }
+ },
+ "botEndpoint": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ }
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "apiVersion": "2021-03-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('azureBotId')]",
+ "location": "[parameters('azureBotRegion')]",
+ "kind": "azurebot",
+ "sku": {
+ "name": "[parameters('azureBotSku')]"
+ },
+ "properties": {
+ "name": "[parameters('azureBotId')]",
+ "displayName": "[parameters('azureBotId')]",
+ "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
+ "endpoint": "[parameters('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "luisAppIds": [],
+ "schemaTransformationVersion": "1.3",
+ "isCmekEnabled": false,
+ "isIsolated": false
+ }
+ }
+ ]
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
new file mode 100644
index 000000000..b33b21510
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json
@@ -0,0 +1,226 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "groupLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "appServiceName": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique name of the Web App."
+ }
+ },
+ "appServicePlanName": {
+ "type": "string",
+ "metadata": {
+ "description": "The name of the App Service Plan."
+ }
+ },
+ "appServicePlanLocation": {
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "appServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types."
+ }
+ }
+ },
+ "variables": {
+ "appServicePlanName": "[parameters('appServicePlanName')]",
+ "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), parameters('groupLocation'), parameters('appServicePlanLocation'))]",
+ "appServiceName": "[parameters('appServiceName')]",
+ "resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]"
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[parameters('groupLocation')]",
+ "properties": {}
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan",
+ "type": "Microsoft.Web/serverfarms",
+ "name": "[variables('appServicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('resourcesLocation')]",
+ "sku": "[parameters('appServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('appServicePlanName')]",
+ "perSiteScaling": false,
+ "reserved": true,
+ "targetWorkerCount": 0,
+ "targetWorkerSizeId": 0
+ }
+ },
+ {
+ "comments": "Create a Web App using the new App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app,linux",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
+ ],
+ "name": "[variables('appServiceName')]",
+ "properties": {
+ "name": "[variables('appServiceName')]",
+ "hostNameSslStates": [
+ {
+ "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Standard"
+ },
+ {
+ "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]",
+ "sslState": "Disabled",
+ "hostType": "Repository"
+ }
+ ],
+ "serverFarmId": "[variables('appServicePlanName')]",
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
+ "value": "true"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ },
+ "webSocketsEnabled": true
+ }
+ }
+ },
+ {
+ "type": "Microsoft.Web/sites/config",
+ "apiVersion": "2016-08-01",
+ "name": "[concat(parameters('appServiceName'), '/web')]",
+ "location": "[variables('resourcesLocation')]",
+ "dependsOn": [
+ "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', parameters('appServiceName'))]"
+ ],
+ "properties": {
+ "numberOfWorkers": 1,
+ "defaultDocuments": [
+ "Default.htm",
+ "Default.html",
+ "Default.asp",
+ "index.htm",
+ "index.html",
+ "iisstart.htm",
+ "default.aspx",
+ "index.php",
+ "hostingstart.html"
+ ],
+ "netFrameworkVersion": "v4.0",
+ "phpVersion": "",
+ "pythonVersion": "",
+ "nodeVersion": "",
+ "linuxFxVersion": "PYTHON|3.7",
+ "requestTracingEnabled": false,
+ "remoteDebuggingEnabled": false,
+ "remoteDebuggingVersion": "VS2017",
+ "httpLoggingEnabled": true,
+ "logsDirectorySizeLimit": 35,
+ "detailedErrorLoggingEnabled": false,
+ "publishingUsername": "[concat('$', parameters('appServiceName'))]",
+ "scmType": "None",
+ "use32BitWorkerProcess": true,
+ "webSocketsEnabled": false,
+ "alwaysOn": false,
+ "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
+ "managedPipelineMode": "Integrated",
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }
+ ],
+ "winAuthAdminState": 0,
+ "winAuthTenantState": 0,
+ "customAppPoolIdentityAdminState": false,
+ "customAppPoolIdentityTenantState": false,
+ "loadBalancing": "LeastRequests",
+ "routingRules": [],
+ "experiments": {
+ "rampUpRules": []
+ },
+ "autoHealEnabled": false,
+ "vnetName": "",
+ "minTlsVersion": "1.2",
+ "ftpsState": "AllAllowed",
+ "reservedInstanceCount": 0
+ }
+ }
+ ],
+ "outputs": {}
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/generators/app/templates/empty/{{cookiecutter.bot_name}}/requirements.txt b/generators/app/templates/empty/{{cookiecutter.bot_name}}/requirements.txt
new file mode 100644
index 000000000..2b2e3ab57
--- /dev/null
+++ b/generators/app/templates/empty/{{cookiecutter.bot_name}}/requirements.txt
@@ -0,0 +1 @@
+botbuilder-integration-aiohttp>=4.15.0
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/about.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/about.py
index de861b694..a7f0c2b88 100644
--- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/about.py
+++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-adapters-slack"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py
index ad32e6e6c..26fc80b41 100644
--- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py
+++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py
@@ -103,7 +103,9 @@ async def update_activity(self, context: TurnContext, activity: Activity):
message = SlackHelper.activity_to_slack(activity)
results = await self.slack_client.chat_update(
- ts=message.ts, channel=message.channel, text=message.text,
+ ts=message.ts,
+ channel=message.channel,
+ text=message.text,
)
if results.status_code / 100 != 2:
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_client.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_client.py
index 70dbc0eaa..dd19e9b2a 100644
--- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_client.py
+++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_client.py
@@ -409,7 +409,9 @@ async def post_message(self, message: SlackMessage) -> SlackResponse:
if message.blocks:
request_content["blocks"] = json.dumps(message.blocks)
- session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30),)
+ session = aiohttp.ClientSession(
+ timeout=aiohttp.ClientTimeout(total=30),
+ )
http_verb = "POST"
api_url = POST_EPHEMERAL_MESSAGE_URL if message.ephemeral else POST_MESSAGE_URL
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_helper.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_helper.py
index 273771f1c..80d30d275 100644
--- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_helper.py
+++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_helper.py
@@ -56,7 +56,9 @@ def activity_to_slack(activity: Activity) -> SlackMessage:
message.blocks = att.content
else:
new_attachment = Attachment(
- author_name=att.name, thumb_url=att.thumbnail_url, text="",
+ author_name=att.name,
+ thumb_url=att.thumbnail_url,
+ text="",
)
attachments.append(new_attachment)
diff --git a/libraries/botbuilder-adapters-slack/requirements.txt b/libraries/botbuilder-adapters-slack/requirements.txt
index ab2b8e8c5..9e8688e38 100644
--- a/libraries/botbuilder-adapters-slack/requirements.txt
+++ b/libraries/botbuilder-adapters-slack/requirements.txt
@@ -1,4 +1,4 @@
aiohttp==3.7.4
pyslack
-botbuilder-core==4.14.0
+botbuilder-core==4.15.0
slackclient
\ No newline at end of file
diff --git a/libraries/botbuilder-adapters-slack/setup.py b/libraries/botbuilder-adapters-slack/setup.py
index b334ce772..41ac5dc42 100644
--- a/libraries/botbuilder-adapters-slack/setup.py
+++ b/libraries/botbuilder-adapters-slack/setup.py
@@ -5,9 +5,9 @@
from setuptools import setup
REQUIRES = [
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botbuilder-core==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botbuilder-core==4.15.0",
"pyslack",
"slackclient",
]
diff --git a/libraries/botbuilder-ai/botbuilder/ai/about.py b/libraries/botbuilder-ai/botbuilder/ai/about.py
index 7a0b00daf..c6bda926b 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/about.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-ai"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
index 8eef3e4dc..9c09af773 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
@@ -262,7 +262,9 @@ async def _recognize_internal(
if turn_context.activity.type != ActivityTypes.message:
return None
- utterance: str = turn_context.activity.text if turn_context.activity is not None else None
+ utterance: str = (
+ turn_context.activity.text if turn_context.activity is not None else None
+ )
recognizer_result: RecognizerResult = None
if luis_prediction_options:
diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v2.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v2.py
index c1ed5ed6b..34d246d99 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v2.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v2.py
@@ -44,7 +44,9 @@ def __init__(
async def recognizer_internal(self, turn_context: TurnContext):
- utterance: str = turn_context.activity.text if turn_context.activity is not None else None
+ utterance: str = (
+ turn_context.activity.text if turn_context.activity is not None else None
+ )
luis_result: LuisResult = self._runtime.prediction.resolve(
self._application.application_id,
utterance,
diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py
index 61fdfef6f..09cb8594e 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py
@@ -55,7 +55,9 @@ def __init__(
async def recognizer_internal(self, turn_context: TurnContext):
recognizer_result: RecognizerResult = None
- utterance: str = turn_context.activity.text if turn_context.activity is not None else None
+ utterance: str = (
+ turn_context.activity.text if turn_context.activity is not None else None
+ )
url = self._build_url()
body = self._build_request(utterance)
diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py
index 9f620be34..c3dc2f106 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py
@@ -303,10 +303,14 @@ def recognizer_result_as_dict(
) -> Dict[str, object]:
# an internal method that returns a dict for json serialization.
- intents: Dict[str, Dict[str, float]] = {
- name: LuisUtil.intent_score_as_dict(intent_score)
- for name, intent_score in recognizer_result.intents.items()
- } if recognizer_result.intents is not None else None
+ intents: Dict[str, Dict[str, float]] = (
+ {
+ name: LuisUtil.intent_score_as_dict(intent_score)
+ for name, intent_score in recognizer_result.intents.items()
+ }
+ if recognizer_result.intents is not None
+ else None
+ )
dictionary: Dict[str, object] = {
"text": recognizer_result.text,
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_record.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_record.py
index 9b9b1b4ce..1a268b2d7 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_record.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_record.py
@@ -5,7 +5,7 @@
class FeedbackRecord(Model):
- """ Active learning feedback record. """
+ """Active learning feedback record."""
_attribute_map = {
"user_id": {"key": "userId", "type": "str"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_records.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_records.py
index 97f9dc776..c9bf67ae8 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_records.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/feedback_records.py
@@ -5,7 +5,7 @@
class FeedbackRecords(Model):
- """ Active learning feedback records. """
+ """Active learning feedback records."""
_attribute_map = {"records": {"key": "records", "type": "[FeedbackRecord]"}}
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py
index dd4104185..473fc2bc2 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py
@@ -5,7 +5,7 @@
class GenerateAnswerRequestBody(Model):
- """ Question used as the payload body for QnA Maker's Generate Answer API. """
+ """Question used as the payload body for QnA Maker's Generate Answer API."""
_attribute_map = {
"question": {"key": "question", "type": "str"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py
index 60f52f18a..8f93fff76 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py
@@ -5,7 +5,7 @@
class Metadata(Model):
- """ Metadata associated with the answer. """
+ """Metadata associated with the answer."""
_attribute_map = {
"name": {"key": "name", "type": "str"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/prompt.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/prompt.py
index b0a2fe7fe..6a347ce14 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/prompt.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/prompt.py
@@ -5,7 +5,7 @@
class Prompt(Model):
- """ Prompt Object. """
+ """Prompt Object."""
_attribute_map = {
"display_order": {"key": "displayOrder", "type": "int"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py
index f585e5c26..16bcc7f8e 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py
@@ -11,7 +11,7 @@
class QnAMakerTraceInfo:
- """ Represents all the trace info that we collect from the QnAMaker Middleware. """
+ """Represents all the trace info that we collect from the QnAMaker Middleware."""
def __init__(
self,
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_result.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_result.py
index a0b1c2c0a..c0ca858f1 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_result.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_result.py
@@ -5,7 +5,7 @@
class QueryResult(Model):
- """ Represents an individual result from a knowledge base query. """
+ """Represents an individual result from a knowledge base query."""
_attribute_map = {
"questions": {"key": "questions", "type": "[str]"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py
index f3c413618..450f47067 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py
@@ -7,7 +7,7 @@
class QueryResults(Model):
- """ Contains answers for a user query. """
+ """Contains answers for a user query."""
_attribute_map = {
"answers": {"key": "answers", "type": "[QueryResult]"},
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/ranker_types.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/ranker_types.py
index a3f0463ca..55d6799aa 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/ranker_types.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/ranker_types.py
@@ -4,7 +4,7 @@
class RankerTypes:
- """ Default Ranker Behaviour. i.e. Ranking based on Questions and Answer. """
+ """Default Ranker Behaviour. i.e. Ranking based on Questions and Answer."""
DEFAULT = "Default"
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/models/train_request_body.py b/libraries/botbuilder-ai/botbuilder/ai/qna/models/train_request_body.py
index 252f8ae81..29b2a0258 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/models/train_request_body.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/models/train_request_body.py
@@ -5,7 +5,7 @@
class TrainRequestBody(Model):
- """ Class the models the request body that is sent as feedback to the Train API. """
+ """Class the models the request body that is sent as feedback to the Train API."""
_attribute_map = {
"feedback_records": {"key": "feedbackRecords", "type": "[FeedbackRecord]"}
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
index f7583c571..18a77521a 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
@@ -55,9 +55,9 @@ def __init__(
instance_timeout = ClientTimeout(total=opt.timeout / 1000)
self._http_client = http_client or ClientSession(timeout=instance_timeout)
- self.telemetry_client: Union[
- BotTelemetryClient, NullTelemetryClient
- ] = telemetry_client or NullTelemetryClient()
+ self.telemetry_client: Union[BotTelemetryClient, NullTelemetryClient] = (
+ telemetry_client or NullTelemetryClient()
+ )
self.log_personal_information = log_personal_information or False
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/active_learning_utils.py b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/active_learning_utils.py
index 625d77dbc..5a63666a8 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/active_learning_utils.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/active_learning_utils.py
@@ -13,7 +13,7 @@
class ActiveLearningUtils:
- """ Active learning helper class """
+ """Active learning helper class"""
@staticmethod
def get_low_score_variation(
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/http_request_utils.py b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/http_request_utils.py
index 977f839de..baca83ae0 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/http_request_utils.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/http_request_utils.py
@@ -14,7 +14,7 @@
class HttpRequestUtils:
- """ HTTP request utils class.
+ """HTTP request utils class.
Parameters:
-----------
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/qna_card_builder.py b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/qna_card_builder.py
index 0ff28caaf..fe70b6c73 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/qna_card_builder.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/qna_card_builder.py
@@ -62,7 +62,9 @@ def get_qna_prompts_card(result: QueryResult, card_no_match_text: str) -> Activi
# Add all prompts
button_list = [
CardAction(
- value=prompt.display_text, type="imBack", title=prompt.display_text,
+ value=prompt.display_text,
+ type="imBack",
+ title=prompt.display_text,
)
for prompt in result.context.prompts
]
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py
index ec2586bd4..31c1ee441 100644
--- a/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py
+++ b/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py
@@ -11,7 +11,7 @@
class TrainUtils:
- """ Class for Train API, used in active learning to add suggestions to the knowledge base """
+ """Class for Train API, used in active learning to add suggestions to the knowledge base"""
def __init__(self, endpoint: QnAMakerEndpoint, http_client: ClientSession):
"""
diff --git a/libraries/botbuilder-ai/requirements.txt b/libraries/botbuilder-ai/requirements.txt
index 824ffc6e6..9a7bdf70b 100644
--- a/libraries/botbuilder-ai/requirements.txt
+++ b/libraries/botbuilder-ai/requirements.txt
@@ -1,6 +1,6 @@
-msrest==0.6.10
-botbuilder-schema==4.14.0
-botbuilder-core==4.14.0
-requests==2.23.0
+msrest==0.6.*
+botbuilder-schema==4.15.0
+botbuilder-core==4.15.0
+requests==2.27.1
aiounittest==1.3.0
-azure-cognitiveservices-language-luis==0.2.0
\ No newline at end of file
+azure-cognitiveservices-language-luis==0.7.0
\ No newline at end of file
diff --git a/libraries/botbuilder-ai/setup.py b/libraries/botbuilder-ai/setup.py
index 64bb0297a..05d83a1d2 100644
--- a/libraries/botbuilder-ai/setup.py
+++ b/libraries/botbuilder-ai/setup.py
@@ -6,8 +6,8 @@
REQUIRES = [
"azure-cognitiveservices-language-luis==0.2.0",
- "botbuilder-schema==4.14.0",
- "botbuilder-core==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botbuilder-core==4.15.0",
"aiohttp>=3.6.2,<3.8.0",
]
diff --git a/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py b/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py
index 33a45ff59..5c55b9951 100644
--- a/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py
+++ b/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py
@@ -126,7 +126,9 @@ async def test_single_intent_simply_entity(self):
async def test_null_utterance(self):
utterance: str = None
- response_path: str = "SingleIntent_SimplyEntity.json" # The path is irrelevant in this case
+ response_path: str = (
+ "SingleIntent_SimplyEntity.json" # The path is irrelevant in this case
+ )
_, result = await LuisRecognizerTest._get_recognizer_result(
utterance, response_path
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/about.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/about.py
index 727bc4347..cf0b5e087 100644
--- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/about.py
+++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/about.py
@@ -6,7 +6,7 @@
__title__ = "botbuilder-applicationinsights"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/bot_telemetry_processor.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/bot_telemetry_processor.py
index fa15a3225..bc6c2918a 100644
--- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/bot_telemetry_processor.py
+++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/bot_telemetry_processor.py
@@ -12,10 +12,14 @@ class BotTelemetryProcessor(TelemetryProcessor):
"""Application Insights Telemetry Processor for Bot"""
def __init__(self, processors: List[TelemetryProcessor] = None):
- self._processors: List[TelemetryProcessor] = [
- DjangoTelemetryProcessor(),
- FlaskTelemetryProcessor(),
- ] if processors is None else processors
+ self._processors: List[TelemetryProcessor] = (
+ [
+ DjangoTelemetryProcessor(),
+ FlaskTelemetryProcessor(),
+ ]
+ if processors is None
+ else processors
+ )
def can_process(self) -> bool:
for processor in self._processors:
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_middleware.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_middleware.py
index b125c8997..8003074c9 100644
--- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_middleware.py
+++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_middleware.py
@@ -10,7 +10,7 @@
def retrieve_flask_body():
- """ retrieve_flask_body
+ """retrieve_flask_body
Retrieve the POST body text from temporary cache.
The POST body corresponds with the thread id and should resides in
cache just for lifetime of request.
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py
index f03588c82..dfe451e3f 100644
--- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py
+++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py
@@ -31,7 +31,7 @@ def get_request_body(self) -> str: # pylint: disable=inconsistent-return-statem
raise NotImplementedError()
def __call__(self, data, context) -> bool:
- """ Traditional Web user and session ID's don't apply for Bots. This processor
+ """Traditional Web user and session ID's don't apply for Bots. This processor
replaces the identifiers to be consistent with Bot Framework's notion of
user and session id's.
diff --git a/libraries/botbuilder-applicationinsights/requirements.txt b/libraries/botbuilder-applicationinsights/requirements.txt
index 8cf713ca2..13d71acfd 100644
--- a/libraries/botbuilder-applicationinsights/requirements.txt
+++ b/libraries/botbuilder-applicationinsights/requirements.txt
@@ -1,3 +1,3 @@
-msrest==0.6.10
-botbuilder-core==4.14.0
+msrest==0.6.*
+botbuilder-core==4.15.0
aiounittest==1.3.0
\ No newline at end of file
diff --git a/libraries/botbuilder-applicationinsights/setup.py b/libraries/botbuilder-applicationinsights/setup.py
index 6b5d8ebdd..78f9afeb3 100644
--- a/libraries/botbuilder-applicationinsights/setup.py
+++ b/libraries/botbuilder-applicationinsights/setup.py
@@ -6,13 +6,13 @@
REQUIRES = [
"applicationinsights==0.11.9",
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botbuilder-core==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botbuilder-core==4.15.0",
]
TESTS_REQUIRES = [
"aiounittest==1.3.0",
- "django==2.2.6", # For samples
+ "django==3.2.16", # For samples
"djangorestframework==3.10.3", # For samples
"flask==1.1.1", # For samples
]
diff --git a/libraries/botbuilder-azure/botbuilder/azure/about.py b/libraries/botbuilder-azure/botbuilder/azure/about.py
index b84412e7f..142cc9770 100644
--- a/libraries/botbuilder-azure/botbuilder/azure/about.py
+++ b/libraries/botbuilder-azure/botbuilder/azure/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-azure"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-azure/setup.py b/libraries/botbuilder-azure/setup.py
index 3ba356fab..0b9806867 100644
--- a/libraries/botbuilder-azure/setup.py
+++ b/libraries/botbuilder-azure/setup.py
@@ -8,8 +8,8 @@
"azure-cosmos==3.2.0",
"azure-storage-blob==12.7.0",
"azure-storage-queue==12.1.5",
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
"jsonpickle>=1.2,<1.5",
]
TEST_REQUIRES = ["aiounittest==1.3.0"]
diff --git a/libraries/botbuilder-core/botbuilder/core/about.py b/libraries/botbuilder-core/botbuilder/core/about.py
index 9ee11acd1..77319082e 100644
--- a/libraries/botbuilder-core/botbuilder/core/about.py
+++ b/libraries/botbuilder-core/botbuilder/core/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-core"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py
index 6488a2726..18c0e2962 100644
--- a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py
+++ b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py
@@ -311,10 +311,18 @@ def create_conversation_reference(
channel_id="test",
service_url="https://test.com",
conversation=ConversationAccount(
- is_group=False, conversation_type=name, id=name,
+ is_group=False,
+ conversation_type=name,
+ id=name,
+ ),
+ user=ChannelAccount(
+ id=user.lower(),
+ name=user.lower(),
+ ),
+ bot=ChannelAccount(
+ id=bot.lower(),
+ name=bot.lower(),
),
- user=ChannelAccount(id=user.lower(), name=user.lower(),),
- bot=ChannelAccount(id=bot.lower(), name=bot.lower(),),
)
def add_user_token(
@@ -657,7 +665,9 @@ async def wait_for_activity():
return TestFlow(await test_flow_previous(), self.adapter)
async def assert_no_reply(
- self, description=None, timeout=None, # pylint: disable=unused-argument
+ self,
+ description=None,
+ timeout=None, # pylint: disable=unused-argument
) -> "TestFlow":
"""
Generates an assertion if the bot responds when no response is expected.
diff --git a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py
index 63ef5fdc3..1e1b7bddb 100644
--- a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py
+++ b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py
@@ -400,7 +400,8 @@ async def create_conversation(
if resource_response.activity_id
else str(uuid.uuid4()),
conversation=ConversationAccount(
- id=resource_response.id, tenant_id=parameters.tenant_id,
+ id=resource_response.id,
+ tenant_id=parameters.tenant_id,
),
channel_data=parameters.channel_data,
recipient=parameters.bot,
@@ -512,7 +513,8 @@ async def process_activity_with_identity(
if invoke_response is None:
return InvokeResponse(status=int(HTTPStatus.NOT_IMPLEMENTED))
return InvokeResponse(
- status=invoke_response.value.status, body=invoke_response.value.body,
+ status=invoke_response.value.status,
+ body=invoke_response.value.body,
)
return None
@@ -1295,7 +1297,9 @@ def key_for_connector_client(service_url: str, app_id: str, scope: str):
return f"{service_url if service_url else ''}:{app_id if app_id else ''}:{scope if scope else ''}"
async def _create_token_api_client(
- self, context: TurnContext, oauth_app_credentials: AppCredentials = None,
+ self,
+ context: TurnContext,
+ oauth_app_credentials: AppCredentials = None,
) -> TokenApiClient:
if (
not self._is_emulating_oauth_cards
diff --git a/libraries/botbuilder-core/botbuilder/core/channel_service_handler.py b/libraries/botbuilder-core/botbuilder/core/channel_service_handler.py
index 9ed7104df..8de4da56d 100644
--- a/libraries/botbuilder-core/botbuilder/core/channel_service_handler.py
+++ b/libraries/botbuilder-core/botbuilder/core/channel_service_handler.py
@@ -150,7 +150,9 @@ async def handle_upload_attachment(
)
async def on_get_conversations(
- self, claims_identity: ClaimsIdentity, continuation_token: str = "",
+ self,
+ claims_identity: ClaimsIdentity,
+ continuation_token: str = "",
) -> ConversationsResult:
"""
get_conversations() API for Skill
@@ -175,7 +177,9 @@ async def on_get_conversations(
raise BotActionNotImplementedError()
async def on_create_conversation(
- self, claims_identity: ClaimsIdentity, parameters: ConversationParameters,
+ self,
+ claims_identity: ClaimsIdentity,
+ parameters: ConversationParameters,
) -> ConversationResourceResponse:
"""
create_conversation() API for Skill
@@ -209,7 +213,10 @@ async def on_create_conversation(
raise BotActionNotImplementedError()
async def on_send_to_conversation(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity: Activity,
) -> ResourceResponse:
"""
send_to_conversation() API for Skill
@@ -318,7 +325,10 @@ async def on_reply_to_activity(
raise BotActionNotImplementedError()
async def on_delete_activity(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity_id: str,
):
"""
delete_activity() API for Skill.
@@ -336,7 +346,9 @@ async def on_delete_activity(
raise BotActionNotImplementedError()
async def on_get_conversation_members(
- self, claims_identity: ClaimsIdentity, conversation_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
) -> List[ChannelAccount]:
"""
get_conversation_members() API for Skill.
@@ -353,7 +365,10 @@ async def on_get_conversation_members(
raise BotActionNotImplementedError()
async def on_get_conversation_member(
- self, claims_identity: ClaimsIdentity, conversation_id: str, member_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ member_id: str,
) -> ChannelAccount:
"""
get_conversation_member() API for Skill.
@@ -407,7 +422,10 @@ async def on_get_conversation_paged_members(
raise BotActionNotImplementedError()
async def on_delete_conversation_member(
- self, claims_identity: ClaimsIdentity, conversation_id: str, member_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ member_id: str,
):
"""
delete_conversation_member() API for Skill.
@@ -427,7 +445,10 @@ async def on_delete_conversation_member(
raise BotActionNotImplementedError()
async def on_get_activity_members(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity_id: str,
) -> List[ChannelAccount]:
"""
get_activity_members() API for Skill.
diff --git a/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py b/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
index 53a6af025..6b1301f1e 100644
--- a/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
+++ b/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py
@@ -89,8 +89,10 @@ async def send_activities(
activity.conversation.id, activity.reply_to_id, activity
)
else:
- response = await connector_client.conversations.send_to_conversation(
- activity.conversation.id, activity
+ response = (
+ await connector_client.conversations.send_to_conversation(
+ activity.conversation.id, activity
+ )
)
response = response or ResourceResponse(activity.id or "")
@@ -140,7 +142,9 @@ async def delete_activity(
)
async def continue_conversation( # pylint: disable=arguments-differ
- self, reference: ConversationReference, callback: Callable,
+ self,
+ reference: ConversationReference,
+ callback: Callable,
):
"""
Sends a proactive message to a conversation.
@@ -190,8 +194,10 @@ async def process_proactive(
)
# Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.)
- user_token_client = await self.bot_framework_authentication.create_user_token_client(
- claims_identity
+ user_token_client = (
+ await self.bot_framework_authentication.create_user_token_client(
+ claims_identity
+ )
)
# Create a turn context and run the pipeline.
@@ -263,8 +269,10 @@ async def process_activity(
# Create a UserTokenClient instance for the application to use.
# (For example, it would be used in a sign-in prompt.)
- user_token_client = await self.bot_framework_authentication.create_user_token_client(
- authenticate_request_result.claims_identity
+ user_token_client = (
+ await self.bot_framework_authentication.create_user_token_client(
+ authenticate_request_result.claims_identity
+ )
)
# Create a turn context and run the pipeline.
diff --git a/libraries/botbuilder-core/botbuilder/core/conversation_state.py b/libraries/botbuilder-core/botbuilder/core/conversation_state.py
index 174ca0883..2a8e2fd34 100644
--- a/libraries/botbuilder-core/botbuilder/core/conversation_state.py
+++ b/libraries/botbuilder-core/botbuilder/core/conversation_state.py
@@ -58,7 +58,7 @@ def get_storage_key(self, turn_context: TurnContext) -> object:
return storage_key
def __raise_type_error(self, err: str = "NoneType found while expecting value"):
- """ Raise type error exception
+ """Raise type error exception
:raises: :class:`TypeError`
"""
raise TypeError(err)
diff --git a/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py b/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py
index f2ef2676f..37131b0e4 100644
--- a/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py
+++ b/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py
@@ -13,9 +13,9 @@ def __init__(
attached_sessions: Dict[str, ConversationReference] = None,
):
self.opened_sessions: Dict[str, ConversationReference] = opened_sessions or {}
- self.attached_sessions: Dict[
- str, ConversationReference
- ] = attached_sessions or {}
+ self.attached_sessions: Dict[str, ConversationReference] = (
+ attached_sessions or {}
+ )
DEFAULT_INSPECTION_SESSIONS_BY_STATUS = InspectionSessionsByStatus()
diff --git a/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service.py b/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service.py
index c4e8b3b2f..71447a1c4 100644
--- a/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service.py
+++ b/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service.py
@@ -127,7 +127,8 @@ async def get_conversation(request: Request):
@routes.get(base_url + "/v3/conversations/{conversation_id}/members")
async def get_conversation_members(request: Request):
result = await handler.handle_get_conversation_members(
- request.headers.get("Authorization"), request.match_info["conversation_id"],
+ request.headers.get("Authorization"),
+ request.match_info["conversation_id"],
)
return get_serialized_response(result)
@@ -145,7 +146,8 @@ async def get_conversation_member(request: Request):
async def get_conversation_paged_members(request: Request):
# TODO: continuation token? page size?
result = await handler.handle_get_conversation_paged_members(
- request.headers.get("Authorization"), request.match_info["conversation_id"],
+ request.headers.get("Authorization"),
+ request.match_info["conversation_id"],
)
return get_serialized_response(result)
diff --git a/libraries/botbuilder-core/botbuilder/core/serializer_helper.py b/libraries/botbuilder-core/botbuilder/core/serializer_helper.py
index 766cd6291..3716913f5 100644
--- a/libraries/botbuilder-core/botbuilder/core/serializer_helper.py
+++ b/libraries/botbuilder-core/botbuilder/core/serializer_helper.py
@@ -1,6 +1,6 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-
+from copy import copy
from inspect import getmembers
from typing import Type
from enum import Enum
@@ -25,6 +25,9 @@
def deserializer_helper(msrest_cls: Type[Model], dict_to_deserialize: dict) -> Model:
deserializer = Deserializer(DEPENDICIES_DICT)
+ _clean_data_for_serialization(
+ deserializer.dependencies[msrest_cls.__name__], dict_to_deserialize
+ )
return deserializer(msrest_cls.__name__, dict_to_deserialize)
@@ -35,3 +38,21 @@ def serializer_helper(object_to_serialize: Model) -> dict:
serializer = Serializer(DEPENDICIES_DICT)
# pylint: disable=protected-access
return serializer._serialize(object_to_serialize)
+
+
+def _clean_data_for_serialization(msrest_cls: Type[Model], dict_to_deserialize: dict):
+ # pylint: disable=protected-access
+ # Clean channel response of empty strings for expected objects.
+ if not isinstance(dict_to_deserialize, dict):
+ return
+ serialization_model = copy(msrest_cls._attribute_map)
+ for key, value in msrest_cls._attribute_map.items():
+ if key != value["key"]:
+ serialization_model[value["key"]] = value
+ for prop, prop_value in dict_to_deserialize.items():
+ if (
+ prop in serialization_model
+ and serialization_model[prop]["type"] in DEPENDICIES_DICT
+ and not prop_value
+ ):
+ dict_to_deserialize[prop] = None
diff --git a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py
index 80b353b4f..557fd56a2 100644
--- a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py
+++ b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py
@@ -60,7 +60,8 @@ async def on_turn(
def start_interval(context: TurnContext, delay, period):
async def aux():
typing_activity = Activity(
- type=ActivityTypes.typing, relates_to=context.activity.relates_to,
+ type=ActivityTypes.typing,
+ relates_to=context.activity.relates_to,
)
conversation_reference = TurnContext.get_conversation_reference(
diff --git a/libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py b/libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py
index ff58f2e02..dcd31a8c6 100644
--- a/libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py
+++ b/libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py
@@ -49,7 +49,10 @@ def __init__( # pylint: disable=super-init-not-called
self._logger = logger
async def on_send_to_conversation(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity: Activity,
) -> ResourceResponse:
"""
send_to_conversation() API for Skill
@@ -76,7 +79,10 @@ async def on_send_to_conversation(
:return:
"""
return await self._process_activity(
- claims_identity, conversation_id, None, activity,
+ claims_identity,
+ conversation_id,
+ None,
+ activity,
)
async def on_reply_to_activity(
@@ -113,7 +119,10 @@ async def on_reply_to_activity(
:return:
"""
return await self._process_activity(
- claims_identity, conversation_id, activity_id, activity,
+ claims_identity,
+ conversation_id,
+ activity_id,
+ activity,
)
async def on_delete_activity(
@@ -257,8 +266,10 @@ async def _get_skill_conversation_reference(
) -> SkillConversationReference:
# Get the SkillsConversationReference
try:
- skill_conversation_reference = await self._conversation_id_factory.get_skill_conversation_reference(
- conversation_id
+ skill_conversation_reference = (
+ await self._conversation_id_factory.get_skill_conversation_reference(
+ conversation_id
+ )
)
except (NotImplementedError, AttributeError):
if self._logger:
@@ -273,13 +284,22 @@ async def _get_skill_conversation_reference(
# or a ConversationReference (the old way, but still here for compatibility). If a
# ConversationReference is returned, build a new SkillConversationReference to simplify
# the remainder of this method.
- conversation_reference_result = await self._conversation_id_factory.get_conversation_reference(
- conversation_id
- )
- skill_conversation_reference: SkillConversationReference = SkillConversationReference(
- conversation_reference=conversation_reference_result,
- oauth_scope=self._get_oauth_scope(),
+ conversation_reference_result = (
+ await self._conversation_id_factory.get_conversation_reference(
+ conversation_id
+ )
)
+ if isinstance(conversation_reference_result, SkillConversationReference):
+ skill_conversation_reference: SkillConversationReference = (
+ conversation_reference_result
+ )
+ else:
+ skill_conversation_reference: SkillConversationReference = (
+ SkillConversationReference(
+ conversation_reference=conversation_reference_result,
+ oauth_scope=self._get_oauth_scope(),
+ )
+ )
if not skill_conversation_reference:
raise KeyError("SkillConversationReference not found")
diff --git a/libraries/botbuilder-core/botbuilder/core/skills/cloud_skill_handler.py b/libraries/botbuilder-core/botbuilder/core/skills/cloud_skill_handler.py
index 4ebba8c67..71572fada 100644
--- a/libraries/botbuilder-core/botbuilder/core/skills/cloud_skill_handler.py
+++ b/libraries/botbuilder-core/botbuilder/core/skills/cloud_skill_handler.py
@@ -41,7 +41,10 @@ def __init__(
)
async def on_send_to_conversation(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity: Activity,
) -> ResourceResponse:
"""
send_to_conversation() API for Skill
@@ -68,7 +71,9 @@ async def on_send_to_conversation(
:return:
"""
return await self._inner.on_send_to_conversation(
- claims_identity, conversation_id, activity,
+ claims_identity,
+ conversation_id,
+ activity,
)
async def on_reply_to_activity(
@@ -105,7 +110,10 @@ async def on_reply_to_activity(
:return:
"""
return await self._inner.on_reply_to_activity(
- claims_identity, conversation_id, activity_id, activity,
+ claims_identity,
+ conversation_id,
+ activity_id,
+ activity,
)
async def on_delete_activity(
diff --git a/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py b/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py
index a67d4b567..476ce2849 100644
--- a/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py
+++ b/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py
@@ -66,7 +66,10 @@ def aux_func():
)
async def on_send_to_conversation(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity: Activity,
) -> ResourceResponse:
"""
send_to_conversation() API for Skill
@@ -93,7 +96,9 @@ async def on_send_to_conversation(
:return:
"""
return await self._inner.on_send_to_conversation(
- claims_identity, conversation_id, activity,
+ claims_identity,
+ conversation_id,
+ activity,
)
async def on_reply_to_activity(
@@ -130,7 +135,10 @@ async def on_reply_to_activity(
:return:
"""
return await self._inner.on_reply_to_activity(
- claims_identity, conversation_id, activity_id, activity,
+ claims_identity,
+ conversation_id,
+ activity_id,
+ activity,
)
async def on_delete_activity(
diff --git a/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py b/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py
index 9d80e63e6..251eb2a90 100644
--- a/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py
+++ b/libraries/botbuilder-core/botbuilder/core/streaming/streaming_http_client.py
@@ -29,8 +29,7 @@ def __init__(
self._body = None
def body(self) -> bytes:
- """Return the whole body as bytes in memory.
- """
+ """Return the whole body as bytes in memory."""
if not self._body:
return bytes([])
return self._body
diff --git a/libraries/botbuilder-core/botbuilder/core/streaming/streaming_request_handler.py b/libraries/botbuilder-core/botbuilder/core/streaming/streaming_request_handler.py
index 66f36c110..12b748ab2 100644
--- a/libraries/botbuilder-core/botbuilder/core/streaming/streaming_request_handler.py
+++ b/libraries/botbuilder-core/botbuilder/core/streaming/streaming_request_handler.py
@@ -139,8 +139,10 @@ async def process_request(
activity.attachments = stream_attachments
# Now that the request has been converted into an activity we can send it to the adapter.
- adapter_response = await self._activity_processor.process_streaming_activity(
- activity, self._bot.on_turn
+ adapter_response = (
+ await self._activity_processor.process_streaming_activity(
+ activity, self._bot.on_turn
+ )
)
# Now we convert the invokeResponse returned by the adapter into a StreamingResponse we can send back
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py
index 8c4400fba..2e5774cc2 100644
--- a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py
+++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py
@@ -120,7 +120,8 @@ async def on_invoke_activity(self, turn_context: TurnContext) -> InvokeResponse:
await self.on_teams_messaging_extension_fetch_task(
turn_context,
deserializer_helper(
- MessagingExtensionAction, turn_context.activity.value,
+ MessagingExtensionAction,
+ turn_context.activity.value,
),
)
)
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py
index fc5c40943..c2a84a43a 100644
--- a/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py
+++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py
@@ -100,7 +100,8 @@ async def get_team_members(
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_members(
- connector_client, turn_context.activity.conversation.id,
+ connector_client,
+ turn_context.activity.conversation.id,
)
@staticmethod
@@ -130,7 +131,10 @@ async def get_paged_team_members(
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_paged_members(
- connector_client, team_id, continuation_token, page_size,
+ connector_client,
+ team_id,
+ continuation_token,
+ page_size,
)
@staticmethod
@@ -253,7 +257,8 @@ async def get_teams_connector_client(
connector_client = await TeamsInfo._get_connector_client(turn_context)
return TeamsConnectorClient(
- connector_client.config.credentials, turn_context.activity.service_url,
+ connector_client.config.credentials,
+ turn_context.activity.service_url,
)
@staticmethod
@@ -310,8 +315,10 @@ async def _get_paged_members(
"TeamsInfo._get_paged_members.conversation_id: cannot be empty."
)
- return await connector_client.conversations.get_teams_conversation_paged_members(
- conversation_id, page_size, continuation_token
+ return (
+ await connector_client.conversations.get_teams_conversation_paged_members(
+ conversation_id, page_size, continuation_token
+ )
)
@staticmethod
@@ -327,8 +334,10 @@ async def _get_member(
if not member_id:
raise TypeError("TeamsInfo._get_member.member_id: cannot be empty.")
- member: TeamsChannelAccount = await connector_client.conversations.get_conversation_member(
- conversation_id, member_id
+ member: TeamsChannelAccount = (
+ await connector_client.conversations.get_conversation_member(
+ conversation_id, member_id
+ )
)
return TeamsChannelAccount().deserialize(
diff --git a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py
index 33fcd6681..7f65d95d5 100644
--- a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py
+++ b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py
@@ -2,6 +2,8 @@
# Licensed under the MIT License.
"""Middleware Component for logging Activity messages."""
from typing import Awaitable, Callable, List, Dict
+from jsonpickle import encode
+
from botbuilder.schema import Activity, ConversationReference, ActivityTypes
from botbuilder.schema.teams import TeamsChannelData, TeamInfo
from botframework.connector import Channels
@@ -33,7 +35,7 @@ def telemetry_client(self) -> BotTelemetryClient:
@property
def log_personal_information(self) -> bool:
- """ Gets a value indicating whether determines whether to log personal
+ """Gets a value indicating whether determines whether to log personal
information that came from the user."""
return self._log_personal_information
@@ -217,10 +219,10 @@ async def fill_send_event_properties(
# Use the LogPersonalInformation flag to toggle logging PII data, text and user name are common examples
if self.log_personal_information:
- if activity.attachments and activity.attachments.strip():
- properties[
- TelemetryConstants.ATTACHMENTS_PROPERTY
- ] = activity.attachments
+ if activity.attachments and len(activity.attachments) > 0:
+ properties[TelemetryConstants.ATTACHMENTS_PROPERTY] = encode(
+ activity.attachments
+ )
if activity.from_property.name and activity.from_property.name.strip():
properties[
TelemetryConstants.FROM_NAME_PROPERTY
@@ -297,13 +299,16 @@ async def fill_delete_event_properties(
@staticmethod
def __populate_additional_channel_properties(
- activity: Activity, properties: dict,
+ activity: Activity,
+ properties: dict,
):
if activity.channel_id == Channels.ms_teams:
- teams_channel_data: TeamsChannelData = activity.channel_data
+ teams_channel_data: TeamsChannelData = TeamsChannelData().deserialize(
+ activity.channel_data
+ )
properties["TeamsTenantId"] = (
- teams_channel_data.tenant
+ teams_channel_data.tenant.id
if teams_channel_data and teams_channel_data.tenant
else ""
)
diff --git a/libraries/botbuilder-core/botbuilder/core/transcript_logger.py b/libraries/botbuilder-core/botbuilder/core/transcript_logger.py
index bfd838f24..e9536c1b6 100644
--- a/libraries/botbuilder-core/botbuilder/core/transcript_logger.py
+++ b/libraries/botbuilder-core/botbuilder/core/transcript_logger.py
@@ -150,7 +150,7 @@ async def log_activity(self, transcript: Queue, activity: Activity) -> None:
class TranscriptStore(TranscriptLogger):
- """ Transcript storage for conversations."""
+ """Transcript storage for conversations."""
@abstractmethod
async def get_transcript_activities(
diff --git a/libraries/botbuilder-core/requirements.txt b/libraries/botbuilder-core/requirements.txt
index 3a7947f70..b87a22a74 100644
--- a/libraries/botbuilder-core/requirements.txt
+++ b/libraries/botbuilder-core/requirements.txt
@@ -1,8 +1,8 @@
-msrest==0.6.10
-botframework-connector==4.14.0
-botbuilder-schema==4.14.0
-botframework-streaming==4.14.0
-requests==2.23.0
-PyJWT==1.5.3
+msrest==0.6.*
+botframework-connector==4.15.0
+botbuilder-schema==4.15.0
+botframework-streaming==4.15.0
+requests==2.27.1
+PyJWT==2.4.0
cryptography==3.3.2
aiounittest==1.3.0
\ No newline at end of file
diff --git a/libraries/botbuilder-core/setup.py b/libraries/botbuilder-core/setup.py
index 18abee638..a9b9b9fd0 100644
--- a/libraries/botbuilder-core/setup.py
+++ b/libraries/botbuilder-core/setup.py
@@ -4,11 +4,11 @@
import os
from setuptools import setup
-VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
REQUIRES = [
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botframework-streaming==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botframework-streaming==4.15.0",
"jsonpickle>=1.2,<1.5",
]
diff --git a/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py b/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py
index 62b954bbd..7b5dea414 100644
--- a/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py
+++ b/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py
@@ -30,12 +30,14 @@ async def test_skill_conversation_id_factory_happy_path(self):
conversation_reference = self._build_conversation_reference()
# Create skill conversation
- skill_conversation_id = await self._skill_conversation_id_factory.create_skill_conversation_id(
- options=SkillConversationIdFactoryOptions(
- activity=self._build_message_activity(conversation_reference),
- bot_framework_skill=self._build_bot_framework_skill(),
- from_bot_id=self._bot_id,
- from_bot_oauth_scope=self._bot_id,
+ skill_conversation_id = (
+ await self._skill_conversation_id_factory.create_skill_conversation_id(
+ options=SkillConversationIdFactoryOptions(
+ activity=self._build_message_activity(conversation_reference),
+ bot_framework_skill=self._build_bot_framework_skill(),
+ from_bot_id=self._bot_id,
+ from_bot_oauth_scope=self._bot_id,
+ )
)
)
@@ -44,8 +46,10 @@ async def test_skill_conversation_id_factory_happy_path(self):
), "Expected a valid skill conversation ID to be created"
# Retrieve skill conversation
- retrieved_conversation_reference = await self._skill_conversation_id_factory.get_skill_conversation_reference(
- skill_conversation_id
+ retrieved_conversation_reference = (
+ await self._skill_conversation_id_factory.get_skill_conversation_reference(
+ skill_conversation_id
+ )
)
# Delete
@@ -54,8 +58,10 @@ async def test_skill_conversation_id_factory_happy_path(self):
)
# Retrieve again
- deleted_conversation_reference = await self._skill_conversation_id_factory.get_skill_conversation_reference(
- skill_conversation_id
+ deleted_conversation_reference = (
+ await self._skill_conversation_id_factory.get_skill_conversation_reference(
+ skill_conversation_id
+ )
)
self.assertIsNotNone(retrieved_conversation_reference)
@@ -70,21 +76,25 @@ async def test_id_is_unique_each_time(self):
conversation_reference = self._build_conversation_reference()
# Create skill conversation
- first_id = await self._skill_conversation_id_factory.create_skill_conversation_id(
- options=SkillConversationIdFactoryOptions(
- activity=self._build_message_activity(conversation_reference),
- bot_framework_skill=self._build_bot_framework_skill(),
- from_bot_id=self._bot_id,
- from_bot_oauth_scope=self._bot_id,
+ first_id = (
+ await self._skill_conversation_id_factory.create_skill_conversation_id(
+ options=SkillConversationIdFactoryOptions(
+ activity=self._build_message_activity(conversation_reference),
+ bot_framework_skill=self._build_bot_framework_skill(),
+ from_bot_id=self._bot_id,
+ from_bot_oauth_scope=self._bot_id,
+ )
)
)
- second_id = await self._skill_conversation_id_factory.create_skill_conversation_id(
- options=SkillConversationIdFactoryOptions(
- activity=self._build_message_activity(conversation_reference),
- bot_framework_skill=self._build_bot_framework_skill(),
- from_bot_id=self._bot_id,
- from_bot_oauth_scope=self._bot_id,
+ second_id = (
+ await self._skill_conversation_id_factory.create_skill_conversation_id(
+ options=SkillConversationIdFactoryOptions(
+ activity=self._build_message_activity(conversation_reference),
+ bot_framework_skill=self._build_bot_framework_skill(),
+ from_bot_id=self._bot_id,
+ from_bot_oauth_scope=self._bot_id,
+ )
)
)
diff --git a/libraries/botbuilder-core/tests/skills/test_skill_handler.py b/libraries/botbuilder-core/tests/skills/test_skill_handler.py
index 7b657620b..722a944b8 100644
--- a/libraries/botbuilder-core/tests/skills/test_skill_handler.py
+++ b/libraries/botbuilder-core/tests/skills/test_skill_handler.py
@@ -114,17 +114,24 @@ async def delete_conversation_reference(self, skill_conversation_id: str):
class SkillHandlerInstanceForTests(SkillHandler):
async def test_on_get_conversations(
- self, claims_identity: ClaimsIdentity, continuation_token: str = "",
+ self,
+ claims_identity: ClaimsIdentity,
+ continuation_token: str = "",
) -> ConversationsResult:
return await self.on_get_conversations(claims_identity, continuation_token)
async def test_on_create_conversation(
- self, claims_identity: ClaimsIdentity, parameters: ConversationParameters,
+ self,
+ claims_identity: ClaimsIdentity,
+ parameters: ConversationParameters,
) -> ConversationResourceResponse:
return await self.on_create_conversation(claims_identity, parameters)
async def test_on_send_to_conversation(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity: Activity,
) -> ResourceResponse:
return await self.on_send_to_conversation(
claims_identity, conversation_id, activity
@@ -163,14 +170,19 @@ async def test_on_reply_to_activity(
)
async def test_on_delete_activity(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity_id: str,
):
return await self.on_delete_activity(
claims_identity, conversation_id, activity_id
)
async def test_on_get_conversation_members(
- self, claims_identity: ClaimsIdentity, conversation_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
) -> List[ChannelAccount]:
return await self.on_get_conversation_members(claims_identity, conversation_id)
@@ -186,14 +198,20 @@ async def test_on_get_conversation_paged_members(
)
async def test_on_delete_conversation_member(
- self, claims_identity: ClaimsIdentity, conversation_id: str, member_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ member_id: str,
):
return await self.on_delete_conversation_member(
claims_identity, conversation_id, member_id
)
async def test_on_get_activity_members(
- self, claims_identity: ClaimsIdentity, conversation_id: str, activity_id: str,
+ self,
+ claims_identity: ClaimsIdentity,
+ conversation_id: str,
+ activity_id: str,
) -> List[ChannelAccount]:
return await self.on_get_activity_members(
claims_identity, conversation_id, activity_id
@@ -469,7 +487,10 @@ async def test_on_reply_to_activity(self):
if activity_type == ActivityTypes.message:
# send_activities validation
- (args_send, _,) = mock_adapter.send_activities.call_args_list[0]
+ (
+ args_send,
+ _,
+ ) = mock_adapter.send_activities.call_args_list[0]
activity_from_send = args_send[1][0]
assert activity_from_send.caller_id is None
assert activity_from_send.reply_to_id, activity_id
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py
index 0bd3c2aa3..69273b27c 100644
--- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py
+++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py
@@ -263,8 +263,10 @@ async def on_teams_messaging_extension_configuration_query_settings_url(
self.record.append(
"on_teams_messaging_extension_configuration_query_settings_url"
)
- return await super().on_teams_messaging_extension_configuration_query_settings_url(
- turn_context, query
+ return (
+ await super().on_teams_messaging_extension_configuration_query_settings_url(
+ turn_context, query
+ )
)
async def on_teams_messaging_extension_configuration_setting(
@@ -1003,6 +1005,28 @@ async def test_on_teams_task_module_fetch(self):
assert bot.record[0] == "on_invoke_activity"
assert bot.record[1] == "on_teams_task_module_fetch"
+ async def test_on_teams_task_module_fetch_none_as_empty(self):
+ # Arrange
+ activity = Activity(
+ type=ActivityTypes.invoke,
+ name="task/fetch",
+ value={
+ "data": {"key": "value"},
+ "context": "",
+ },
+ )
+
+ turn_context = TurnContext(SimpleAdapter(), activity)
+
+ # Act
+ bot = TestingTeamsActivityHandler()
+ await bot.on_turn(turn_context)
+
+ # Assert
+ assert len(bot.record) == 2
+ assert bot.record[0] == "on_invoke_activity"
+ assert bot.record[1] == "on_teams_task_module_fetch"
+
async def test_on_teams_task_module_submit(self):
# Arrange
activity = Activity(
@@ -1030,7 +1054,10 @@ async def test_on_teams_tab_fetch(self):
activity = Activity(
type=ActivityTypes.invoke,
name="tab/fetch",
- value={"data": {"key": "value"}, "context": TabContext().serialize(),},
+ value={
+ "data": {"key": "value"},
+ "context": TabContext().serialize(),
+ },
)
turn_context = TurnContext(SimpleAdapter(), activity)
@@ -1049,7 +1076,10 @@ async def test_on_teams_tab_submit(self):
activity = Activity(
type=ActivityTypes.invoke,
name="tab/submit",
- value={"data": {"key": "value"}, "context": TabContext().serialize(),},
+ value={
+ "data": {"key": "value"},
+ "context": TabContext().serialize(),
+ },
)
turn_context = TurnContext(SimpleAdapter(), activity)
diff --git a/libraries/botbuilder-core/tests/test_bot_framework_adapter.py b/libraries/botbuilder-core/tests/test_bot_framework_adapter.py
index 51692a13d..616971f64 100644
--- a/libraries/botbuilder-core/tests/test_bot_framework_adapter.py
+++ b/libraries/botbuilder-core/tests/test_bot_framework_adapter.py
@@ -479,7 +479,10 @@ async def __process_activity_creates_correct_creds_and_client(
async def callback(context: TurnContext):
TestBotFrameworkAdapter.get_creds_and_assert_values(
- context, bot_app_id, expected_scope, expected_app_credentials_count,
+ context,
+ bot_app_id,
+ expected_scope,
+ expected_app_credentials_count,
)
TestBotFrameworkAdapter.get_client_and_assert_values(
context,
@@ -498,7 +501,11 @@ async def callback(context: TurnContext):
)
sut = BotFrameworkAdapter(settings)
await sut.process_activity_with_identity(
- Activity(channel_id="emulator", service_url=service_url, text="test",),
+ Activity(
+ channel_id="emulator",
+ service_url=service_url,
+ text="test",
+ ),
identity,
callback,
)
@@ -519,10 +526,17 @@ async def test_process_activity_for_forwarded_activity(self):
async def callback(context: TurnContext):
TestBotFrameworkAdapter.get_creds_and_assert_values(
- context, skill_1_app_id, bot_app_id, 1,
+ context,
+ skill_1_app_id,
+ bot_app_id,
+ 1,
)
TestBotFrameworkAdapter.get_client_and_assert_values(
- context, skill_1_app_id, bot_app_id, service_url, 1,
+ context,
+ skill_1_app_id,
+ bot_app_id,
+ service_url,
+ 1,
)
scope = context.turn_state[BotFrameworkAdapter.BOT_OAUTH_SCOPE_KEY]
@@ -535,7 +549,11 @@ async def callback(context: TurnContext):
settings = BotFrameworkAdapterSettings(bot_app_id)
sut = BotFrameworkAdapter(settings)
await sut.process_activity_with_identity(
- Activity(channel_id="emulator", service_url=service_url, text="test",),
+ Activity(
+ channel_id="emulator",
+ service_url=service_url,
+ text="test",
+ ),
identity,
callback,
)
@@ -640,17 +658,26 @@ async def test_continue_conversation_with_audience(self):
async def callback(context: TurnContext):
TestBotFrameworkAdapter.get_creds_and_assert_values(
- context, skill_1_app_id, skill_2_app_id, 1,
+ context,
+ skill_1_app_id,
+ skill_2_app_id,
+ 1,
)
TestBotFrameworkAdapter.get_client_and_assert_values(
- context, skill_1_app_id, skill_2_app_id, skill_2_service_url, 1,
+ context,
+ skill_1_app_id,
+ skill_2_app_id,
+ skill_2_service_url,
+ 1,
)
# pylint: disable=protected-access
client_cache = context.adapter._connector_client_cache
client = client_cache.get(
BotFrameworkAdapter.key_for_connector_client(
- skill_2_service_url, skill_1_app_id, skill_2_app_id,
+ skill_2_service_url,
+ skill_1_app_id,
+ skill_2_app_id,
)
)
assert client
@@ -769,7 +796,8 @@ async def test_process_activity_with_identity_token_exchange_invoke_response(sel
mock_credential_provider = unittest.mock.create_autospec(CredentialProvider)
settings = BotFrameworkAdapterSettings(
- app_id="bot_id", credential_provider=mock_credential_provider,
+ app_id="bot_id",
+ credential_provider=mock_credential_provider,
)
adapter = AdapterUnderTest(settings)
@@ -810,7 +838,9 @@ async def callback(context: TurnContext):
await context.send_activity(activity)
invoke_response = await adapter.process_activity_with_identity(
- inbound_activity, identity, callback,
+ inbound_activity,
+ identity,
+ callback,
)
assert invoke_response
@@ -825,7 +855,8 @@ async def test_exchange_token_from_credentials(self):
mock_credential_provider = unittest.mock.create_autospec(CredentialProvider)
settings = BotFrameworkAdapterSettings(
- app_id="bot_id", credential_provider=mock_credential_provider,
+ app_id="bot_id",
+ credential_provider=mock_credential_provider,
)
adapter = AdapterUnderTest(settings)
@@ -875,7 +906,9 @@ async def callback(context):
await context.send_activity(activity)
invoke_response = await adapter.process_activity_with_identity(
- inbound_activity, identity, callback,
+ inbound_activity,
+ identity,
+ callback,
)
assert invoke_response
diff --git a/libraries/botbuilder-core/tests/test_telemetry_middleware.py b/libraries/botbuilder-core/tests/test_telemetry_middleware.py
index 6a5cc8e5d..ee3504d1b 100644
--- a/libraries/botbuilder-core/tests/test_telemetry_middleware.py
+++ b/libraries/botbuilder-core/tests/test_telemetry_middleware.py
@@ -52,7 +52,8 @@ async def send_proactive(context: TurnContext):
async def logic(context: TurnContext):
await adapter.create_conversation(
- context.activity.channel_id, send_proactive,
+ context.activity.channel_id,
+ send_proactive,
)
adapter.logic = logic
@@ -242,16 +243,22 @@ async def test_log_teams(self):
)
adapter.use(my_logger)
- team_info = TeamInfo(id="teamId", name="teamName",)
+ team_info = TeamInfo(
+ id="teamId",
+ name="teamName",
+ )
channel_data = TeamsChannelData(
- team=team_info, tenant=TenantInfo(id="tenantId"),
- )
+ team=team_info,
+ tenant=TenantInfo(id="tenantId"),
+ ).serialize()
activity = MessageFactory.text("test")
activity.channel_data = channel_data
activity.from_property = ChannelAccount(
- id="userId", name="userName", aad_object_id="aaId",
+ id="userId",
+ name="userName",
+ aad_object_id="aaId",
)
test_flow = TestFlow(None, adapter)
@@ -265,7 +272,7 @@ async def test_log_teams(self):
"fromId": "userId",
"recipientId": "bot",
"recipientName": "Bot",
- "TeamsTenantId": TenantInfo(id="tenantId"),
+ "TeamsTenantId": "tenantId",
"TeamsUserAadObjectId": "aaId",
"TeamsTeamInfo": TeamInfo.serialize(team_info),
},
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/_user_token_access.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/_user_token_access.py
index 9b9b36b51..cd2874ad4 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/_user_token_access.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/_user_token_access.py
@@ -99,11 +99,16 @@ async def exchange_token(
if user_token_client:
channel_id = turn_context.activity.channel_id
return await user_token_client.exchange_token(
- user_id, channel_id, token_exchange_request,
+ user_id,
+ channel_id,
+ token_exchange_request,
)
if isinstance(turn_context.adapter, ExtendedUserTokenProvider):
return await turn_context.adapter.exchange_token(
- turn_context, settings.connection_name, user_id, token_exchange_request,
+ turn_context,
+ settings.connection_name,
+ user_id,
+ token_exchange_request,
)
raise TypeError("OAuthPrompt is not supported by the current adapter")
@@ -122,7 +127,9 @@ async def create_connector_client(
return await connector_factory.create(service_url, audience)
if isinstance(turn_context.adapter, ConnectorClientBuilder):
return await turn_context.adapter.create_connector_client(
- service_url, claims_identity, audience,
+ service_url,
+ claims_identity,
+ audience,
)
raise TypeError("OAuthPrompt is not supported by the current adapter")
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/about.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/about.py
index d2a3b3c35..609492f20 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/about.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-dialogs"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py
index 02fb71e6e..ec4b226b7 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py
@@ -14,7 +14,7 @@
class ChoiceRecognizers:
- """ Contains methods for matching user input against a list of choices. """
+ """Contains methods for matching user input against a list of choices."""
@staticmethod
def recognize_choices(
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find.py
index f7f5b3cab..4f37ce451 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find.py
@@ -14,7 +14,7 @@
class Find:
- """ Contains methods for matching user input against a list of choices """
+ """Contains methods for matching user input against a list of choices"""
@staticmethod
def find_choices(
@@ -22,7 +22,7 @@ def find_choices(
choices: [Union[str, Choice]],
options: FindChoicesOptions = None,
):
- """ Matches user input against a list of choices """
+ """Matches user input against a list of choices"""
if not choices:
raise TypeError(
@@ -92,9 +92,9 @@ def find_values(
# Search for each value within the utterance.
matches: [ModelResult] = []
opt = options if options else FindValuesOptions()
- tokenizer: Callable[
- [str, str], List[Token]
- ] = opt.tokenizer if opt.tokenizer else Tokenizer.default_tokenizer
+ tokenizer: Callable[[str, str], List[Token]] = (
+ opt.tokenizer if opt.tokenizer else Tokenizer.default_tokenizer
+ )
tokens = tokenizer(utterance, opt.locale)
max_distance = (
opt.max_token_distance if opt.max_token_distance is not None else 2
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py
index 418781ddb..4d7c15471 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py
@@ -5,7 +5,7 @@
class FindChoicesOptions(FindValuesOptions):
- """ Contains options to control how input is matched against a list of choices """
+ """Contains options to control how input is matched against a list of choices"""
def __init__(
self,
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py
index 63753dda2..62ac0acfa 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_values_options.py
@@ -7,7 +7,7 @@
class FindValuesOptions:
- """ Contains search options, used to control how choices are recognized in a user's utterance. """
+ """Contains search options, used to control how choices are recognized in a user's utterance."""
def __init__(
self,
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_choice.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_choice.py
index f3e994566..b32fd09a3 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_choice.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_choice.py
@@ -3,7 +3,7 @@
class FoundChoice:
- """ Represents a result from matching user input against a list of choices """
+ """Represents a result from matching user input against a list of choices"""
def __init__(self, value: str, index: int, score: float, synonym: str = None):
"""
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py
index e0a94a269..d25b19052 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/found_value.py
@@ -3,7 +3,7 @@
class FoundValue:
- """ Represents a result from matching user input against a list of choices """
+ """Represents a result from matching user input against a list of choices"""
def __init__(self, value: str, index: int, score: float):
"""
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py
index ea9724b23..6a4a2123f 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py
@@ -3,7 +3,7 @@
class SortedValue:
- """ A value that can be sorted and still refer to its original position with a source array. """
+ """A value that can be sorted and still refer to its original position with a source array."""
def __init__(self, value: str, index: int):
"""
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/token.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/token.py
index 3321e2eb4..63418b322 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/token.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/token.py
@@ -3,7 +3,7 @@
class Token:
- """ Represents an individual token, such as a word in an input string. """
+ """Represents an individual token, such as a word in an input string."""
def __init__(self, start: int, end: int, text: str, normalized: str):
"""
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py
index 1b4af2139..80d805f14 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py
@@ -7,7 +7,7 @@
class Tokenizer:
- """ Provides a default tokenizer implementation. """
+ """Provides a default tokenizer implementation."""
@staticmethod
def default_tokenizer( # pylint: disable=unused-argument
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
index d2aaa601a..f221708f1 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
@@ -231,7 +231,10 @@ async def cancel_all_dialogs(
# Check to see if the dialog wants to handle the event
if notify:
event_handled = await dialog_context.emit_event(
- event_name, event_value, bubble=False, from_leaf=False,
+ event_name,
+ event_value,
+ bubble=False,
+ from_leaf=False,
)
if event_handled:
@@ -360,7 +363,11 @@ async def emit_event(
"""
try:
# Initialize event
- dialog_event = DialogEvent(bubble=bubble, name=name, value=value,)
+ dialog_event = DialogEvent(
+ bubble=bubble,
+ name=name,
+ value=value,
+ )
dialog_context = self
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py
index be2055ffa..a5a8a34ab 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py
@@ -184,8 +184,10 @@ def __send_eoc_to_parent(turn_context: TurnContext) -> bool:
) and SkillValidation.is_skill_claim(claims_identity.claims):
# EoC Activities returned by skills are bounced back to the bot by SkillHandler.
# In those cases we will have a SkillConversationReference instance in state.
- skill_conversation_reference: SkillConversationReference = turn_context.turn_state.get(
- SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
+ skill_conversation_reference: SkillConversationReference = (
+ turn_context.turn_state.get(
+ SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
+ )
)
if skill_conversation_reference:
# If the skillConversationReference.OAuthScope is for one of the supported channels,
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py
index f0ab06055..84dc108c2 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_manager.py
@@ -142,8 +142,10 @@ async def on_turn(self, context: TurnContext) -> DialogManagerResult:
dialog_context = DialogContext(self.dialogs, context, dialog_state)
# Call the common dialog "continue/begin" execution pattern shared with the classic RunAsync extension method
- turn_result = await DialogExtensions._internal_run( # pylint: disable=protected-access
- context, self._root_dialog_id, dialog_context
+ turn_result = (
+ await DialogExtensions._internal_run( # pylint: disable=protected-access
+ context, self._root_dialog_id, dialog_context
+ )
)
# save BotState changes
@@ -224,8 +226,8 @@ def should_send_end_of_conversation_to_parent(
) and SkillValidation.is_skill_claim(claims_identity.claims):
# EoC Activities returned by skills are bounced back to the bot by SkillHandler.
# In those cases we will have a SkillConversationReference instance in state.
- skill_conversation_reference: SkillConversationReference = context.turn_state.get(
- SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
+ skill_conversation_reference: SkillConversationReference = (
+ context.turn_state.get(SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY)
)
if skill_conversation_reference:
# If the skill_conversation_reference.OAuthScope is for one of the supported channels, we are at the
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py
index 466cfac0f..4ddf01ebf 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py
@@ -26,7 +26,7 @@ def status(self):
:return self._status: The status of the stack.
:rtype self._status: :class:`DialogTurnStatus`
- """
+ """
return self._status
@property
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager.py
index 0610f3ac5..c123f2cce 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager.py
@@ -290,7 +290,10 @@ def try_get_value(
# TODO: HACK to support .First() retrieval on turn.recognized.entities.foo, replace with Expressions once
# expressions ship
first = ".FIRST()"
- i_first = path.upper().rindex(first)
+ try:
+ i_first = path.upper().rindex(first)
+ except ValueError:
+ i_first = -1
if i_first >= 0:
remaining_path = path[i_first + len(first) :]
path = path[0:i_first]
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state.py
index e4fc016e8..7825a3d9f 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state.py
@@ -9,12 +9,12 @@
class PersistedState:
def __init__(self, keys: PersistedStateKeys = None, data: Dict[str, object] = None):
if keys and data:
- self.user_state: Dict[str, object] = data[
- keys.user_state
- ] if keys.user_state in data else {}
- self.conversation_state: Dict[str, object] = data[
- keys.conversation_state
- ] if keys.conversation_state in data else {}
+ self.user_state: Dict[str, object] = (
+ data[keys.user_state] if keys.user_state in data else {}
+ )
+ self.conversation_state: Dict[str, object] = (
+ data[keys.conversation_state] if keys.conversation_state in data else {}
+ )
else:
self.user_state: Dict[str, object] = {}
self.conversation_state: Dict[str, object] = {}
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py
index 3d5f562ad..9996c7964 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py
@@ -123,7 +123,11 @@ async def on_recognize(
utterance: str = activity.text
if not utterance:
return result
- opt: FindChoicesOptions = self.recognizer_options if self.recognizer_options else FindChoicesOptions()
+ opt: FindChoicesOptions = (
+ self.recognizer_options
+ if self.recognizer_options
+ else FindChoicesOptions()
+ )
opt.locale = self._determine_culture(turn_context.activity, opt)
results = ChoiceRecognizers.recognize_choices(utterance, choices, opt)
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py
index 67a3e8ff5..55fae561f 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py
@@ -429,21 +429,21 @@ async def _recognize_token(
await context.send_activity(
Activity(
type="invokeResponse",
- value=InvokeResponse(int(HTTPStatus.OK)),
+ value=InvokeResponse(status=HTTPStatus.OK),
)
)
else:
await context.send_activity(
Activity(
type="invokeResponse",
- value=InvokeResponse(int(HTTPStatus.NOT_FOUND)),
+ value=InvokeResponse(status=HTTPStatus.NOT_FOUND),
)
)
except Exception:
await context.send_activity(
Activity(
type="invokeResponse",
- value=InvokeResponse(int(HTTPStatus.INTERNAL_SERVER_ERROR)),
+ value=InvokeResponse(status=HTTPStatus.INTERNAL_SERVER_ERROR),
)
)
elif self._is_token_exchange_request_invoke(context):
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_culture_models.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_culture_models.py
index 1572ac688..abb527e21 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_culture_models.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_culture_models.py
@@ -174,6 +174,7 @@ def get_supported_cultures(cls) -> List[PromptCultureModel]:
"""
return [
cls.Chinese,
+ cls.German,
cls.Dutch,
cls.English,
cls.French,
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_recognizer_result.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_recognizer_result.py
index aa90d7704..9d4f6b1ee 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_recognizer_result.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_recognizer_result.py
@@ -7,7 +7,6 @@
class PromptRecognizerResult:
def __init__(self, succeeded: bool = False, value: object = None):
- """Creates result returned by a prompts recognizer function.
- """
+ """Creates result returned by a prompts recognizer function."""
self.succeeded = succeeded
self.value = value
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/skills/skill_dialog.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/skills/skill_dialog.py
index 3bfd8a1db..81b67de18 100644
--- a/libraries/botbuilder-dialogs/botbuilder/dialogs/skills/skill_dialog.py
+++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/skills/skill_dialog.py
@@ -331,7 +331,9 @@ async def _send_token_exchange_invoke_to_skill(
activity.type = ActivityTypes.invoke
activity.name = SignInConstants.token_exchange_operation_name
activity.value = TokenExchangeInvokeRequest(
- id=request_id, token=token, connection_name=connection_name,
+ id=request_id,
+ token=token,
+ connection_name=connection_name,
)
# route the activity to the skill
diff --git a/libraries/botbuilder-dialogs/requirements.txt b/libraries/botbuilder-dialogs/requirements.txt
index 4b4aaabc8..3907a2b3d 100644
--- a/libraries/botbuilder-dialogs/requirements.txt
+++ b/libraries/botbuilder-dialogs/requirements.txt
@@ -1,8 +1,8 @@
-msrest==0.6.10
-botframework-connector==4.14.0
-botbuilder-schema==4.14.0
-botbuilder-core==4.14.0
-requests==2.23.0
-PyJWT==1.5.3
+msrest==0.6.*
+botframework-connector==4.15.0
+botbuilder-schema==4.15.0
+botbuilder-core==4.15.0
+requests==2.27.1
+PyJWT==2.4.0
cryptography==3.3.2
aiounittest==1.3.0
diff --git a/libraries/botbuilder-dialogs/setup.py b/libraries/botbuilder-dialogs/setup.py
index 8890439cd..6e97715a5 100644
--- a/libraries/botbuilder-dialogs/setup.py
+++ b/libraries/botbuilder-dialogs/setup.py
@@ -6,15 +6,16 @@
REQUIRES = [
"regex<=2019.08.19",
+ "emoji==1.7.0",
"recognizers-text-date-time>=1.0.2a1",
"recognizers-text-number-with-unit>=1.0.2a1",
"recognizers-text-number>=1.0.2a1",
"recognizers-text>=1.0.2a1",
"recognizers-text-choice>=1.0.2a1",
- "babel==2.7.0",
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botbuilder-core==4.14.0",
+ "babel==2.9.1",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botbuilder-core==4.15.0",
]
TEST_REQUIRES = ["aiounittest==1.3.0"]
diff --git a/libraries/botbuilder-dialogs/tests/memory/scopes/test_settings.py b/libraries/botbuilder-dialogs/tests/memory/scopes/test_settings.py
index ab83adef1..9e21a99a6 100644
--- a/libraries/botbuilder-dialogs/tests/memory/scopes/test_settings.py
+++ b/libraries/botbuilder-dialogs/tests/memory/scopes/test_settings.py
@@ -5,7 +5,7 @@
class DefaultConfig:
- """ Bot Configuration """
+ """Bot Configuration"""
STRING = os.environ.get("STRING", "test")
INT = os.environ.get("INT", 3)
diff --git a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py
index ce3035603..995758888 100644
--- a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py
+++ b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py
@@ -527,7 +527,9 @@ async def validator(prompt: PromptValidatorContext) -> bool:
for locale_tests in locale_tests:
await exec_test_for_locale(locale_tests[0], locale_tests)
- async def test_should_recognize_and_use_custom_locale_dict(self,):
+ async def test_should_recognize_and_use_custom_locale_dict(
+ self,
+ ):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
diff --git a/libraries/botbuilder-dialogs/tests/test_confirm_prompt.py b/libraries/botbuilder-dialogs/tests/test_confirm_prompt.py
index 905eea4a0..132fef923 100644
--- a/libraries/botbuilder-dialogs/tests/test_confirm_prompt.py
+++ b/libraries/botbuilder-dialogs/tests/test_confirm_prompt.py
@@ -438,7 +438,9 @@ async def validator(prompt: PromptValidatorContext) -> bool:
for locale_tests in locale_tests:
await exec_test_for_locale(locale_tests[0], locale_tests)
- async def test_should_recognize_and_use_custom_locale_dict(self,):
+ async def test_should_recognize_and_use_custom_locale_dict(
+ self,
+ ):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
diff --git a/libraries/botbuilder-dialogs/tests/test_dialog_manager.py b/libraries/botbuilder-dialogs/tests/test_dialog_manager.py
index 0ce723054..1846ce42f 100644
--- a/libraries/botbuilder-dialogs/tests/test_dialog_manager.py
+++ b/libraries/botbuilder-dialogs/tests/test_dialog_manager.py
@@ -81,7 +81,11 @@ def __init__(
self.add_dialog(TextPrompt(self.text_prompt))
self.add_dialog(
WaterfallDialog(
- self.waterfall_dialog, [self.prompt_for_name, self.final_step,]
+ self.waterfall_dialog,
+ [
+ self.prompt_for_name,
+ self.final_step,
+ ],
)
)
self.initial_dialog_id = self.waterfall_dialog
diff --git a/libraries/botbuilder-dialogs/tests/test_dialogextensions.py b/libraries/botbuilder-dialogs/tests/test_dialogextensions.py
index d95142a7e..533f4384c 100644
--- a/libraries/botbuilder-dialogs/tests/test_dialogextensions.py
+++ b/libraries/botbuilder-dialogs/tests/test_dialogextensions.py
@@ -147,7 +147,8 @@ async def test_skill_handles_eoc_from_parent(self):
await test_flow.assert_reply("Hello, what is your name?")
await test_flow.send(
Activity(
- type=ActivityTypes.end_of_conversation, caller_id=self.parent_bot_id,
+ type=ActivityTypes.end_of_conversation,
+ caller_id=self.parent_bot_id,
)
)
diff --git a/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py b/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py
index a6b22553b..7a1eaeba6 100644
--- a/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py
+++ b/libraries/botbuilder-dialogs/tests/test_oauth_prompt.py
@@ -324,7 +324,9 @@ def inspector(
step3 = await step2.send("test invalid message")
await step3.assert_reply("Ended")
- async def test_should_timeout_oauth_prompt_with_message_activity(self,):
+ async def test_should_timeout_oauth_prompt_with_message_activity(
+ self,
+ ):
activity = Activity(type=ActivityTypes.message, text="any")
await self.run_timeout_test(activity)
@@ -344,7 +346,9 @@ async def test_should_timeout_oauth_prompt_with_verify_state_operation_activity(
)
await self.run_timeout_test(activity)
- async def test_should_not_timeout_oauth_prompt_with_custom_event_activity(self,):
+ async def test_should_not_timeout_oauth_prompt_with_custom_event_activity(
+ self,
+ ):
activity = Activity(type=ActivityTypes.event, name="custom event name")
await self.run_timeout_test(activity, False, "Ended", "Failed")
@@ -388,7 +392,8 @@ async def exec_test(turn_context: TurnContext):
dialogs = DialogSet(dialog_state)
dialogs.add(
OAuthPrompt(
- "prompt", OAuthPromptSettings(connection_name, "Login", None, 1),
+ "prompt",
+ OAuthPromptSettings(connection_name, "Login", None, 1),
)
)
diff --git a/libraries/botbuilder-dialogs/tests/test_object_path.py b/libraries/botbuilder-dialogs/tests/test_object_path.py
index 447f52893..8ff6ff543 100644
--- a/libraries/botbuilder-dialogs/tests/test_object_path.py
+++ b/libraries/botbuilder-dialogs/tests/test_object_path.py
@@ -33,7 +33,10 @@ async def test_typed_only_default(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
overlay = Options()
@@ -53,7 +56,10 @@ async def test_typed_only_overlay(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
result = ObjectPath.assign(default_options, overlay)
@@ -69,7 +75,10 @@ async def test_typed_full_overlay(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
dictionary={"one": 1, "two": 2},
)
@@ -77,7 +86,10 @@ async def test_typed_full_overlay(self):
last_name="Grant",
first_name="Eddit",
age=32,
- location=Location(lat=2.2312312, long=2.234234,),
+ location=Location(
+ lat=2.2312312,
+ long=2.234234,
+ ),
dictionary={"one": 99, "three": 3},
)
@@ -98,10 +110,15 @@ async def test_typed_partial_overlay(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
- overlay = Options(last_name="Grant",)
+ overlay = Options(
+ last_name="Grant",
+ )
result = ObjectPath.assign(default_options, overlay)
assert result.last_name == overlay.last_name
@@ -116,7 +133,10 @@ async def test_typed_no_target(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
result = ObjectPath.assign(None, overlay)
@@ -132,7 +152,10 @@ async def test_typed_no_overlay(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
result = ObjectPath.assign(default_options, None)
@@ -152,7 +175,10 @@ async def test_dict_partial_overlay(self):
"last_name": "Smith",
"first_name": "Fred",
"age": 22,
- "location": Location(lat=1.2312312, long=3.234234,),
+ "location": Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
}
overlay = {
@@ -171,7 +197,10 @@ async def test_dict_to_typed_overlay(self):
last_name="Smith",
first_name="Fred",
age=22,
- location=Location(lat=1.2312312, long=3.234234,),
+ location=Location(
+ lat=1.2312312,
+ long=3.234234,
+ ),
)
overlay = {
diff --git a/libraries/botbuilder-dialogs/tests/test_skill_dialog.py b/libraries/botbuilder-dialogs/tests/test_skill_dialog.py
index 9bb695a62..3c2a3d1b4 100644
--- a/libraries/botbuilder-dialogs/tests/test_skill_dialog.py
+++ b/libraries/botbuilder-dialogs/tests/test_skill_dialog.py
@@ -208,7 +208,10 @@ async def capture(
)
sut = SkillDialog(dialog_options, "dialog_id")
- activity_to_send = Activity(type=ActivityTypes.invoke, name=str(uuid.uuid4()),)
+ activity_to_send = Activity(
+ type=ActivityTypes.invoke,
+ name=str(uuid.uuid4()),
+ )
client = DialogTestClient(
"test",
@@ -334,7 +337,9 @@ async def post_return():
client = DialogTestClient(
"test",
sut,
- BeginSkillDialogOptions(activity=activity_to_send,),
+ BeginSkillDialogOptions(
+ activity=activity_to_send,
+ ),
conversation_state=conversation_state,
)
@@ -376,7 +381,9 @@ async def post_return():
client = DialogTestClient(
"test",
sut,
- BeginSkillDialogOptions(activity=activity_to_send,),
+ BeginSkillDialogOptions(
+ activity=activity_to_send,
+ ),
conversation_state=conversation_state,
)
@@ -418,7 +425,9 @@ async def post_return():
client = DialogTestClient(
"test",
sut,
- BeginSkillDialogOptions(activity=activity_to_send,),
+ BeginSkillDialogOptions(
+ activity=activity_to_send,
+ ),
conversation_state=conversation_state,
)
@@ -455,10 +464,15 @@ async def post_return():
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
- initial_dialog_options = BeginSkillDialogOptions(activity=activity_to_send,)
+ initial_dialog_options = BeginSkillDialogOptions(
+ activity=activity_to_send,
+ )
client = DialogTestClient(
- "test", sut, initial_dialog_options, conversation_state=conversation_state,
+ "test",
+ sut,
+ initial_dialog_options,
+ conversation_state=conversation_state,
)
client.test_adapter.throw_on_exchange_request(
connection_name, "test", "User1", "https://test"
@@ -499,7 +513,9 @@ async def post_return():
client = DialogTestClient(
"test",
sut,
- BeginSkillDialogOptions(activity=activity_to_send,),
+ BeginSkillDialogOptions(
+ activity=activity_to_send,
+ ),
conversation_state=conversation_state,
)
@@ -558,7 +574,9 @@ async def capture_action(
# Send something to the dialog to start it
await client.send_activity("hello")
- simple_id_factory: SimpleConversationIdFactory = dialog_options.conversation_id_factory
+ simple_id_factory: SimpleConversationIdFactory = (
+ dialog_options.conversation_id_factory
+ )
self.assertEqual(0, len(simple_id_factory.conversation_refs))
self.assertEqual(1, simple_id_factory.create_count)
@@ -593,7 +611,8 @@ def create_send_activity() -> Activity:
def create_oauth_card_attachment_activity(uri: str) -> Activity:
oauth_card = OAuthCard(token_exchange_resource=TokenExchangeResource(uri=uri))
attachment = Attachment(
- content_type=ContentTypes.oauth_card, content=oauth_card,
+ content_type=ContentTypes.oauth_card,
+ content=oauth_card,
)
attachment_activity = MessageFactory.attachment(attachment)
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/about.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/about.py
index 5a5370a30..898458512 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/about.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/about.py
@@ -5,7 +5,7 @@
__title__ = "botbuilder-integration-aiohttp"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/aiohttp_channel_service.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/aiohttp_channel_service.py
index af2545d89..8a31f3342 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/aiohttp_channel_service.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/aiohttp_channel_service.py
@@ -127,7 +127,8 @@ async def get_conversation(request: Request):
@routes.get(base_url + "/v3/conversations/{conversation_id}/members")
async def get_conversation_members(request: Request):
result = await handler.handle_get_conversation_members(
- request.headers.get("Authorization"), request.match_info["conversation_id"],
+ request.headers.get("Authorization"),
+ request.match_info["conversation_id"],
)
return get_serialized_response(result)
@@ -136,7 +137,8 @@ async def get_conversation_members(request: Request):
async def get_conversation_paged_members(request: Request):
# TODO: continuation token? page size?
result = await handler.handle_get_conversation_paged_members(
- request.headers.get("Authorization"), request.match_info["conversation_id"],
+ request.headers.get("Authorization"),
+ request.match_info["conversation_id"],
)
return get_serialized_response(result)
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py
index a331380fa..cf46a0081 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py
@@ -121,12 +121,16 @@ async def _post_content(
}
if token:
headers_dict.update(
- {"Authorization": f"Bearer {token}",}
+ {
+ "Authorization": f"Bearer {token}",
+ }
)
json_content = json.dumps(activity.serialize())
resp = await self._session.post(
- to_url, data=json_content.encode("utf-8"), headers=headers_dict,
+ to_url,
+ data=json_content.encode("utf-8"),
+ headers=headers_dict,
)
resp.raise_for_status()
data = (await resp.read()).decode()
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/cloud_adapter.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/cloud_adapter.py
index 32fba5c97..0aa2ba8af 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/cloud_adapter.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/cloud_adapter.py
@@ -121,8 +121,10 @@ async def _connect(
# Grab the channelId which should be in the http headers
channel_id = request.headers.get(self._CHANNEL_ID_HEADER_NAME)
- authentication_request_result = await self.bot_framework_authentication.authenticate_streaming_request(
- auth_header, channel_id
+ authentication_request_result = (
+ await self.bot_framework_authentication.authenticate_streaming_request(
+ auth_header, channel_id
+ )
)
# Transition the request to a WebSocket connection
@@ -151,8 +153,8 @@ def __init__(
self._request_handler = StreamingRequestHandler(bot, self, web_socket)
# Fix up the connector factory so connector create from it will send over this connection
- self._authenticate_request_result.connector_factory = _StreamingConnectorFactory(
- self._request_handler
+ self._authenticate_request_result.connector_factory = (
+ _StreamingConnectorFactory(self._request_handler)
)
async def listen(self):
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py
index 39b036058..8ef9d3bf1 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/configuration_bot_framework_authentication.py
@@ -30,38 +30,40 @@ def __init__(
http_client_factory: HttpClientFactory = None,
logger: Logger = None
):
- self._inner: BotFrameworkAuthentication = BotFrameworkAuthenticationFactory.create(
- channel_service=getattr(configuration, "CHANNEL_SERVICE", None),
- validate_authority=getattr(configuration, "VALIDATE_AUTHORITY", True),
- to_channel_from_bot_login_url=getattr(
- configuration, "TO_CHANNEL_FROM_BOT_LOGIN_URL", None
- ),
- to_channel_from_bot_oauth_scope=getattr(
- configuration, "TO_CHANNEL_FROM_BOT_OAUTH_SCOPE", None
- ),
- to_bot_from_channel_token_issuer=getattr(
- configuration, "TO_BOT_FROM_CHANNEL_TOKEN_ISSUER", None
- ),
- oauth_url=getattr(configuration, "OAUTH_URL", None),
- to_bot_from_channel_open_id_metadata_url=getattr(
- configuration, "TO_BOT_FROM_CHANNEL_OPENID_METADATA_URL", None
- ),
- to_bot_from_emulator_open_id_metadata_url=getattr(
- configuration, "TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL", None
- ),
- caller_id=getattr(configuration, "CALLER_ID", None),
- credential_factory=(
- credentials_factory
- if credentials_factory
- else ConfigurationServiceClientCredentialFactory(configuration)
- ),
- auth_configuration=(
- auth_configuration
- if auth_configuration
- else AuthenticationConfiguration()
- ),
- http_client_factory=http_client_factory,
- logger=logger,
+ self._inner: BotFrameworkAuthentication = (
+ BotFrameworkAuthenticationFactory.create(
+ channel_service=getattr(configuration, "CHANNEL_SERVICE", None),
+ validate_authority=getattr(configuration, "VALIDATE_AUTHORITY", True),
+ to_channel_from_bot_login_url=getattr(
+ configuration, "TO_CHANNEL_FROM_BOT_LOGIN_URL", None
+ ),
+ to_channel_from_bot_oauth_scope=getattr(
+ configuration, "TO_CHANNEL_FROM_BOT_OAUTH_SCOPE", None
+ ),
+ to_bot_from_channel_token_issuer=getattr(
+ configuration, "TO_BOT_FROM_CHANNEL_TOKEN_ISSUER", None
+ ),
+ oauth_url=getattr(configuration, "OAUTH_URL", None),
+ to_bot_from_channel_open_id_metadata_url=getattr(
+ configuration, "TO_BOT_FROM_CHANNEL_OPENID_METADATA_URL", None
+ ),
+ to_bot_from_emulator_open_id_metadata_url=getattr(
+ configuration, "TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL", None
+ ),
+ caller_id=getattr(configuration, "CALLER_ID", None),
+ credential_factory=(
+ credentials_factory
+ if credentials_factory
+ else ConfigurationServiceClientCredentialFactory(configuration)
+ ),
+ auth_configuration=(
+ auth_configuration
+ if auth_configuration
+ else AuthenticationConfiguration()
+ ),
+ http_client_factory=http_client_factory,
+ logger=logger,
+ )
)
async def authenticate_request(
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/skill_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/skill_http_client.py
index 68da498ab..6f3e2a215 100644
--- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/skill_http_client.py
+++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/skills/skill_http_client.py
@@ -61,8 +61,10 @@ async def post_activity_to_skill(
bot_framework_skill=to_skill,
)
- skill_conversation_id = await self._skill_conversation_id_factory.create_skill_conversation_id(
- options
+ skill_conversation_id = (
+ await self._skill_conversation_id_factory.create_skill_conversation_id(
+ options
+ )
)
return await super().post_activity(
diff --git a/libraries/botbuilder-integration-aiohttp/requirements.txt b/libraries/botbuilder-integration-aiohttp/requirements.txt
index 8898a86aa..fc518a833 100644
--- a/libraries/botbuilder-integration-aiohttp/requirements.txt
+++ b/libraries/botbuilder-integration-aiohttp/requirements.txt
@@ -1,4 +1,4 @@
-msrest==0.6.10
-botframework-connector==4.14.0
-botbuilder-schema==4.14.0
+msrest==0.6.*
+botframework-connector==4.15.0
+botbuilder-schema==4.15.0
aiohttp==3.7.4
diff --git a/libraries/botbuilder-integration-aiohttp/setup.py b/libraries/botbuilder-integration-aiohttp/setup.py
index 1d6b34204..603690785 100644
--- a/libraries/botbuilder-integration-aiohttp/setup.py
+++ b/libraries/botbuilder-integration-aiohttp/setup.py
@@ -4,11 +4,11 @@
import os
from setuptools import setup
-VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
REQUIRES = [
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botbuilder-core==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botbuilder-core==4.15.0",
"yarl<=1.4.2",
"aiohttp>=3.6.2,<3.8.0",
]
diff --git a/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/about.py b/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/about.py
index e718dad20..6a821af3e 100644
--- a/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/about.py
+++ b/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/about.py
@@ -6,7 +6,7 @@
__title__ = "botbuilder-integration-applicationinsights-aiohttp"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py b/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py
index 06a509fd3..94c9aea11 100644
--- a/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py
+++ b/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py
@@ -7,10 +7,10 @@
REQUIRES = [
"applicationinsights>=0.11.9",
"aiohttp>=3.6.2,<3.8.0",
- "botbuilder-schema==4.14.0",
- "botframework-connector==4.14.0",
- "botbuilder-core==4.14.0",
- "botbuilder-applicationinsights==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
+ "botbuilder-core==4.15.0",
+ "botbuilder-applicationinsights==4.15.0",
]
TESTS_REQUIRES = [
"aiounittest==1.3.0",
diff --git a/libraries/botbuilder-schema/botbuilder/schema/__init__.py b/libraries/botbuilder-schema/botbuilder/schema/__init__.py
index 8e3eea34e..082eb28e6 100644
--- a/libraries/botbuilder-schema/botbuilder/schema/__init__.py
+++ b/libraries/botbuilder-schema/botbuilder/schema/__init__.py
@@ -1,6 +1,8 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
+from warnings import warn
+
from ._models_py3 import Activity
from ._models_py3 import ActivityEventNames
from ._models_py3 import AdaptiveCardInvokeAction
@@ -75,6 +77,10 @@
from .callerid_constants import CallerIdConstants
from .speech_constants import SpeechConstants
+warn(
+ "The Bot Framework Python SDK is being retired with final long-term support ending in November 2023, after which this repository will be archived. There will be no further feature development, with only critical security and bug fixes within this repository being undertaken. Existing bots built with this SDK will continue to function. For all new bot development we recommend that you adopt Power Virtual Agents."
+)
+
__all__ = [
"Activity",
"ActivityEventNames",
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py
index 51c0b9d74..3f0f9689f 100644
--- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py
+++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py
@@ -1,6 +1,7 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
+from typing import List
from msrest.serialization import Model
from botbuilder.schema import (
Attachment,
@@ -1947,7 +1948,7 @@ def __init__(
self,
*,
continuation_token: str = None,
- members: [TeamsChannelAccount] = None,
+ members: List[TeamsChannelAccount] = None,
**kwargs
) -> None:
super(TeamsPagedMembersResult, self).__init__(
@@ -1977,7 +1978,7 @@ class TeamsChannelData(Model):
_attribute_map = {
"channel": {"key": "channel", "type": "ChannelInfo"},
- "eventType": {"key": "eventType", "type": "str"},
+ "event_type": {"key": "eventType", "type": "str"},
"team": {"key": "team", "type": "TeamInfo"},
"notification": {"key": "notification", "type": "NotificationInfo"},
"tenant": {"key": "tenant", "type": "TenantInfo"},
@@ -1988,7 +1989,7 @@ def __init__(
self,
*,
channel=None,
- eventType: str = None,
+ event_type: str = None,
team=None,
notification=None,
tenant=None,
@@ -1998,7 +1999,7 @@ def __init__(
super(TeamsChannelData, self).__init__(**kwargs)
self.channel = channel
# doing camel case here since that's how the data comes in
- self.event_type = eventType
+ self.event_type = event_type
self.team = team
self.notification = notification
self.tenant = tenant
diff --git a/libraries/botbuilder-schema/requirements.txt b/libraries/botbuilder-schema/requirements.txt
index 0361325e5..908ffb023 100644
--- a/libraries/botbuilder-schema/requirements.txt
+++ b/libraries/botbuilder-schema/requirements.txt
@@ -1,2 +1,2 @@
aiounittest==1.3.0
-msrest==0.6.10
\ No newline at end of file
+msrest==0.6.*
\ No newline at end of file
diff --git a/libraries/botbuilder-schema/setup.py b/libraries/botbuilder-schema/setup.py
index e52027451..085ac7ca2 100644
--- a/libraries/botbuilder-schema/setup.py
+++ b/libraries/botbuilder-schema/setup.py
@@ -5,8 +5,8 @@
from setuptools import setup
NAME = "botbuilder-schema"
-VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
-REQUIRES = ["msrest==0.6.10"]
+VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
+REQUIRES = ["msrest==0.6.*"]
root = os.path.abspath(os.path.dirname(__file__))
@@ -24,7 +24,10 @@
long_description_content_type="text/x-rst",
license="MIT",
install_requires=REQUIRES,
- packages=["botbuilder.schema", "botbuilder.schema.teams",],
+ packages=[
+ "botbuilder.schema",
+ "botbuilder.schema.teams",
+ ],
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3.7",
diff --git a/libraries/botbuilder-testing/botbuilder/testing/about.py b/libraries/botbuilder-testing/botbuilder/testing/about.py
index 677893266..5c866c335 100644
--- a/libraries/botbuilder-testing/botbuilder/testing/about.py
+++ b/libraries/botbuilder-testing/botbuilder/testing/about.py
@@ -6,7 +6,7 @@
__title__ = "botbuilder-testing"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botbuilder-testing/botbuilder/testing/storage_base_tests.py b/libraries/botbuilder-testing/botbuilder/testing/storage_base_tests.py
index 1a307d336..e196099a0 100644
--- a/libraries/botbuilder-testing/botbuilder/testing/storage_base_tests.py
+++ b/libraries/botbuilder-testing/botbuilder/testing/storage_base_tests.py
@@ -248,7 +248,11 @@ async def delete_unknown_object(storage) -> bool:
@staticmethod
async def perform_batch_operations(storage) -> bool:
await storage.write(
- {"batch1": {"count": 10}, "batch2": {"count": 20}, "batch3": {"count": 30},}
+ {
+ "batch1": {"count": 10},
+ "batch2": {"count": 20},
+ "batch3": {"count": 30},
+ }
)
result = await storage.read(["batch1", "batch2", "batch3"])
diff --git a/libraries/botbuilder-testing/requirements.txt b/libraries/botbuilder-testing/requirements.txt
index 89ca8a2b9..8f011997c 100644
--- a/libraries/botbuilder-testing/requirements.txt
+++ b/libraries/botbuilder-testing/requirements.txt
@@ -1,4 +1,4 @@
-botbuilder-schema==4.14.0
-botbuilder-core==4.14.0
-botbuilder-dialogs==4.14.0
+botbuilder-schema==4.15.0
+botbuilder-core==4.15.0
+botbuilder-dialogs==4.15.0
aiounittest==1.4.0
diff --git a/libraries/botbuilder-testing/setup.py b/libraries/botbuilder-testing/setup.py
index 6d5d236d5..36b99ef73 100644
--- a/libraries/botbuilder-testing/setup.py
+++ b/libraries/botbuilder-testing/setup.py
@@ -5,10 +5,10 @@
from setuptools import setup
REQUIRES = [
- "botbuilder-schema==4.14.0",
- "botbuilder-core==4.14.0",
- "botbuilder-dialogs==4.14.0",
- "botbuilder-azure==4.14.0",
+ "botbuilder-schema==4.15.0",
+ "botbuilder-core==4.15.0",
+ "botbuilder-dialogs==4.15.0",
+ "botbuilder-azure==4.15.0",
"pytest~=6.2.3",
]
diff --git a/libraries/botframework-connector/botframework/connector/about.py b/libraries/botframework-connector/botframework/connector/about.py
index 86722da0f..1df0ab2e9 100644
--- a/libraries/botframework-connector/botframework/connector/about.py
+++ b/libraries/botframework-connector/botframework/connector/about.py
@@ -5,7 +5,7 @@
__title__ = "botframework-connector"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py b/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
index 8a2313480..c8a913df0 100644
--- a/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
+++ b/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
@@ -143,7 +143,7 @@ class _MsrestStopIteration(Exception):
def _msrest_next(iterator):
- """"To avoid:
+ """ "To avoid:
TypeError: StopIteration interacts badly with generators and cannot be raised into a Future
"""
try:
diff --git a/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py b/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py
index aeff33376..512207cd4 100644
--- a/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py
+++ b/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py
@@ -103,7 +103,9 @@ async def post_activity(
}
if token:
headers_dict.update(
- {"Authorization": f"Bearer {token}",}
+ {
+ "Authorization": f"Bearer {token}",
+ }
)
json_content = dumps(activity_copy.serialize()).encode("utf-8")
diff --git a/libraries/botframework-connector/botframework/connector/auth/channel_validation.py b/libraries/botframework-connector/botframework/connector/auth/channel_validation.py
index 0acaeea8f..671086a80 100644
--- a/libraries/botframework-connector/botframework/connector/auth/channel_validation.py
+++ b/libraries/botframework-connector/botframework/connector/auth/channel_validation.py
@@ -36,7 +36,7 @@ async def authenticate_channel_token_with_service_url(
channel_id: str,
auth_configuration: AuthenticationConfiguration = None,
) -> ClaimsIdentity:
- """ Validate the incoming Auth Header
+ """Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
@@ -71,7 +71,7 @@ async def authenticate_channel_token(
channel_id: str,
auth_configuration: AuthenticationConfiguration = None,
) -> ClaimsIdentity:
- """ Validate the incoming Auth Header
+ """Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
diff --git a/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py b/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py
index a50a5eaea..57c961ddc 100644
--- a/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py
+++ b/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py
@@ -46,7 +46,7 @@ class EmulatorValidation:
@staticmethod
def is_token_from_emulator(auth_header: str) -> bool:
- """ Determines if a given Auth header is from the Bot Framework Emulator
+ """Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
@@ -63,7 +63,7 @@ def is_token_from_emulator(auth_header: str) -> bool:
bearer_token = auth_header.split(" ")[1]
# Parse the Big Long String into an actual token.
- token = jwt.decode(bearer_token, verify=False)
+ token = jwt.decode(bearer_token, options={"verify_signature": False})
if not token:
return False
@@ -91,7 +91,7 @@ async def authenticate_emulator_token(
channel_service_or_provider: Union[str, ChannelProvider],
channel_id: str,
) -> ClaimsIdentity:
- """ Validate the incoming Auth Header
+ """Validate the incoming Auth Header
Validate the incoming Auth Header as a token sent from the Bot Framework Service.
A token issued by the Bot Framework emulator will FAIL this check.
diff --git a/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py b/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py
index 48a93ba5d..7abd054a5 100644
--- a/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py
+++ b/libraries/botframework-connector/botframework/connector/auth/enterprise_channel_validation.py
@@ -64,12 +64,14 @@ async def authenticate_channel_token_with_service_url(
channel_service_or_provider: Union[str, ChannelProvider],
auth_configuration: AuthenticationConfiguration = None,
) -> ClaimsIdentity:
- identity: ClaimsIdentity = await EnterpriseChannelValidation.authenticate_channel_token(
- auth_header,
- credentials,
- channel_id,
- channel_service_or_provider,
- auth_configuration,
+ identity: ClaimsIdentity = (
+ await EnterpriseChannelValidation.authenticate_channel_token(
+ auth_header,
+ credentials,
+ channel_id,
+ channel_service_or_provider,
+ auth_configuration,
+ )
)
service_url_claim: str = identity.get_claim_value(
diff --git a/libraries/botframework-connector/botframework/connector/auth/government_channel_validation.py b/libraries/botframework-connector/botframework/connector/auth/government_channel_validation.py
index 3c2285393..5d7868b71 100644
--- a/libraries/botframework-connector/botframework/connector/auth/government_channel_validation.py
+++ b/libraries/botframework-connector/botframework/connector/auth/government_channel_validation.py
@@ -57,8 +57,10 @@ async def authenticate_channel_token_with_service_url(
channel_id: str,
auth_configuration: AuthenticationConfiguration = None,
) -> ClaimsIdentity:
- identity: ClaimsIdentity = await GovernmentChannelValidation.authenticate_channel_token(
- auth_header, credentials, channel_id, auth_configuration
+ identity: ClaimsIdentity = (
+ await GovernmentChannelValidation.authenticate_channel_token(
+ auth_header, credentials, channel_id, auth_configuration
+ )
)
service_url_claim: str = identity.get_claim_value(
diff --git a/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py b/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py
index 91dd5d221..a030c3fb7 100644
--- a/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py
+++ b/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py
@@ -68,7 +68,7 @@ async def get_identity(
raise error
def _has_allowed_issuer(self, jwt_token: str) -> bool:
- decoded = jwt.decode(jwt_token, verify=False)
+ decoded = jwt.decode(jwt_token, options={"verify_signature": False})
issuer = decoded.get("iss", None)
if issuer in self.validation_parameters.issuer:
return True
@@ -111,6 +111,7 @@ async def _validate_token(
metadata.public_key,
leeway=self.validation_parameters.clock_tolerance,
options=options,
+ algorithms=["RS256"],
)
claims = ClaimsIdentity(decoded_payload, True)
diff --git a/libraries/botframework-connector/botframework/connector/auth/skill_validation.py b/libraries/botframework-connector/botframework/connector/auth/skill_validation.py
index fb3f7a1a8..d23572e3f 100644
--- a/libraries/botframework-connector/botframework/connector/auth/skill_validation.py
+++ b/libraries/botframework-connector/botframework/connector/auth/skill_validation.py
@@ -55,7 +55,7 @@ def is_skill_token(auth_header: str) -> bool:
bearer_token = auth_header.split(" ")[1]
# Parse the Big Long String into an actual token.
- token = jwt.decode(bearer_token, verify=False)
+ token = jwt.decode(bearer_token, options={"verify_signature": False})
return SkillValidation.is_skill_claim(token)
@staticmethod
diff --git a/libraries/botframework-connector/botframework/connector/token_api/_token_api_client.py b/libraries/botframework-connector/botframework/connector/token_api/_token_api_client.py
index f4d34c744..dbb6a52fe 100644
--- a/libraries/botframework-connector/botframework/connector/token_api/_token_api_client.py
+++ b/libraries/botframework-connector/botframework/connector/token_api/_token_api_client.py
@@ -9,8 +9,8 @@
from msrest import Serializer, Deserializer
from ._configuration import TokenApiClientConfiguration
-from .operations import BotSignInOperations
-from .operations import UserTokenOperations
+from .operations._bot_sign_in_operations import BotSignInOperations
+from .operations._user_token_operations import UserTokenOperations
from . import models
diff --git a/libraries/botframework-connector/botframework/connector/token_api/aio/_token_api_client_async.py b/libraries/botframework-connector/botframework/connector/token_api/aio/_token_api_client_async.py
index 80eba06be..513cb62be 100644
--- a/libraries/botframework-connector/botframework/connector/token_api/aio/_token_api_client_async.py
+++ b/libraries/botframework-connector/botframework/connector/token_api/aio/_token_api_client_async.py
@@ -9,8 +9,8 @@
from msrest import Serializer, Deserializer
from .._configuration import TokenApiClientConfiguration
-from .operations_async import BotSignInOperations
-from .operations_async import UserTokenOperations
+from .operations_async._bot_sign_in_operations_async import BotSignInOperations
+from .operations_async._user_token_operations_async import UserTokenOperations
from .. import models
diff --git a/libraries/botframework-connector/requirements.txt b/libraries/botframework-connector/requirements.txt
index 277baedbf..118e3f311 100644
--- a/libraries/botframework-connector/requirements.txt
+++ b/libraries/botframework-connector/requirements.txt
@@ -1,6 +1,6 @@
-msrest==0.6.10
-botbuilder-schema==4.14.0
-requests==2.23.0
-PyJWT==1.5.3
+msrest==0.6.*
+botbuilder-schema==4.15.0
+requests==2.27.1
+PyJWT==2.4.0
cryptography==3.3.2
-msal==1.6.0
+msal==1.*
diff --git a/libraries/botframework-connector/setup.py b/libraries/botframework-connector/setup.py
index 4e2ec8c7c..15411c492 100644
--- a/libraries/botframework-connector/setup.py
+++ b/libraries/botframework-connector/setup.py
@@ -5,13 +5,13 @@
from setuptools import setup
NAME = "botframework-connector"
-VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
REQUIRES = [
- "msrest==0.6.10",
- "requests>=2.23.0,<2.26",
- "PyJWT>=1.5.3,<2.0.0",
- "botbuilder-schema==4.14.0",
- "msal==1.6.0",
+ "msrest==0.6.*",
+ # "requests>=2.23.0,<2.26",
+ "PyJWT>=2.4.0",
+ "botbuilder-schema==4.15.0",
+ "msal==1.*",
]
root = os.path.abspath(os.path.dirname(__file__))
@@ -40,6 +40,7 @@
"botframework.connector.teams.operations",
"botframework.connector.token_api",
"botframework.connector.token_api.aio",
+ "botframework.connector.token_api.aio.operations_async",
"botframework.connector.token_api.models",
"botframework.connector.token_api.operations",
],
diff --git a/libraries/botframework-connector/tests/requirements.txt b/libraries/botframework-connector/tests/requirements.txt
index a5669fcb8..a376f63cf 100644
--- a/libraries/botframework-connector/tests/requirements.txt
+++ b/libraries/botframework-connector/tests/requirements.txt
@@ -1,5 +1,6 @@
pytest-cov>=2.6.0
pytest~=6.2.3
+pyyaml==5.4
azure-devtools>=0.4.1
pytest-asyncio==0.15.1
ddt==1.2.1
\ No newline at end of file
diff --git a/libraries/botframework-connector/tests/test_auth.py b/libraries/botframework-connector/tests/test_auth.py
index a13f433ef..39a29a1ea 100644
--- a/libraries/botframework-connector/tests/test_auth.py
+++ b/libraries/botframework-connector/tests/test_auth.py
@@ -19,11 +19,11 @@
ChannelValidation,
ClaimsIdentity,
MicrosoftAppCredentials,
- GovernmentConstants,
+ # GovernmentConstants,
GovernmentChannelValidation,
SimpleChannelProvider,
ChannelProvider,
- AppCredentials,
+ # AppCredentials,
)
@@ -105,84 +105,84 @@ async def test_claims_validation(self):
in str(excinfo_skill.value)
)
- @pytest.mark.asyncio
- async def test_connector_auth_header_correct_app_id_and_service_url_should_validate(
- self,
- ):
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", ""
- )
- result = await JwtTokenValidation.validate_auth_header(
- header, credentials, "", "https://webchat.botframework.com/"
- )
-
- result_with_provider = await JwtTokenValidation.validate_auth_header(
- header,
- credentials,
- SimpleChannelProvider(),
- "https://webchat.botframework.com/",
- )
-
- assert result
- assert result_with_provider
-
- @pytest.mark.asyncio
- async def test_connector_auth_header_with_different_bot_app_id_should_not_validate(
- self,
- ):
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "00000000-0000-0000-0000-000000000000", ""
- )
- with pytest.raises(Exception) as excinfo:
- await JwtTokenValidation.validate_auth_header(
- header, credentials, "", "https://webchat.botframework.com/"
- )
- assert "Unauthorized" in str(excinfo.value)
-
- with pytest.raises(Exception) as excinfo2:
- await JwtTokenValidation.validate_auth_header(
- header,
- credentials,
- SimpleChannelProvider(),
- "https://webchat.botframework.com/",
- )
- assert "Unauthorized" in str(excinfo2.value)
-
- @pytest.mark.asyncio
- async def test_connector_auth_header_and_no_credential_should_not_validate(self):
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider("", "")
- with pytest.raises(Exception) as excinfo:
- await JwtTokenValidation.validate_auth_header(
- header, credentials, "", "https://webchat.botframework.com/"
- )
- assert "Unauthorized" in str(excinfo.value)
-
- with pytest.raises(Exception) as excinfo2:
- await JwtTokenValidation.validate_auth_header(
- header,
- credentials,
- SimpleChannelProvider(),
- "https://webchat.botframework.com/",
- )
- assert "Unauthorized" in str(excinfo2.value)
+ # @pytest.mark.asyncio
+ # async def test_connector_auth_header_correct_app_id_and_service_url_should_validate(
+ # self,
+ # ):
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "", ""
+ # )
+ # result = await JwtTokenValidation.validate_auth_header(
+ # header, credentials, "", "https://webchat.botframework.com/"
+ # )
+ #
+ # result_with_provider = await JwtTokenValidation.validate_auth_header(
+ # header,
+ # credentials,
+ # SimpleChannelProvider(),
+ # "https://webchat.botframework.com/",
+ # )
+ #
+ # assert result
+ # assert result_with_provider
+
+ # @pytest.mark.asyncio
+ # async def test_connector_auth_header_with_different_bot_app_id_should_not_validate(
+ # self,
+ # ):
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "00000000-0000-0000-0000-000000000000", ""
+ # )
+ # with pytest.raises(Exception) as excinfo:
+ # await JwtTokenValidation.validate_auth_header(
+ # header, credentials, "", "https://webchat.botframework.com/"
+ # )
+ # assert "Unauthorized" in str(excinfo.value)
+ #
+ # with pytest.raises(Exception) as excinfo2:
+ # await JwtTokenValidation.validate_auth_header(
+ # header,
+ # credentials,
+ # SimpleChannelProvider(),
+ # "https://webchat.botframework.com/",
+ # )
+ # assert "Unauthorized" in str(excinfo2.value)
+
+ # @pytest.mark.asyncio
+ # async def test_connector_auth_header_and_no_credential_should_not_validate(self):
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider("", "")
+ # with pytest.raises(Exception) as excinfo:
+ # await JwtTokenValidation.validate_auth_header(
+ # header, credentials, "", "https://webchat.botframework.com/"
+ # )
+ # assert "Unauthorized" in str(excinfo.value)
+ #
+ # with pytest.raises(Exception) as excinfo2:
+ # await JwtTokenValidation.validate_auth_header(
+ # header,
+ # credentials,
+ # SimpleChannelProvider(),
+ # "https://webchat.botframework.com/",
+ # )
+ # assert "Unauthorized" in str(excinfo2.value)
@pytest.mark.asyncio
async def test_empty_header_and_no_credential_should_throw(self):
@@ -198,99 +198,99 @@ async def test_empty_header_and_no_credential_should_throw(self):
)
assert "auth_header" in str(excinfo2.value)
- @pytest.mark.asyncio
- async def test_emulator_msa_header_correct_app_id_and_service_url_should_validate(
- self,
- ):
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", ""
- )
- result = await JwtTokenValidation.validate_auth_header(
- header, credentials, "", "https://webchat.botframework.com/"
- )
-
- result_with_provider = await JwtTokenValidation.validate_auth_header(
- header,
- credentials,
- SimpleChannelProvider(),
- "https://webchat.botframework.com/",
- )
-
- assert result
- assert result_with_provider
-
- @pytest.mark.asyncio
- async def test_emulator_msa_header_and_no_credential_should_not_validate(self):
- # pylint: disable=protected-access
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "00000000-0000-0000-0000-000000000000", ""
- )
- with pytest.raises(Exception) as excinfo:
- await JwtTokenValidation.validate_auth_header(header, credentials, "", None)
- assert "Unauthorized" in str(excinfo._excinfo)
-
- with pytest.raises(Exception) as excinfo2:
- await JwtTokenValidation.validate_auth_header(
- header, credentials, SimpleChannelProvider(), None
- )
- assert "Unauthorized" in str(excinfo2._excinfo)
+ # @pytest.mark.asyncio
+ # async def test_emulator_msa_header_correct_app_id_and_service_url_should_validate(
+ # self,
+ # ):
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "", ""
+ # )
+ # result = await JwtTokenValidation.validate_auth_header(
+ # header, credentials, "", "https://webchat.botframework.com/"
+ # )
+ #
+ # result_with_provider = await JwtTokenValidation.validate_auth_header(
+ # header,
+ # credentials,
+ # SimpleChannelProvider(),
+ # "https://webchat.botframework.com/",
+ # )
+ #
+ # assert result
+ # assert result_with_provider
+
+ # @pytest.mark.asyncio
+ # async def test_emulator_msa_header_and_no_credential_should_not_validate(self):
+ # # pylint: disable=protected-access
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "00000000-0000-0000-0000-000000000000", ""
+ # )
+ # with pytest.raises(Exception) as excinfo:
+ # await JwtTokenValidation.validate_auth_header(header, credentials, "", None)
+ # assert "Unauthorized" in str(excinfo._excinfo)
+ #
+ # with pytest.raises(Exception) as excinfo2:
+ # await JwtTokenValidation.validate_auth_header(
+ # header, credentials, SimpleChannelProvider(), None
+ # )
+ # assert "Unauthorized" in str(excinfo2._excinfo)
# Tests with a valid Token and service url; and ensures that Service url is added to Trusted service url list.
- @pytest.mark.asyncio
- async def test_channel_msa_header_valid_service_url_should_be_trusted(self):
- activity = Activity(
- service_url="https://smba.trafficmanager.net/amer-client-ss.msg/"
- )
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", ""
- )
-
- await JwtTokenValidation.authenticate_request(activity, header, credentials)
-
- assert AppCredentials.is_trusted_service(
- "https://smba.trafficmanager.net/amer-client-ss.msg/"
- )
-
- @pytest.mark.asyncio
- # Tests with a valid Token and invalid service url and ensures that Service url is NOT added to
- # Trusted service url list.
- async def test_channel_msa_header_invalid_service_url_should_not_be_trusted(self):
- activity = Activity(service_url="https://webchat.botframework.com/")
- header = (
- "Bearer "
- + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- ).get_access_token()
- )
- credentials = SimpleCredentialProvider(
- "7f74513e-6f96-4dbc-be9d-9a81fea22b88", ""
- )
-
- with pytest.raises(Exception) as excinfo:
- await JwtTokenValidation.authenticate_request(activity, header, credentials)
- assert "Unauthorized" in str(excinfo.value)
-
- assert not MicrosoftAppCredentials.is_trusted_service(
- "https://webchat.botframework.com/"
- )
+ # @pytest.mark.asyncio
+ # async def test_channel_msa_header_valid_service_url_should_be_trusted(self):
+ # activity = Activity(
+ # service_url="https://smba.trafficmanager.net/amer-client-ss.msg/"
+ # )
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "", ""
+ # )
+ #
+ # await JwtTokenValidation.authenticate_request(activity, header, credentials)
+ #
+ # assert AppCredentials.is_trusted_service(
+ # "https://smba.trafficmanager.net/amer-client-ss.msg/"
+ # )
+
+ # @pytest.mark.asyncio
+ # # Tests with a valid Token and invalid service url and ensures that Service url is NOT added to
+ # # Trusted service url list.
+ # async def test_channel_msa_header_invalid_service_url_should_not_be_trusted(self):
+ # activity = Activity(service_url="https://webchat.botframework.com/")
+ # header = (
+ # "Bearer "
+ # MicrosoftAppCredentials(
+ # "", ""
+ # ).get_access_token()
+ # )
+ # credentials = SimpleCredentialProvider(
+ # "7f74513e-6f96-4dbc-be9d-9a81fea22b88", ""
+ # )
+ #
+ # with pytest.raises(Exception) as excinfo:
+ # await JwtTokenValidation.authenticate_request(activity, header, credentials)
+ # assert "Unauthorized" in str(excinfo.value)
+ #
+ # assert not MicrosoftAppCredentials.is_trusted_service(
+ # "https://webchat.botframework.com/"
+ # )
@pytest.mark.asyncio
# Tests with a valid Token and invalid service url and ensures that Service url is NOT added to
@@ -318,23 +318,23 @@ async def test_channel_authentication_disabled_and_skill_should_be_anonymous(sel
== AuthenticationConstants.ANONYMOUS_SKILL_APP_ID
)
- @pytest.mark.asyncio
- async def test_channel_msa_header_from_user_specified_tenant(self):
- activity = Activity(
- service_url="https://smba.trafficmanager.net/amer-client-ss.msg/"
- )
- header = "Bearer " + MicrosoftAppCredentials(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F", "microsoft.com"
- ).get_access_token(True)
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", ""
- )
-
- claims = await JwtTokenValidation.authenticate_request(
- activity, header, credentials
- )
-
- assert claims.get_claim_value("tid") == "72f988bf-86f1-41af-91ab-2d7cd011db47"
+ # @pytest.mark.asyncio
+ # async def test_channel_msa_header_from_user_specified_tenant(self):
+ # activity = Activity(
+ # service_url="https://smba.trafficmanager.net/amer-client-ss.msg/"
+ # )
+ # header = "Bearer " MicrosoftAppCredentials(
+ # "", "", "microsoft.com"
+ # ).get_access_token(True)
+ # credentials = SimpleCredentialProvider(
+ # "", ""
+ # )
+ #
+ # claims = await JwtTokenValidation.authenticate_request(
+ # activity, header, credentials
+ # )
+ #
+ # assert claims.get_claim_value("tid") == "72f988bf-86f1-41af-91ab-2d7cd011db47"
@pytest.mark.asyncio
# Tests with no authentication header and makes sure the service URL is not added to the trusted list.
@@ -367,43 +367,42 @@ async def test_channel_authentication_disabled_service_url_should_not_be_trusted
"https://webchat.botframework.com/"
)
- @pytest.mark.asyncio
- async def test_emulator_auth_header_correct_app_id_and_service_url_with_gov_channel_service_should_validate(
- self,
- ):
- await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", # emulator creds
- "2.30Vs3VQLKt974F",
- GovernmentConstants.CHANNEL_SERVICE,
- )
-
- await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", # emulator creds
- "2.30Vs3VQLKt974F",
- SimpleChannelProvider(GovernmentConstants.CHANNEL_SERVICE),
- )
-
- @pytest.mark.asyncio
- async def test_emulator_auth_header_correct_app_id_and_service_url_with_private_channel_service_should_validate(
- self,
- ):
- await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", # emulator creds
- "2.30Vs3VQLKt974F",
- "TheChannel",
- )
-
- await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", # emulator creds
- "2.30Vs3VQLKt974F",
- SimpleChannelProvider("TheChannel"),
- )
+ # @pytest.mark.asyncio
+ # async def test_emulator_auth_header_correct_app_id_and_service_url_with_gov_channel_service_should_validate(
+ # self,
+ # ):
+ # await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
+ # "", # emulator creds
+ # "",
+ # GovernmentConstants.CHANNEL_SERVICE,
+ # )
+ #
+ # await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
+ # "", # emulator creds
+ # "",
+ # SimpleChannelProvider(GovernmentConstants.CHANNEL_SERVICE),
+ # )
+
+ # @pytest.mark.asyncio
+ # async def
+ # test_emulator_auth_header_correct_app_id_and_service_url_with_private_channel_service_should_validate(
+ # self,
+ # ):
+ # await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
+ # "", # emulator creds
+ # "",
+ # "TheChannel",
+ # )
+ #
+ # await jwt_token_validation_validate_auth_header_with_channel_service_succeeds(
+ # "", # emulator creds
+ # "",
+ # SimpleChannelProvider("TheChannel"),
+ # )
@pytest.mark.asyncio
async def test_government_channel_validation_succeeds(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity(
@@ -422,9 +421,7 @@ async def test_government_channel_validation_no_authentication_fails(self):
@pytest.mark.asyncio
async def test_government_channel_validation_no_issuer_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity({"peanut": "peanut"}, True), credentials
@@ -433,32 +430,28 @@ async def test_government_channel_validation_no_issuer_fails(self):
@pytest.mark.asyncio
async def test_government_channel_validation_wrong_issuer_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity({"iss": "peanut"}, True), credentials
)
assert "Unauthorized" in str(excinfo.value)
- @pytest.mark.asyncio
- async def test_government_channel_validation_no_audience_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
- with pytest.raises(Exception) as excinfo:
- await GovernmentChannelValidation.validate_identity(
- ClaimsIdentity({"iss": "https://api.botframework.us"}, True),
- credentials,
- )
- assert "Unauthorized" in str(excinfo.value)
+ # @pytest.mark.asyncio
+ # async def test_government_channel_validation_no_audience_fails(self):
+ # credentials = SimpleCredentialProvider(
+ # "", ""
+ # )
+ # with pytest.raises(Exception) as excinfo:
+ # await GovernmentChannelValidation.validate_identity(
+ # ClaimsIdentity({"iss": "https://api.botframework.us"}, True),
+ # credentials,
+ # )
+ # assert "Unauthorized" in str(excinfo.value)
@pytest.mark.asyncio
async def test_government_channel_validation_wrong_audience_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity(
@@ -470,9 +463,7 @@ async def test_government_channel_validation_wrong_audience_fails(self):
@pytest.mark.asyncio
async def test_enterprise_channel_validation_succeeds(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
await EnterpriseChannelValidation.validate_identity(
ClaimsIdentity(
@@ -491,9 +482,7 @@ async def test_enterprise_channel_validation_no_authentication_fails(self):
@pytest.mark.asyncio
async def test_enterprise_channel_validation_no_issuer_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await EnterpriseChannelValidation.validate_identity(
ClaimsIdentity({"peanut": "peanut"}, True), credentials
@@ -502,9 +491,7 @@ async def test_enterprise_channel_validation_no_issuer_fails(self):
@pytest.mark.asyncio
async def test_enterprise_channel_validation_wrong_issuer_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await EnterpriseChannelValidation.validate_identity(
ClaimsIdentity({"iss": "peanut"}, True), credentials
@@ -513,9 +500,7 @@ async def test_enterprise_channel_validation_wrong_issuer_fails(self):
@pytest.mark.asyncio
async def test_enterprise_channel_validation_no_audience_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity({"iss": "https://api.botframework.com"}, True),
@@ -525,9 +510,7 @@ async def test_enterprise_channel_validation_no_audience_fails(self):
@pytest.mark.asyncio
async def test_enterprise_channel_validation_wrong_audience_fails(self):
- credentials = SimpleCredentialProvider(
- "2cd87869-38a0-4182-9251-d056e8f0ac24", "2.30Vs3VQLKt974F"
- )
+ credentials = SimpleCredentialProvider("", "")
with pytest.raises(Exception) as excinfo:
await GovernmentChannelValidation.validate_identity(
ClaimsIdentity(
diff --git a/libraries/botframework-streaming/README.rst b/libraries/botframework-streaming/README.rst
index 49595961f..35838e289 100644
--- a/libraries/botframework-streaming/README.rst
+++ b/libraries/botframework-streaming/README.rst
@@ -1,7 +1,7 @@
-===============================
+=================================
BotFramework-Streaming for Python
-===============================
+=================================
.. image:: https://fuselabs.visualstudio.com/SDK_v4/_apis/build/status/Python/SDK_v4-Python-CI?branchName=master
:target: https://fuselabs.visualstudio.com/SDK_v4/_apis/build/status/Python/SDK_v4-Python-CI
@@ -16,11 +16,10 @@ Streaming Extensions libraries for BotFramework.
How to Install
==============
-.. code-block:: python
+.. code-block:: bash
pip install botframework-streaming
-
Documentation/Wiki
==================
diff --git a/libraries/botframework-streaming/botframework/streaming/about.py b/libraries/botframework-streaming/botframework/streaming/about.py
index 9048bf6e5..78ae10a20 100644
--- a/libraries/botframework-streaming/botframework/streaming/about.py
+++ b/libraries/botframework-streaming/botframework/streaming/about.py
@@ -5,7 +5,7 @@
__title__ = "botframework-streaming"
__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+ os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
)
__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
__author__ = "Microsoft"
diff --git a/libraries/botframework-streaming/botframework/streaming/streaming_request.py b/libraries/botframework-streaming/botframework/streaming/streaming_request.py
index 6157a04d6..232446cb4 100644
--- a/libraries/botframework-streaming/botframework/streaming/streaming_request.py
+++ b/libraries/botframework-streaming/botframework/streaming/streaming_request.py
@@ -34,7 +34,10 @@ def create_request(
if not method:
return None
- request = StreamingRequest(verb=method, path=path,)
+ request = StreamingRequest(
+ verb=method,
+ path=path,
+ )
if body:
request.add_stream(body)
diff --git a/libraries/botframework-streaming/requirements.txt b/libraries/botframework-streaming/requirements.txt
index 7f973ed8c..004ce4c73 100644
--- a/libraries/botframework-streaming/requirements.txt
+++ b/libraries/botframework-streaming/requirements.txt
@@ -1,3 +1,3 @@
-msrest==0.6.10
-botframework-connector>=4.14.0
-botbuilder-schema>=4.14.0
\ No newline at end of file
+msrest==0.6.*
+botframework-connector>=4.15.0
+botbuilder-schema>=4.15.0
\ No newline at end of file
diff --git a/libraries/botframework-streaming/setup.py b/libraries/botframework-streaming/setup.py
index 316d04e34..9a5f06e20 100644
--- a/libraries/botframework-streaming/setup.py
+++ b/libraries/botframework-streaming/setup.py
@@ -4,10 +4,10 @@
import os
from setuptools import setup
-VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.14.0"
+VERSION = os.environ["packageVersion"] if "packageVersion" in os.environ else "4.15.0"
REQUIRES = [
- "botbuilder-schema>=4.12.0",
- "botframework-connector>=4.12.0",
+ "botbuilder-schema==4.15.0",
+ "botframework-connector==4.15.0",
]
root = os.path.abspath(os.path.dirname(__file__))
@@ -26,13 +26,21 @@
url=package_info["__uri__"],
author=package_info["__author__"],
description=package_info["__description__"],
- keywords=["BotFrameworkStreaming", "bots", "ai", "botframework", "botframework",],
+ keywords=[
+ "BotFrameworkStreaming",
+ "bots",
+ "ai",
+ "botframework",
+ "botframework",
+ ],
long_description=long_description,
long_description_content_type="text/x-rst",
license=package_info["__license__"],
packages=[
"botframework.streaming",
"botframework.streaming.payloads",
+ "botframework.streaming.payloads.assemblers",
+ "botframework.streaming.payloads.disassemblers",
"botframework.streaming.payloads.models",
"botframework.streaming.payload_transport",
"botframework.streaming.transport",
diff --git a/libraries/functional-tests/functionaltestbot/Dockerfile b/libraries/functional-tests/functionaltestbot/Dockerfile
index 3364fc380..9691bc470 100644
--- a/libraries/functional-tests/functionaltestbot/Dockerfile
+++ b/libraries/functional-tests/functionaltestbot/Dockerfile
@@ -1,7 +1,7 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
-FROM tiangolo/uwsgi-nginx-flask:python3.6
+FROM mcr.microsoft.com/oryx/python:3.10
RUN mkdir /functionaltestbot
diff --git a/libraries/functional-tests/functionaltestbot/flask_bot_app/default_config.py b/libraries/functional-tests/functionaltestbot/flask_bot_app/default_config.py
index 96c277e09..95a060d12 100644
--- a/libraries/functional-tests/functionaltestbot/flask_bot_app/default_config.py
+++ b/libraries/functional-tests/functionaltestbot/flask_bot_app/default_config.py
@@ -5,7 +5,7 @@
class DefaultConfig:
- """ Bot Configuration """
+ """Bot Configuration"""
PORT: int = 3978
APP_ID: str = environ.get("MicrosoftAppId", "")
diff --git a/libraries/functional-tests/functionaltestbot/functionaltestbot/config.py b/libraries/functional-tests/functionaltestbot/functionaltestbot/config.py
index a3bd72174..e79075c24 100644
--- a/libraries/functional-tests/functionaltestbot/functionaltestbot/config.py
+++ b/libraries/functional-tests/functionaltestbot/functionaltestbot/config.py
@@ -6,7 +6,7 @@
class DefaultConfig:
- """ Bot Configuration """
+ """Bot Configuration"""
PORT = 443
APP_ID = os.environ.get("MicrosoftAppId", "")
diff --git a/libraries/functional-tests/requirements.txt b/libraries/functional-tests/requirements.txt
index b1c2f0a5d..698a44df0 100644
--- a/libraries/functional-tests/requirements.txt
+++ b/libraries/functional-tests/requirements.txt
@@ -1,2 +1,2 @@
-requests==2.23.0
+requests==2.27.1
aiounittest==1.3.0
diff --git a/libraries/functional-tests/slacktestbot/config.py b/libraries/functional-tests/slacktestbot/config.py
index 73916b758..9271d8422 100644
--- a/libraries/functional-tests/slacktestbot/config.py
+++ b/libraries/functional-tests/slacktestbot/config.py
@@ -6,7 +6,7 @@
class DefaultConfig:
- """ Bot Configuration """
+ """Bot Configuration"""
PORT = 3978
diff --git a/libraries/functional-tests/tests/test_slack_client.py b/libraries/functional-tests/tests/test_slack_client.py
index cc5abd74d..ab2a9ca90 100644
--- a/libraries/functional-tests/tests/test_slack_client.py
+++ b/libraries/functional-tests/tests/test_slack_client.py
@@ -33,7 +33,9 @@ async def _receive_message_async(self) -> str:
f"{self._slack_url_base}/conversations.history?token="
f"{self._slack_bot_token}&channel={self._slack_channel}"
)
- response = requests.get(url,)
+ response = requests.get(
+ url,
+ )
last_message = response.json()["messages"][0]["text"]
time.sleep(1)
diff --git a/libraries/swagger/package-lock.json b/libraries/swagger/package-lock.json
index 53f2e2d4a..f9a8accd5 100644
--- a/libraries/swagger/package-lock.json
+++ b/libraries/swagger/package-lock.json
@@ -14,11 +14,20 @@
}
},
"ansi-regex": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
- "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true
},
+ "ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "dev": true,
+ "requires": {
+ "color-convert": "^1.9.0"
+ }
+ },
"autorest": {
"version": "3.0.5165",
"resolved": "https://registry.npmjs.org/autorest/-/autorest-3.0.5165.tgz",
@@ -26,9 +35,9 @@
"dev": true
},
"balanced-match": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
- "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true
},
"brace-expansion": {
@@ -42,57 +51,58 @@
}
},
"camelcase": {
- "version": "5.2.0",
- "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz",
- "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==",
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
+ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
"dev": true
},
+ "chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ }
+ },
"cliui": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz",
- "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==",
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
+ "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
"dev": true,
"requires": {
- "string-width": "^2.1.1",
- "strip-ansi": "^4.0.0",
- "wrap-ansi": "^2.0.0"
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.0",
+ "wrap-ansi": "^6.2.0"
}
},
- "code-point-at": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz",
- "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=",
- "dev": true
+ "color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "dev": true,
+ "requires": {
+ "color-name": "1.1.3"
+ }
},
- "colors": {
- "version": "1.2.4",
- "resolved": "https://registry.npmjs.org/colors/-/colors-1.2.4.tgz",
- "integrity": "sha512-6Y+iBnWmXL+AWtlOp2Vr6R2w5MUlNJRwR0ShVFaAb1CqWzhPOpQg4L0jxD+xpw/Nc8QJwaq3KM79QUCriY8CWQ==",
+ "color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"dev": true
},
"concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
- "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true
},
- "cross-spawn": {
- "version": "6.0.5",
- "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
- "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
- "dev": true,
- "requires": {
- "nice-try": "^1.0.4",
- "path-key": "^2.0.1",
- "semver": "^5.5.0",
- "shebang-command": "^1.2.0",
- "which": "^1.2.9"
- }
- },
"decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
- "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=",
+ "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
"dev": true
},
"dotnet-2.0.0": {
@@ -101,416 +111,224 @@
"integrity": "sha512-KDbUncVUhwkJH2wjL9gbUWQ5NcZIe+PFEI0CGTMtX5TImFG6Nlt9CABVGBBG+oWf13zLARaBVenkD20moz1NPw==",
"dev": true
},
- "end-of-stream": {
- "version": "1.4.1",
- "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz",
- "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==",
- "dev": true,
- "requires": {
- "once": "^1.4.0"
- }
+ "emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true
},
- "execa": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz",
- "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==",
- "dev": true,
- "requires": {
- "cross-spawn": "^6.0.0",
- "get-stream": "^4.0.0",
- "is-stream": "^1.1.0",
- "npm-run-path": "^2.0.0",
- "p-finally": "^1.0.0",
- "signal-exit": "^3.0.0",
- "strip-eof": "^1.0.0"
- }
+ "escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "dev": true
},
"find-up": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz",
- "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==",
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
"dev": true,
"requires": {
- "locate-path": "^3.0.0"
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
}
},
"get-caller-file": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
- "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==",
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true
},
- "get-stream": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz",
- "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==",
- "dev": true,
- "requires": {
- "pump": "^3.0.0"
- }
- },
- "invert-kv": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz",
- "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==",
+ "has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
"dev": true
},
"is-fullwidth-code-point": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
- "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
- "dev": true
- },
- "is-stream": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
- "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=",
- "dev": true
- },
- "isexe": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
- "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true
},
- "lcid": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz",
- "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==",
- "dev": true,
- "requires": {
- "invert-kv": "^2.0.0"
- }
- },
"locate-path": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
- "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==",
- "dev": true,
- "requires": {
- "p-locate": "^3.0.0",
- "path-exists": "^3.0.0"
- }
- },
- "map-age-cleaner": {
- "version": "0.1.3",
- "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz",
- "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==",
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
"dev": true,
"requires": {
- "p-defer": "^1.0.0"
+ "p-locate": "^4.1.0"
}
},
- "mem": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/mem/-/mem-4.2.0.tgz",
- "integrity": "sha512-5fJxa68urlY0Ir8ijatKa3eRz5lwXnRCTvo9+TbTGAuTFJOwpGcY0X05moBd0nW45965Njt4CDI2GFQoG8DvqA==",
- "dev": true,
- "requires": {
- "map-age-cleaner": "^0.1.1",
- "mimic-fn": "^2.0.0",
- "p-is-promise": "^2.0.0"
- }
- },
- "mimic-fn": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.0.0.tgz",
- "integrity": "sha512-jbex9Yd/3lmICXwYT6gA/j2mNQGU48wCh/VzRd+/Y/PjYQtlg1gLMdZqvu9s/xH7qKvngxRObl56XZR609IMbA==",
- "dev": true
- },
"minimatch": {
- "version": "3.0.4",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
- "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.5.tgz",
+ "integrity": "sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw==",
"dev": true,
"requires": {
"brace-expansion": "^1.1.7"
}
},
- "nice-try": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",
- "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
- "dev": true
- },
- "npm-run-path": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz",
- "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=",
- "dev": true,
- "requires": {
- "path-key": "^2.0.0"
- }
- },
- "number-is-nan": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz",
- "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=",
- "dev": true
- },
- "once": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
- "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
- "dev": true,
- "requires": {
- "wrappy": "1"
- }
- },
- "os-locale": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz",
- "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==",
- "dev": true,
- "requires": {
- "execa": "^1.0.0",
- "lcid": "^2.0.0",
- "mem": "^4.0.0"
- }
- },
- "p-defer": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz",
- "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=",
- "dev": true
- },
- "p-finally": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
- "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=",
- "dev": true
- },
- "p-is-promise": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.0.0.tgz",
- "integrity": "sha512-pzQPhYMCAgLAKPWD2jC3Se9fEfrD9npNos0y150EeqZll7akhEgGhTW/slB6lHku8AvYGiJ+YJ5hfHKePPgFWg==",
- "dev": true
- },
"p-limit": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz",
- "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
"dev": true,
"requires": {
"p-try": "^2.0.0"
}
},
"p-locate": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz",
- "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==",
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
"dev": true,
"requires": {
- "p-limit": "^2.0.0"
+ "p-limit": "^2.2.0"
}
},
"p-try": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.1.0.tgz",
- "integrity": "sha512-H2RyIJ7+A3rjkwKC2l5GGtU4H1vkxKCAGsWasNVd0Set+6i4znxbWy6/j16YDPJDWxhsgZiKAstMEP8wCdSpjA==",
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
"dev": true
},
"path-exists": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
- "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=",
- "dev": true
- },
- "path-key": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
- "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=",
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
"dev": true
},
- "pump": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
- "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
- "dev": true,
- "requires": {
- "end-of-stream": "^1.1.0",
- "once": "^1.3.1"
- }
- },
"replace": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/replace/-/replace-1.1.0.tgz",
- "integrity": "sha512-0k9rtPG0MUDfJj77XtMCSJKOPdzSwVwM79ZQ6lZuFjqqXrQAMKIMp0g7/8GDAzeERxdktV/LzqbMtJ3yxB23lg==",
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/replace/-/replace-1.2.2.tgz",
+ "integrity": "sha512-C4EDifm22XZM2b2JOYe6Mhn+lBsLBAvLbK8drfUQLTfD1KYl/n3VaW/CDju0Ny4w3xTtegBpg8YNSpFJPUDSjA==",
"dev": true,
"requires": {
- "colors": "1.2.4",
- "minimatch": "3.0.4",
- "yargs": "12.0.5"
+ "chalk": "2.4.2",
+ "minimatch": "3.0.5",
+ "yargs": "^15.3.1"
}
},
"require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
- "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true
},
"require-main-filename": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz",
- "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=",
- "dev": true
- },
- "semver": {
- "version": "5.6.0",
- "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz",
- "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
+ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
"dev": true
},
"set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
- "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=",
- "dev": true
- },
- "shebang-command": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz",
- "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=",
- "dev": true,
- "requires": {
- "shebang-regex": "^1.0.0"
- }
- },
- "shebang-regex": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz",
- "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=",
- "dev": true
- },
- "signal-exit": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",
- "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=",
+ "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
"dev": true
},
"string-width": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
- "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"requires": {
- "is-fullwidth-code-point": "^2.0.0",
- "strip-ansi": "^4.0.0"
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
}
},
"strip-ansi": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
- "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"requires": {
- "ansi-regex": "^3.0.0"
+ "ansi-regex": "^5.0.1"
}
},
- "strip-eof": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
- "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=",
- "dev": true
- },
- "which": {
- "version": "1.3.1",
- "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
- "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
+ "supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
"dev": true,
"requires": {
- "isexe": "^2.0.0"
+ "has-flag": "^3.0.0"
}
},
"which-module": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
- "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=",
+ "integrity": "sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==",
"dev": true
},
"wrap-ansi": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
- "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
+ "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
"dev": true,
"requires": {
- "string-width": "^1.0.1",
- "strip-ansi": "^3.0.1"
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
},
"dependencies": {
- "ansi-regex": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
- "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
- "dev": true
- },
- "is-fullwidth-code-point": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
- "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"requires": {
- "number-is-nan": "^1.0.0"
+ "color-convert": "^2.0.1"
}
},
- "string-width": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
- "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"requires": {
- "code-point-at": "^1.0.0",
- "is-fullwidth-code-point": "^1.0.0",
- "strip-ansi": "^3.0.0"
+ "color-name": "~1.1.4"
}
},
- "strip-ansi": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
- "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
- "dev": true,
- "requires": {
- "ansi-regex": "^2.0.0"
- }
+ "color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
}
}
},
- "wrappy": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
- "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
- "dev": true
- },
"y18n": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz",
- "integrity": "sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ==",
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
+ "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
"dev": true
},
"yargs": {
- "version": "12.0.5",
- "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz",
- "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==",
+ "version": "15.4.1",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
+ "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
"dev": true,
"requires": {
- "cliui": "^4.0.0",
+ "cliui": "^6.0.0",
"decamelize": "^1.2.0",
- "find-up": "^3.0.0",
- "get-caller-file": "^1.0.1",
- "os-locale": "^3.0.0",
+ "find-up": "^4.1.0",
+ "get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
- "require-main-filename": "^1.0.1",
+ "require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
- "string-width": "^2.0.0",
+ "string-width": "^4.2.0",
"which-module": "^2.0.0",
- "y18n": "^3.2.1 || ^4.0.0",
- "yargs-parser": "^11.1.1"
+ "y18n": "^4.0.0",
+ "yargs-parser": "^18.1.2"
}
},
"yargs-parser": {
- "version": "11.1.1",
- "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz",
- "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==",
+ "version": "18.1.3",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
+ "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
"dev": true,
"requires": {
"camelcase": "^5.0.0",
diff --git a/libraries/swagger/package.json b/libraries/swagger/package.json
index 140121b5c..da19c0f8f 100644
--- a/libraries/swagger/package.json
+++ b/libraries/swagger/package.json
@@ -7,7 +7,7 @@
"devDependencies": {
"@microsoft.azure/autorest.python": "^4.0.67",
"autorest": "^3.0.5165",
- "replace": "^1.0.0"
+ "replace": "^1.2.2"
},
"dependencies": {}
}
diff --git a/pipelines/botbuilder-python-ci.yml b/pipelines/botbuilder-python-ci.yml
index 00176dbd9..61de37a83 100644
--- a/pipelines/botbuilder-python-ci.yml
+++ b/pipelines/botbuilder-python-ci.yml
@@ -15,7 +15,7 @@ jobs:
- job: Build
#Multi-configuration and multi-agent job options are not exported to YAML. Configure these options using documentation guidance: https://docs.microsoft.com/vsts/pipelines/process/phases
pool:
- name: Hosted Ubuntu 1604
+ vmImage: 'ubuntu-latest'
strategy:
matrix:
@@ -54,7 +54,7 @@ jobs:
pip install -r ./libraries/botbuilder-ai/tests/requirements.txt
pip install coveralls
pip install pylint==2.4.4
- pip install black==19.10b0
+ pip install black==22.3.0
displayName: 'Install dependencies'
- script: |
@@ -104,3 +104,6 @@ jobs:
Get-ChildItem -Path "$(Build.SourcesDirectory)" -Include "*coverage*" | Copy-Item -Destination "$(Build.ArtifactStagingDirectory)/CodeCoverage"
displayName: 'Copy .coverage Files to CodeCoverage folder'
continueOnError: true
+
+ - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
+ displayName: 'Component Detection'
diff --git a/specs/DailyBuildProposal.md b/specs/DailyBuildProposal.md
deleted file mode 100644
index f68e154ad..000000000
--- a/specs/DailyBuildProposal.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# Daily Build Propsal for .Net BotBuilder SDK
-
-This proposal describes our plan to publish daily builds for consumption. The goals of this are:
-1. Make it easy for developers (1P and 3P) to consume our daily builds.
-2. Exercise our release process frequently, so issues don't arise at critical times.
-3. Meet Developers where they are.
-
-Use the [ASP.Net Team](https://github.com/dotnet/aspnetcore/blob/master/docs/DailyBuilds.md) as inspiration, and draft off the work they do.
-
-# Versioning
-Move to Python suggested versioning for dailies defined in [PEP440](https://www.python.org/dev/peps/pep-0440/#developmental-releases).
-
-The tags we use for preview versions are:
-```
-..dev{incrementing value}
--rc{incrementing value}
-```
-
-# Daily Builds
-All our Python wheel packages would be pushed to the SDK_Public project at [fuselabs.visualstudio.com](https://fuselabs.visualstudio.com).
-
- Note: Only a public project on Devops can have a public feed. The public project on our Enterprise Tenant is [SDK_Public](https://fuselabs.visualstudio.com/SDK_Public).
-
-This means developers could add this feed their projects by adding the following command on a pip conf file, or in the pip command itself:
-
-```bash
-extra-index-url=https://pkgs.dev.azure.com/ConversationalAI/BotFramework/_packaging/SDK%40Local/pypi/simple/
-```
-
-## Debugging
-To debug daily builds in VSCode:
-* In the launch.json configuration file set the option `"justMyCode": false`.
-
-## Daily Build Lifecyle
-Daily builds older than 90 days are automatically deleted.
-
-# Summary - Weekly Builds
-Once per week, preferably on a Monday, a daily build is pushed to PyPI test. This build happens from 'main', the same as a standard daily build. This serves 2 purposes:
-
-1. Keeps PyPI "Fresh" for people that don't want daily builds.
-2. Keeps the release pipelines active and working, and prevents issues.
-
-These builds will have the "-dev" tag and ARE the the daily build.
-
-**This release pipeline should be the EXACT same pipeline that releases our production bits.**
-
-Weekly builds older than 1 year should be automatically delisted.
-
-## Adding packages to the feed
-Our existing Release pipelines would add packages to the feed.
-# Migration from MyGet
-
-1. Initially, our daily builds should go to both MyGet and Azure Devops.
-2. Our docs are updated once builds are in both locations.
-3. Towards the end of 2020, we stop publising to MyGet.
-
-# Containers
-ASP.Net and .Net Core 5 also publish a container to [Docker Hub](https://hub.docker.com/_/microsoft-dotnet-nightly-aspnet/) as part of their daily feed. We should consider that, along with our samples, in the next iteration of this work.
diff --git a/tests/experimental/101.corebot-bert-bidaf/Dockerfile_bot b/tests/experimental/101.corebot-bert-bidaf/Dockerfile_bot
deleted file mode 100644
index 1ce39d22e..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/Dockerfile_bot
+++ /dev/null
@@ -1,35 +0,0 @@
-FROM tiangolo/uwsgi-nginx-flask:python3.6
-
-# Setup for nginx
-RUN mkdir -p /home/LogFiles \
- && apt update \
- && apt install -y --no-install-recommends vim
-
-EXPOSE 3978
-
-COPY /model /model
-
-# Pytorch very large. Install from wheel.
-RUN wget https://files.pythonhosted.org/packages/69/60/f685fb2cfb3088736bafbc9bdbb455327bdc8906b606da9c9a81bae1c81e/torch-1.1.0-cp36-cp36m-manylinux1_x86_64.whl
-RUN pip3 install torch-1.1.0-cp36-cp36m-manylinux1_x86_64.whl
-
-RUN pip3 install -e /model/
-
-
-COPY ./bot /bot
-
-RUN pip3 install -r /bot/requirements.txt
-
-ENV FLASK_APP=/bot/main.py
-ENV LANG=C.UTF-8
-ENV LC_ALL=C.UTF-8
-ENV PATH ${PATH}:/home/site/wwwroot
-
-WORKDIR bot
-# Initialize models
-
-
-# For Debugging, uncomment the following:
-#ENTRYPOINT ["python3.6", "-c", "import time ; time.sleep(500000)"]
-ENTRYPOINT [ "flask" ]
-CMD [ "run", "--port", "3978", "--host", "0.0.0.0" ]
diff --git a/tests/experimental/101.corebot-bert-bidaf/Dockerfile_model_runtime b/tests/experimental/101.corebot-bert-bidaf/Dockerfile_model_runtime
deleted file mode 100644
index ed777a1d2..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/Dockerfile_model_runtime
+++ /dev/null
@@ -1,29 +0,0 @@
-# https://github.com/tornadoweb/tornado/blob/master/demos/blog/Dockerfile
-FROM python:3.6
-
-# Port the model runtime service will listen on.
-EXPOSE 8880
-
-# Make structure where the models will live.
-RUN mkdir -p /cognitiveModels/bert
-RUN mkdir -p /cognitiveModels/bidaf
-
-# Copy and install models.
-COPY model /model/
-#RUN pip3 install --upgrade pip
-#RUN pip3 install --upgrade nltk
-RUN wget https://files.pythonhosted.org/packages/69/60/f685fb2cfb3088736bafbc9bdbb455327bdc8906b606da9c9a81bae1c81e/torch-1.1.0-cp36-cp36m-manylinux1_x86_64.whl
-RUN pip3 install torch-1.1.0-cp36-cp36m-manylinux1_x86_64.whl
-RUN pip3 install -e /model
-
-# Copy and install model runtime service api.
-COPY model_runtime_svc /model_runtime_svc/
-RUN pip3 install -e /model_runtime_svc
-
-# One time initialization of the models.
-RUN python3 /model_runtime_svc/model_runtime_svc_corebot101/docker_init.py
-RUN rm /model_runtime_svc/model_runtime_svc_corebot101/docker_init.py
-
-WORKDIR /model_runtime_svc
-
-ENTRYPOINT ["python3", "./model_runtime_svc_corebot101/main.py"]
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/NOTICE.md b/tests/experimental/101.corebot-bert-bidaf/NOTICE.md
deleted file mode 100644
index 984258e65..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/NOTICE.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## NOTICE
-
-Please note that while the 101.corebot-bert-bidaf sample is licensed under the MIT license, the sample has dependencies that use other types of licenses.
-
-Since Microsoft does not modify nor distribute these dependencies, it is the sole responsibility of the user to determine the correct/compliant usage of these dependencies. Please refer to the
-[bot requirements](./bot/requirements.txt), [model requirements](./model/setup.py) and [model runtime requirements](./model_runtime_svc/setup.py) for a list of the **direct** dependencies.
-
-Please also note that the sample depends on the `requests` package, which has a dependency `chardet` that uses LGPL license.
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/README.md b/tests/experimental/101.corebot-bert-bidaf/README.md
deleted file mode 100644
index 501f8d600..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/README.md
+++ /dev/null
@@ -1,349 +0,0 @@
-# CoreBot-bert-bidaf
-
-Bot Framework v4 core bot sample demonstrating using open source language models employing the BERT and BiDAF. This is for demonstration purposes only.
-
-## Table of Contents
-- [Overview](#overview)
-- [Terminology](#terminology)
-- [Setup](#setup)
-- [Model Development](#model-development)
-- [Model Runtime Options](#model-runtime-options)
- - [In-Process](#in-process)
- - [Out-of-process to local service](#out-of-process-to-local-service)
- - [Using Docker Containers](#using-docker-containers)
-
-
-## Overview
-This bot has been created using [Bot Framework](https://dev.botframework.com). It demonstrates the following:
-- Train a one layer logistic regression classifier on top of the pretrained BERT model to infer intents.
-- Use locally the ONNX BiDAF pre-trained model to infer entities for the scenario, in this case simple flight booking.
-- Run the bot with the model runtime in-process to the bot.
-- Run the bot with the model runtime external to the bot.
-
-## Terminology
-This document uses the following terminology.
-**Model Development**: Model Development broadly covers gathering data, data processing, training/validation/evaluation and testing. This can also be thought of as model preparation or authoring time.
-**Model Runtime**: The built model which can be used to perform inferences against bot utterances. The model runtime refers to the model and the associated code to perform inferences. The model runtime is used when the bot is running to infer intents and entities.
-**Inference**: Applying the bot utterance to a model yields intents and entities. The intents and entities are the inferences used by the bot.
-
-## Setup
-
-This sample uses the Anaconda environment (which provides Jupyter Lab and other machine learning tools) in order to run.
-
-The following instructions assume using the [Anaconda]() environment (v4.6.11+).
-
-Note: Be sure to install the **64-bit** version of Anaconda for the purposes of this tutorial.
-
-### Create and activate virtual environment
-
-In your local folder, open an **Anaconda prompt** and run the following commands:
-
-```bash
-cd 101.corebot-bert-bidaf
-conda create -n botsample python=3.6 anaconda -y
-conda activate botsample # source conda
-
-# Add extension to handle Jupyter kernel based on the new environemnt.
-pip install ipykernel
-ipython kernel install --user --name=botsample
-
-# Add extension for visual controls to display correctly
-conda install -c conda-forge nodejs -y
-jupyter labextension install @jupyter-widgets/jupyterlab-manager
-```
-
-From here on out, all CLI interactions should occur within the `botsample` Anaconda virtual environment.
-
-### Install models package
-The `models` package contains source to perform model development support and runtime inferencing using the tuned BERT and BiDAF models.
-
-
-```bash
-# Install Pytorch
-conda install -c pytorch pytorch -y
-
-# Install models package using code in sample
-# This will create the python package that contains all the
-# models used in the Jupyter Notebooks and the Bot code.
-cd model
-pip install -e . # Note the '.' after -e
-
-# Verify packages installed
- # On Windows:
- conda list | findstr "corebot pytorch onnx"
-
- # On Linux/etc:
- conda list | grep -e corebot -e pytorch -e onnx
-```
-
-You should see something like:
-```bash
-model-corebot101 0.0.1 dev_0
-onnx 1.5.0 pypi_0 pypi
-onnxruntime 0.4.0 pypi_0 pypi
-pytorch 1.1.0 py3.6_cuda100_cudnn7_1 pytorch
-pytorch-pretrained-bert 0.6.2 pypi_0 pypi
-```
-
-## Model Development
-Model development in this sample involves building a BERT classifier model and is performed in the Juypter Lab environment.
-
-### Training in Jupyter Lab
-Training the model can be performed in Jupyter Lab.
-Within the Anaconda shell, launch Jupyter Lab from the sample directory.
-
-```bash
-# Start JupyterLab from the root of the sample directory
-(botsample) 101.corebot-bert-bidaf> jupyter lab
-
-```
-#### Click on `notebooks` folder in the left hand navigation of JupyterLab
-
-
- Click for screen shot.
- Selecting notebooks folder in Jupyter
-
-
-
-#### Click on `bert_train.ipynb` notebook
-If running the first time, you should select the `botsample` environment.
-
- Click for screen shot.
- Selecting Anaconda `botsample` environment for Jupyter Kernel
-
-
-
-#### Train the model
-
-To build the BERT classifier model, run the Jupyterlab Notebok (Run->**Run All Cells**).
-
-
- Click for screen shot.
- Selecting Model to build folder
-
-
-
-This process may take several minutes. The built model is placed into a directory that will get packaged with the bot during deployment. The sample demonstrates using this package in-process to the bot, our of process in a separate host that performs inferences, and within Jupyter Notebooks.
-
-After running the Jupyter Notebook, the output should resemble something like the following:
-
- Click for screen shot.
- Showing Completed Model Build
-
-
-
-
-
-#### Test the BERT runtime model classification
-Once the model has been built, you can test the model with a separately provided Jupyter Notebook (Run->Run All Cells).
-- Within the `notebooks` folder, select the `bert_model_runtime.ipynb` file.
-- Run the notebook.
-
-[]
-
-- The output shows intents (`Book flight`, `Cancel`) that will be used by the bot.
-
-- Add additional test cases to see how phrases will be inferenced.
-
-- To modify the training data, update the file below. The format of this is compatible with the LUIS schema. When done modifying the training data [re-train the model](#train-the-model) before testing.
- `101.corebot-bert-bidaf/model/model_corebot101/bert/training_data/FlightBooking.json`
-
- [Click to edit Training Data.](./model/model_corebot101/bert/training_data/FlightBooking.json)
-
-> **NOTE**: The default file output location for the tuned BERT model is `/models/bert`.
-
-### Test the BiDAF runtime model classification
-Similarly, you can test the BiDAF model. Note there is no explicit data processing for the bidaf model. The entities detected are configured at runtime in the notebook.
-
-[]
-
-> **NOTE**: The default file output location for the BiDAF model is `/models/bidaf`.
-
-
-
-## Model Runtime Options
-
-The sample can host the model runtime within the bot process or out-of-process in a REST API service. The following sections demonstrate how to do this on the local machine. In addition, the sample provides Dockerfiles to run this sample in containers.
-
-### In-process
-Within an Anaconda environment (bring up a new Anaconda shell and activate your virtual environment if you would like to continue having JupyterLab running in the original shell), install dependencies for the bot:
-```bash
-# Install requirements required for the bot
-(botsample) 101.corebot-bert-bidaf> pip install -r requirements.txt
-```
-> **NOTE**: If `requirements.txt` doesn't install, you may have to stop JupyterLab if it's running.
-
-```bash
-# Run the bot
-(botsample) 101.corebot-bert-bidaf> cd bot
-(botsample) 101.corebot-bert-bidaf\bot> python main.py
-```
-
-
-> **NOTE**: If executing `main.py` with Python above doesn't work, try running Flask directly:
->
-> ```bash
-> # Set FLASK_APP with full path to main.py in the sample directory
-> # On linux, use export instead of set.
-> (botsample) 101.corebot-bert-bidaf> set FLASK_APP=main.py
->
-> # Turn on development
-> (botsample) 101.corebot-bert-bidaf> set FLASK_ENV=development
->
-> # Run flask
-> (botsample) 101.corebot-bert-bidaf> flask run
-> ```
-
-At this point, you can [test the bot](#testing-the-bot-using-bot-framework-emulator).
-
-### Out-of-process to local service
-Sometimes it's helpful to host the model outside the bot's process space and serve inferences from a separate process.
-
-This section builds on the previous section of [In-process](#in-process).
-
-#### Stop any running bot/model runtime processes
-Ensure there are no running bot or model runtimes executing. Hit ^C on any Anaconda shells running flask/bot or the model service runtime (`python main.py`).
-
-#### Modify bot configuration for localhost
-To call the out-of-process REST API, the bot configuration is modified. Edit the following file:
-`101.corebot-bert-bidaf/bot/config.py`
-
-Edit the settings for `USE_MODEL_RUNTIME_SERVICE` and set to `True`.
-
-```python
-class DefaultConfig(object):
- """Bot configuration parameters."""
- # TCP port that the bot listens on (default:3978)
- PORT = 3978
-
- # Azure Application ID (not required if running locally)
- APP_ID = ""
- # Azure Application Password (not required if running locally)
- APP_PASSWORD = ""
-
- # Determines if the bot calls the models in-proc to the bot or call out of process
- # to the service api using a REST API.
- USE_MODEL_RUNTIME_SERVICE = True
- # Host serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_HOST = "localhost"
- # TCP serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_PORT = 8880
-```
-#### Set up model runtime service
-Inside a separate Anaconda shell, activate the `botsample` environment, and install the model runtime service.
-
-```bash
-# Install requirements required for model runtime service
-(botsample) 101.corebot-bert-bidaf> cd model_runtime_svc
-(botsample) 101.corebot-bert-bidaf\model_runtime_svc> pip install -e . # Note the dot after the -e switch
-```
-
-#### Run model runtime service
-To run the model runtime service, execute the following:
-```bash
-# Navigate into the model_runtime_svc_corebot101 folder
-cd model_runtime_svc_corebot101
-
-# From 101.corebot-bert-bidaf\model_runtime_svc\model_runtime_svc_corebot101
-python main.py
-```
-If not already running, create a separate Anaconda shell set to the `botsample` environment and [run the local bot](#local-in-process) as described above. If it was already running, ensure [the configuration changes made above](#modify-bot-configuration) are running.
-
-At this point, you can [test the bot](#testing-the-bot-using-bot-framework-emulator).
-
-### Using Docker Containers
-This sample also demonstrates using Docker and Docker Compose to run a bot and model runtime service on the local host, that communicate together.
-
-> **NOTE**: For Windows: https://hub.docker.com/editions/community/docker-ce-desktop-windows In the configuration dialog make sure the use Linux containers is checked.
-
-
-#### Modify bot configuration for Docker
-To call the out-of-process REST API inside a Docker container, the bot configuration is modified. Edit the following file:
-`101.corebot-bert-bidaf/bot/config.py`
-
-Ensure that the bot configuration is set to serve model predictions remotely by setting `USE_MODEL_RUNTIME_SERVICE` to `True`.
-
-In addition, modify the `MODEL_RUNTIME_SERVICE_HOST` to `api` (previously `localhost`). This will allow the `bot` container to properly address the model `model runtime api` service container.
-
-The resulting `config.py`should look like the following:
-```python
-class DefaultConfig(object):
- """Bot configuration parameters."""
- # TCP port that the bot listens on (default:3978)
- PORT = 3978
-
- # Azure Application ID (not required if running locally)
- APP_ID = ""
- # Azure Application Password (not required if running locally)
- APP_PASSWORD = ""
-
- # Determines if the bot calls the models in-proc to the bot or call out of process
- # to the service api using a REST API.
- USE_MODEL_RUNTIME_SERVICE = True
- # Host serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_HOST = "api"
- # TCP serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_PORT = 8880
-```
-#### Build the containers
-
-The following command builds both the bot and the model runtime service containers.
-```bash
-# From 101.corebot-bert-bidaf directory
-docker-compose --project-directory . --file docker/docker-compose.yml build
-```
-> **NOTE**: If you get error code 137, you may need to increase the amount of memory supplied to Docker.
-
-#### Run the containers locally
-```bash
-# From 101.corebot-bert-bidaf directory
-docker-compose --project-directory . --file docker/docker-compose.yml up -d
-```
-#### Verify
-```bash
-# From 101.corebot-bert-bidaf directory
-docker-compose --project-directory . --file docker/docker-compose.yml logs
-docker ps
-```
-Look at the logs and docker to ensure the containers are running.
-
-> **NOTE**: When testing the bot inside containers, use your local IP address instead of `localhost` (`http://:3978/api/messages`).
-> To find your IP address:
->
-> - On **Windows**, `ipconfig` at a command prompt.
-> - On **Linux**, `ip addr` at a command prompt.
-
-
-## Testing the bot using Bot Framework Emulator
-
-[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to the bot using Bot Framework Emulator
-
-- Launch Bot Framework Emulator
-- File -> Open Bot
-- Enter a Bot URL of `http://localhost:3978/api/messages`
-
-### Test the bot
-In the emulator, type phrases such as`hello`, `book flight from seattle to miami`, etc
-
-
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
-- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
-- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
-- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
-- [.NET Core CLI tools](https://docs.microsoft.com/dotnet/core/tools/?tabs=netcore2x)
-- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
-- [Azure Portal](https://portal.azure.com)
-- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
-- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
-- [Google BERT](https://github.com/google-research/bert)
-- [ONNX BiDAF](https://github.com/onnx/models/tree/master/bidaf)
\ No newline at end of file
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/config.py b/tests/experimental/101.corebot-bert-bidaf/bot/config.py
deleted file mode 100644
index 89b234435..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/config.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Bot/Flask Configuration parameters.
-Configuration parameters for the bot.
-"""
-
-
-class DefaultConfig(object):
- """Bot configuration parameters."""
-
- # TCP port that the bot listens on (default:3978)
- PORT = 3978
-
- # Azure Application ID (not required if running locally)
- APP_ID = ""
- # Azure Application Password (not required if running locally)
- APP_PASSWORD = ""
-
- # Determines if the bot calls the models in-proc to the bot or call out of process
- # to the service api.
- USE_MODEL_RUNTIME_SERVICE = False
- # Host serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_HOST = "localhost"
- # TCP serving the out-of-process model runtime service api.
- MODEL_RUNTIME_SERVICE_PORT = 8880
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/main_dialog.py b/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/main_dialog.py
deleted file mode 100644
index 8e501a596..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/dialogs/main_dialog.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Main dialog. """
-from typing import Dict
-from botbuilder.dialogs import (
- ComponentDialog,
- WaterfallDialog,
- WaterfallStepContext,
- DialogTurnResult,
-)
-from botbuilder.dialogs.prompts import TextPrompt, PromptOptions
-from botbuilder.core import MessageFactory
-from model_corebot101.booking_details import BookingDetails
-from model_corebot101.language_helper import LanguageHelper
-from .booking_dialog import BookingDialog
-
-# pylint:disable=line-too-long
-class MainDialog(ComponentDialog):
- """Main dialog."""
-
- def __init__(
- self,
- configuration: Dict[str, object],
- dialog_id: str = None,
- language_helper: LanguageHelper = None,
- ):
- super(MainDialog, self).__init__(dialog_id or MainDialog.__name__)
-
- self._configuration = configuration
- self._language_helper = language_helper
-
- self.add_dialog(TextPrompt(TextPrompt.__name__))
- self.add_dialog(BookingDialog())
- self.add_dialog(
- WaterfallDialog(
- "WFDialog", [self.intro_step, self.act_step, self.final_step]
- )
- )
-
- self.initial_dialog_id = "WFDialog"
-
- # Initialize language models if we're not using service
- self._language_helper = LanguageHelper()
- if not self._configuration["USE_MODEL_RUNTIME_SERVICE"]:
- self._language_helper.initialize_models()
-
- async def intro_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
- """Initial prompt."""
- return await step_context.prompt(
- TextPrompt.__name__,
- PromptOptions(
- prompt=MessageFactory.text("What can I help you with today?")
- ),
- )
-
- async def act_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
- """Use language understanding to gather details about booking.
- In this sample we only have a single Intent we are concerned with.
- However, typically a scenario will have multiple different Intents
- each corresponding to starting a different child Dialog."""
-
- if step_context.result is not None:
- utterance = step_context.context.activity.text
- if not self._configuration["USE_MODEL_RUNTIME_SERVICE"]:
- booking_details = await self._language_helper.excecute_query_inproc(
- utterance
- )
- else:
- booking_details = await self._language_helper.excecute_query_service(
- self._configuration, utterance
- )
- else:
- booking_details = BookingDetails()
-
- # Run the BookingDialog giving it whatever details we have from the
- # model. The dialog will prompt to find out the remaining details.
- return await step_context.begin_dialog(BookingDialog.__name__, booking_details)
-
- async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
- """Complete dialog.
- At this step, with details from the user, display the completed
- flight booking to the user.
- """
- # If the child dialog ("BookingDialog") was cancelled or the user failed
- # to confirm, the Result here will be null.
- if step_context.result is not None:
- result = step_context.result
-
- # Now we have all the booking details call the booking service.
- # If the call to the booking service was successful tell the user.
- # time_property = Timex(result.travel_date)
- # travel_date_msg = time_property.to_natural_language(datetime.now())
- msg = (
- f"I have you booked to {result.destination} from"
- f" {result.origin} on {result.travel_date}."
- )
- await step_context.context.send_activity(MessageFactory.text(msg))
- else:
- await step_context.context.send_activity(MessageFactory.text("Thank you."))
- return await step_context.end_dialog()
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/__init__.py b/tests/experimental/101.corebot-bert-bidaf/bot/helpers/__init__.py
deleted file mode 100644
index b2860c928..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Helpers module."""
-
-from . import activity_helper, dialog_helper
-
-__all__ = ["activity_helper", "dialog_helper"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/activity_helper.py b/tests/experimental/101.corebot-bert-bidaf/bot/helpers/activity_helper.py
deleted file mode 100644
index bbd0ac848..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/helpers/activity_helper.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Helper to create reply object."""
-
-from datetime import datetime
-from botbuilder.schema import (
- Activity,
- ActivityTypes,
- ChannelAccount,
- ConversationAccount,
-)
-
-
-def create_activity_reply(activity: Activity, text: str = None, locale: str = None):
- """Helper to create reply object."""
- return Activity(
- type=ActivityTypes.message,
- timestamp=datetime.utcnow(),
- from_property=ChannelAccount(
- id=getattr(activity.recipient, "id", None),
- name=getattr(activity.recipient, "name", None),
- ),
- recipient=ChannelAccount(
- id=activity.from_property.id, name=activity.from_property.name
- ),
- reply_to_id=activity.id,
- service_url=activity.service_url,
- channel_id=activity.channel_id,
- conversation=ConversationAccount(
- is_group=activity.conversation.is_group,
- id=activity.conversation.id,
- name=activity.conversation.name,
- ),
- text=text or "",
- locale=locale or "",
- attachments=[],
- entities=[],
- )
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/main.py b/tests/experimental/101.corebot-bert-bidaf/bot/main.py
deleted file mode 100644
index 3dcfce782..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/main.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-"""
-This sample shows how to create a simple EchoBot with state.
-"""
-import asyncio
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapter,
- BotFrameworkAdapterSettings,
- ConversationState,
- MemoryStorage,
- UserState,
-)
-from botbuilder.schema import Activity
-from dialogs import MainDialog
-from bots import DialogAndWelcomeBot
-
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-
-# Retrieve Flask/Bot configuration
-APP.config.from_object("config.DefaultConfig")
-
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-# Create MemoryStorage, UserState and ConversationState
-MEMORY = MemoryStorage()
-USER_STATE = UserState(MEMORY)
-CONVERSATION_STATE = ConversationState(MEMORY)
-DIALOG = MainDialog(APP.config)
-BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
-
-
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- """Main bot message handler."""
- 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
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=True, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/experimental/101.corebot-bert-bidaf/bot/requirements.txt b/tests/experimental/101.corebot-bert-bidaf/bot/requirements.txt
deleted file mode 100644
index 496696f2c..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/bot/requirements.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-# Note: The model must be built first!
-# cd model
-#
-
-# The following are installed outside of requirements.txt
-# conda install -c pytorch pytorch -y
-# pip install onnxruntime
-# Install python package dependencies with the following:
-# `pip install -r requirements.txt`
-
-# Bot
-Flask>=1.0.2
-asyncio>=3.4.3
-requests>=2.18.1
-
-# Bot Framework
-botframework-connector>=4.4.0.b1
-botbuilder-schema>=4.4.0.b1
-botbuilder-core>=4.4.0.b1
-botbuilder-dialogs>=4.4.0.b1
-botbuilder-ai>=4.4.0.b1
-datatypes-date-time>=1.0.0.a1
-azure-cognitiveservices-language-luis>=0.2.0
-msrest>=0.6.6
-
-# Internal library - must be built first!
-model_corebot101>=0.0.1
-
-torch
-onnx
-onnxruntime
-tqdm>=4.32.1
-pytorch-pretrained-bert>=0.6.2
-nltk>=3.4.1
-numpy>=1.16.3
-scipy>=1.3.0
-scikit-learn>=0.21.2
-
diff --git a/tests/experimental/101.corebot-bert-bidaf/docker/docker-compose.yml b/tests/experimental/101.corebot-bert-bidaf/docker/docker-compose.yml
deleted file mode 100644
index 55599a3c9..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/docker/docker-compose.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-version: '3.7'
-services:
- bot:
- build:
- context: .
- dockerfile: Dockerfile_bot
- ports:
- - "3978:3978"
- links:
- - api
- environment:
- MODEL_RUNTIME_API_HOST : api
-
- api:
- build:
- context: .
- dockerfile: Dockerfile_model_runtime
- ports:
- - "8880:8880"
-
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_complete.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_complete.PNG
deleted file mode 100644
index 0254191fe..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_complete.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_runtime.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_runtime.PNG
deleted file mode 100644
index cbf7f5f76..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_runtime.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_train.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_train.PNG
deleted file mode 100644
index 231ae766b..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bert_train.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bidaf_runtime.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bidaf_runtime.PNG
deleted file mode 100644
index 80e7bb79f..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_bidaf_runtime.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_model_nav.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_model_nav.PNG
deleted file mode 100644
index 55181da4b..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_model_nav.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_run_all_cells.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_run_all_cells.PNG
deleted file mode 100644
index eb151981f..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_run_all_cells.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_select_kernel.PNG b/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_select_kernel.PNG
deleted file mode 100644
index b4c2f48d8..000000000
Binary files a/tests/experimental/101.corebot-bert-bidaf/media/jupyter_lab_select_kernel.PNG and /dev/null differ
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/about.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/about.py
deleted file mode 100644
index e6dd2b2d7..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/about.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Package information."""
-import os
-
-__title__ = "model_corebot101"
-__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "0.0.1"
-)
-__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
-__author__ = "Microsoft"
-__description__ = "Microsoft Bot Framework Bot Builder"
-__summary__ = "Microsoft Bot Framework Bot Builder SDK for Python."
-__license__ = "MIT"
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/__init__.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/__init__.py
deleted file mode 100644
index f9d109364..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .bert_util import BertUtil
-from .input_example import InputExample
-from .input_features import InputFeatures
-
-__all__ = ["BertUtil", "InputExample", "InputFeatures"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/bert_util.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/bert_util.py
deleted file mode 100644
index 800cee607..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/bert_util.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import logging
-from typing import List
-
-from .input_features import InputFeatures
-from scipy.stats import pearsonr, spearmanr
-from sklearn.metrics import f1_score
-
-
-class BertUtil:
- logger = logging.getLogger(__name__)
-
- @classmethod
- def convert_examples_to_features(
- cls, examples, label_list, max_seq_length, tokenizer, output_mode
- ) -> List:
- """Loads a data file into a list of `InputBatch`s."""
-
- label_map = {label: i for i, label in enumerate(label_list)}
-
- features = []
- for (ex_index, example) in enumerate(examples):
- if ex_index % 10000 == 0:
- cls.logger.info("Writing example %d of %d" % (ex_index, len(examples)))
-
- tokens_a = tokenizer.tokenize(example.text_a)
-
- tokens_b = None
- if example.text_b:
- tokens_b = tokenizer.tokenize(example.text_b)
- # Modifies `tokens_a` and `tokens_b` in place so that the total
- # length is less than the specified length.
- # Account for [CLS], [SEP], [SEP] with "- 3"
- BertUtil._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
- else:
- # Account for [CLS] and [SEP] with "- 2"
- if len(tokens_a) > max_seq_length - 2:
- tokens_a = tokens_a[: (max_seq_length - 2)]
-
- # The convention in BERT is:
- # (a) For sequence pairs:
- # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
- # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
- # (b) For single sequences:
- # tokens: [CLS] the dog is hairy . [SEP]
- # type_ids: 0 0 0 0 0 0 0
- #
- # Where "type_ids" are used to indicate whether this is the first
- # sequence or the second sequence. The embedding vectors for `type=0` and
- # `type=1` were learned during pre-training and are added to the wordpiece
- # embedding vector (and position vector). This is not *strictly* necessary
- # since the [SEP] token unambiguously separates the sequences, but it makes
- # it easier for the model to learn the concept of sequences.
- #
- # For classification tasks, the first vector (corresponding to [CLS]) is
- # used as as the "sentence vector". Note that this only makes sense because
- # the entire model is fine-tuned.
- tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
- segment_ids = [0] * len(tokens)
-
- if tokens_b:
- tokens += tokens_b + ["[SEP]"]
- segment_ids += [1] * (len(tokens_b) + 1)
-
- input_ids = tokenizer.convert_tokens_to_ids(tokens)
-
- # The mask has 1 for real tokens and 0 for padding tokens. Only real
- # tokens are attended to.
- input_mask = [1] * len(input_ids)
-
- # Zero-pad up to the sequence length.
- padding = [0] * (max_seq_length - len(input_ids))
- input_ids += padding
- input_mask += padding
- segment_ids += padding
-
- assert len(input_ids) == max_seq_length
- assert len(input_mask) == max_seq_length
- assert len(segment_ids) == max_seq_length
-
- if output_mode == "classification":
- label_id = label_map[example.label]
- elif output_mode == "regression":
- label_id = float(example.label)
- else:
- raise KeyError(output_mode)
-
- if ex_index < 5:
- cls.logger.info("*** Example ***")
- cls.logger.info("guid: %s" % (example.guid))
- cls.logger.info("tokens: %s" % " ".join([str(x) for x in tokens]))
- cls.logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
- cls.logger.info(
- "input_mask: %s" % " ".join([str(x) for x in input_mask])
- )
- cls.logger.info(
- "segment_ids: %s" % " ".join([str(x) for x in segment_ids])
- )
- cls.logger.info("label: %s (id = %d)" % (example.label, label_id))
-
- features.append(
- InputFeatures(
- input_ids=input_ids,
- input_mask=input_mask,
- segment_ids=segment_ids,
- label_id=label_id,
- )
- )
- return features
-
- @staticmethod
- def _truncate_seq_pair(tokens_a, tokens_b, max_length):
- """Truncates a sequence pair in place to the maximum length."""
-
- # This is a simple heuristic which will always truncate the longer sequence
- # one token at a time. This makes more sense than truncating an equal percent
- # of tokens from each, since if one sequence is very short then each token
- # that's truncated likely contains more information than a longer sequence.
- while True:
- total_length = len(tokens_a) + len(tokens_b)
- if total_length <= max_length:
- break
- if len(tokens_a) > len(tokens_b):
- tokens_a.pop()
- else:
- tokens_b.pop()
-
- @staticmethod
- def simple_accuracy(preds, labels):
- return (preds == labels).mean()
-
- @staticmethod
- def acc_and_f1(preds, labels):
- acc = BertUtil.simple_accuracy(preds, labels)
- f1 = f1_score(y_true=labels, y_pred=preds)
- return {"acc": acc, "f1": f1, "acc_and_f1": (acc + f1) / 2}
-
- @staticmethod
- def pearson_and_spearman(preds, labels):
- pearson_corr = pearsonr(preds, labels)[0]
- spearman_corr = spearmanr(preds, labels)[0]
- return {
- "pearson": pearson_corr,
- "spearmanr": spearman_corr,
- "corr": (pearson_corr + spearman_corr) / 2,
- }
-
- @staticmethod
- def compute_metrics(task_name, preds, labels):
- assert len(preds) == len(labels)
- if task_name == "flight_booking":
- return BertUtil.acc_and_f1(preds, labels)
- else:
- raise KeyError(task_name)
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_example.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_example.py
deleted file mode 100644
index 63410a11f..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_example.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-
-class InputExample(object):
- """A single training/test example for sequence classification."""
-
- def __init__(self, guid, text_a, text_b=None, label=None):
- """Constructs a InputExample.
-
- Args:
- guid: Unique id for the example.
- text_a: string. The untokenized text of the first sequence. For single
- sequence tasks, only this sequence must be specified.
- text_b: (Optional) string. The untokenized text of the second sequence.
- Only must be specified for sequence pair tasks.
- label: (Optional) string. The label of the example. This should be
- specified for train and dev examples, but not for test examples.
- """
- self.guid = guid
- self.text_a = text_a
- self.text_b = text_b
- self.label = label
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_features.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_features.py
deleted file mode 100644
index 0138e75e2..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/common/input_features.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-
-class InputFeatures(object):
- """A single set of features of data."""
-
- def __init__(self, input_ids, input_mask, segment_ids, label_id):
- self.input_ids = input_ids
- self.input_mask = input_mask
- self.segment_ids = segment_ids
- self.label_id = label_id
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/__init__.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/__init__.py
deleted file mode 100644
index 22497eea5..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .bert_model_runtime import BertModelRuntime
-
-__all__ = ["BertModelRuntime"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/bert_model_runtime.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/bert_model_runtime.py
deleted file mode 100644
index bb66ddc07..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/model_runtime/bert_model_runtime.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Bert model runtime."""
-
-import os
-import sys
-from typing import List
-import numpy as np
-import torch
-from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
-from pytorch_pretrained_bert import BertForSequenceClassification, BertTokenizer
-from model_corebot101.bert.common.bert_util import BertUtil
-from model_corebot101.bert.common.input_example import InputExample
-
-
-class BertModelRuntime:
- """Model runtime for the Bert model."""
-
- def __init__(
- self,
- model_dir: str,
- label_list: List[str],
- max_seq_length: int = 128,
- output_mode: str = "classification",
- no_cuda: bool = False,
- do_lower_case: bool = True,
- ):
- self.model_dir = model_dir
- self.label_list = label_list
- self.num_labels = len(self.label_list)
- self.max_seq_length = max_seq_length
- self.output_mode = output_mode
- self.no_cuda = no_cuda
- self.do_lower_case = do_lower_case
- self._load_model()
-
- # pylint:disable=unused-argument
- @staticmethod
- def init_bert(bert_model_dir: str) -> bool:
- """ Handle any one-time initlization """
- if os.path.isdir(bert_model_dir):
- print("bert model directory already present..", file=sys.stderr)
- else:
- print("Creating bert model directory..", file=sys.stderr)
- os.makedirs(bert_model_dir, exist_ok=True)
- return True
-
- def _load_model(self) -> None:
- self.device = torch.device(
- "cuda" if torch.cuda.is_available() and not self.no_cuda else "cpu"
- )
- self.n_gpu = torch.cuda.device_count()
-
- # Load a trained model and vocabulary that you have fine-tuned
- self.model = BertForSequenceClassification.from_pretrained(
- self.model_dir, num_labels=self.num_labels
- )
- self.tokenizer = BertTokenizer.from_pretrained(
- self.model_dir, do_lower_case=self.do_lower_case
- )
- self.model.to(self.device)
-
- def serve(self, query: str) -> str:
- example = InputExample(
- guid="", text_a=query, text_b=None, label=self.label_list[0]
- )
- examples = [example]
-
- eval_features = BertUtil.convert_examples_to_features(
- examples,
- self.label_list,
- self.max_seq_length,
- self.tokenizer,
- self.output_mode,
- )
- all_input_ids = torch.tensor(
- [f.input_ids for f in eval_features], dtype=torch.long
- )
- all_input_mask = torch.tensor(
- [f.input_mask for f in eval_features], dtype=torch.long
- )
- all_segment_ids = torch.tensor(
- [f.segment_ids for f in eval_features], dtype=torch.long
- )
-
- if self.output_mode == "classification":
- all_label_ids = torch.tensor(
- [f.label_id for f in eval_features], dtype=torch.long
- )
-
- eval_data = TensorDataset(
- all_input_ids, all_input_mask, all_segment_ids, all_label_ids
- )
- # Run prediction for full data
- eval_sampler = SequentialSampler(eval_data)
- eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=1)
-
- self.model.eval()
- nb_eval_steps = 0
- preds = []
-
- for input_ids, input_mask, segment_ids, label_ids in eval_dataloader:
- input_ids = input_ids.to(self.device)
- input_mask = input_mask.to(self.device)
- segment_ids = segment_ids.to(self.device)
-
- with torch.no_grad():
- logits = self.model(input_ids, segment_ids, input_mask, labels=None)
-
- nb_eval_steps += 1
- if len(preds) == 0:
- preds.append(logits.detach().cpu().numpy())
- else:
- preds[0] = np.append(preds[0], logits.detach().cpu().numpy(), axis=0)
-
- preds = preds[0]
- if self.output_mode == "classification":
- preds = np.argmax(preds, axis=1)
-
- label_id = preds[0]
- pred_label = self.label_list[label_id]
- return pred_label
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/requirements.txt b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/requirements.txt
deleted file mode 100644
index f9d97a146..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-torch
-tqdm
-pytorch-pretrained-bert
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/__init__.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/__init__.py
deleted file mode 100644
index 1bd0ac221..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Bert tuning training."""
-
-from .args import Args
-from .bert_train_eval import BertTrainEval
-from .flight_booking_processor import FlightBookingProcessor
-
-__all__ = ["Args", "BertTrainEval", "FlightBookingProcessor"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/args.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/args.py
deleted file mode 100644
index 3d0f77811..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/args.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Arguments for the model. """
-
-import os
-import sys
-from pathlib import Path
-
-# pylint:disable=line-too-long
-class Args:
- """Arguments for the model."""
-
- training_data_dir: str = None
- bert_model: str = None
- task_name: str = None
- model_dir: str = None
- cleanup_output_dir: bool = False
- cache_dir: str = ""
- max_seq_length: int = 128
- do_train: bool = None
- do_eval: bool = None
- do_lower_case: bool = None
- train_batch_size: int = 4
- eval_batch_size: int = 8
- learning_rate: float = 5e-5
- num_train_epochs: float = 3.0
- warmup_proportion: float = 0.1
- no_cuda: bool = None
- local_rank: int = -1
- seed: int = 42
- gradient_accumulation_steps: int = 1
- fp16: bool = None
- loss_scale: float = 0
-
- @classmethod
- def for_flight_booking(
- cls,
- training_data_dir: str = os.path.abspath(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), "../training_data")
- ),
- task_name: str = "flight_booking",
- ):
- """Return the flight booking args."""
- args = cls()
-
- args.training_data_dir = training_data_dir
- args.task_name = task_name
- home_dir = str(Path.home())
- args.model_dir = os.path.abspath(os.path.join(home_dir, "models/bert"))
- args.bert_model = "bert-base-uncased"
- args.do_lower_case = True
-
- print(
- f"Bert Model training_data_dir is set to {args.training_data_dir}",
- file=sys.stderr,
- )
- print(f"Bert Model model_dir is set to {args.model_dir}", file=sys.stderr)
- return args
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/bert_train_eval.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/bert_train_eval.py
deleted file mode 100644
index 11d6d558e..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/bert_train_eval.py
+++ /dev/null
@@ -1,375 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import logging
-import os
-import random
-import shutil
-import numpy as np
-import torch
-from .args import Args
-
-from model_corebot101.bert.common.bert_util import BertUtil
-from model_corebot101.bert.train.flight_booking_processor import FlightBookingProcessor
-from pytorch_pretrained_bert.file_utils import (
- CONFIG_NAME,
- PYTORCH_PRETRAINED_BERT_CACHE,
- WEIGHTS_NAME,
-)
-from pytorch_pretrained_bert.modeling import (
- BertForSequenceClassification,
- BertPreTrainedModel,
-)
-from pytorch_pretrained_bert.optimization import BertAdam
-from pytorch_pretrained_bert.tokenization import BertTokenizer
-from torch.nn import CrossEntropyLoss
-from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
-from torch.utils.data.distributed import DistributedSampler
-
-from tqdm import tqdm, trange
-
-
-class BertTrainEval:
- logger = logging.getLogger(__name__)
-
- def __init__(self, args: Args):
- self.processor = FlightBookingProcessor()
- self.output_mode = "classification"
- self.args = args
- self._prepare()
- self.model = self._prepare_model()
-
- @classmethod
- def train_eval(cls, cleanup_output_dir: bool = False) -> None:
- # uncomment the following line for debugging.
- # import pdb; pdb.set_trace()
- args = Args.for_flight_booking()
- args.do_train = True
- args.do_eval = True
- args.cleanup_output_dir = cleanup_output_dir
- bert = cls(args)
- bert.train()
- bert.eval()
-
- def train(self) -> None:
- # Prepare optimizer
- param_optimizer = list(self.model.named_parameters())
- no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
- optimizer_grouped_parameters = [
- {
- "params": [
- p for n, p in param_optimizer if not any(nd in n for nd in no_decay)
- ],
- "weight_decay": 0.01,
- },
- {
- "params": [
- p for n, p in param_optimizer if any(nd in n for nd in no_decay)
- ],
- "weight_decay": 0.0,
- },
- ]
- optimizer = BertAdam(
- optimizer_grouped_parameters,
- lr=self.args.learning_rate,
- warmup=self.args.warmup_proportion,
- t_total=self.num_train_optimization_steps,
- )
-
- global_step: int = 0
- nb_tr_steps = 0
- tr_loss: float = 0
- train_features = BertUtil.convert_examples_to_features(
- self.train_examples,
- self.label_list,
- self.args.max_seq_length,
- self.tokenizer,
- self.output_mode,
- )
- self.logger.info("***** Running training *****")
- self.logger.info(" Num examples = %d", len(self.train_examples))
- self.logger.info(" Batch size = %d", self.args.train_batch_size)
- self.logger.info(" Num steps = %d", self.num_train_optimization_steps)
- all_input_ids = torch.tensor(
- [f.input_ids for f in train_features], dtype=torch.long
- )
- all_input_mask = torch.tensor(
- [f.input_mask for f in train_features], dtype=torch.long
- )
- all_segment_ids = torch.tensor(
- [f.segment_ids for f in train_features], dtype=torch.long
- )
-
- if self.output_mode == "classification":
- all_label_ids = torch.tensor(
- [f.label_id for f in train_features], dtype=torch.long
- )
-
- train_data = TensorDataset(
- all_input_ids, all_input_mask, all_segment_ids, all_label_ids
- )
- if self.args.local_rank == -1:
- train_sampler = RandomSampler(train_data)
- else:
- train_sampler = DistributedSampler(train_data)
- train_dataloader = DataLoader(
- train_data, sampler=train_sampler, batch_size=self.args.train_batch_size
- )
-
- self.model.train()
- for _ in trange(int(self.args.num_train_epochs), desc="Epoch"):
- tr_loss = 0
- nb_tr_examples, nb_tr_steps = 0, 0
- for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
- batch = tuple(t.to(self.device) for t in batch)
- input_ids, input_mask, segment_ids, label_ids = batch
-
- # define a new function to compute loss values for both output_modes
- logits = self.model(input_ids, segment_ids, input_mask, labels=None)
-
- if self.output_mode == "classification":
- loss_fct = CrossEntropyLoss()
- loss = loss_fct(
- logits.view(-1, self.num_labels), label_ids.view(-1)
- )
-
- if self.args.gradient_accumulation_steps > 1:
- loss = loss / self.args.gradient_accumulation_steps
-
- loss.backward()
-
- tr_loss += loss.item()
- nb_tr_examples += input_ids.size(0)
- nb_tr_steps += 1
- if (step + 1) % self.args.gradient_accumulation_steps == 0:
- optimizer.step()
- optimizer.zero_grad()
- global_step += 1
-
- if self.args.local_rank == -1 or torch.distributed.get_rank() == 0:
- # Save a trained model, configuration and tokenizer
- model_to_save = (
- self.model.module if hasattr(self.model, "module") else self.model
- ) # Only save the model it-self
-
- # If we save using the predefined names, we can load using `from_pretrained`
- output_model_file = os.path.join(self.args.model_dir, WEIGHTS_NAME)
- output_config_file = os.path.join(self.args.model_dir, CONFIG_NAME)
-
- torch.save(model_to_save.state_dict(), output_model_file)
- model_to_save.config.to_json_file(output_config_file)
- self.tokenizer.save_vocabulary(self.args.model_dir)
-
- # Load a trained model and vocabulary that you have fine-tuned
- self.model = BertForSequenceClassification.from_pretrained(
- self.args.model_dir, num_labels=self.num_labels
- )
- self.tokenizer = BertTokenizer.from_pretrained(
- self.args.model_dir, do_lower_case=self.args.do_lower_case
- )
- else:
- self.model = BertForSequenceClassification.from_pretrained(
- self.args.bert_model, num_labels=self.num_labels
- )
- self.model.to(self.device)
-
- self.tr_loss, self.global_step = tr_loss, global_step
-
- self.logger.info("DONE TRAINING."),
-
- def eval(self) -> None:
- if not (self.args.local_rank == -1 or torch.distributed.get_rank() == 0):
- return
-
- eval_examples = self.processor.get_dev_examples(self.args.training_data_dir)
- eval_features = BertUtil.convert_examples_to_features(
- eval_examples,
- self.label_list,
- self.args.max_seq_length,
- self.tokenizer,
- self.output_mode,
- )
- self.logger.info("***** Running evaluation *****")
- self.logger.info(" Num examples = %d", len(eval_examples))
- self.logger.info(" Batch size = %d", self.args.eval_batch_size)
- all_input_ids = torch.tensor(
- [f.input_ids for f in eval_features], dtype=torch.long
- )
- all_input_mask = torch.tensor(
- [f.input_mask for f in eval_features], dtype=torch.long
- )
- all_segment_ids = torch.tensor(
- [f.segment_ids for f in eval_features], dtype=torch.long
- )
-
- if self.output_mode == "classification":
- all_label_ids = torch.tensor(
- [f.label_id for f in eval_features], dtype=torch.long
- )
-
- eval_data = TensorDataset(
- all_input_ids, all_input_mask, all_segment_ids, all_label_ids
- )
- # Run prediction for full data
- eval_sampler = SequentialSampler(eval_data)
- eval_dataloader = DataLoader(
- eval_data, sampler=eval_sampler, batch_size=self.args.eval_batch_size
- )
-
- self.model.eval()
- eval_loss = 0
- nb_eval_steps = 0
- preds = []
-
- for input_ids, input_mask, segment_ids, label_ids in tqdm(
- eval_dataloader, desc="Evaluating"
- ):
- input_ids = input_ids.to(self.device)
- input_mask = input_mask.to(self.device)
- segment_ids = segment_ids.to(self.device)
- label_ids = label_ids.to(self.device)
-
- with torch.no_grad():
- logits = self.model(input_ids, segment_ids, input_mask, labels=None)
-
- # create eval loss and other metric required by the task
- if self.output_mode == "classification":
- loss_fct = CrossEntropyLoss()
- tmp_eval_loss = loss_fct(
- logits.view(-1, self.num_labels), label_ids.view(-1)
- )
-
- eval_loss += tmp_eval_loss.mean().item()
- nb_eval_steps += 1
- if len(preds) == 0:
- preds.append(logits.detach().cpu().numpy())
- else:
- preds[0] = np.append(preds[0], logits.detach().cpu().numpy(), axis=0)
-
- eval_loss = eval_loss / nb_eval_steps
- preds = preds[0]
- if self.output_mode == "classification":
- preds = np.argmax(preds, axis=1)
- result = BertUtil.compute_metrics(self.task_name, preds, all_label_ids.numpy())
- loss = self.tr_loss / self.global_step if self.args.do_train else None
-
- result["eval_loss"] = eval_loss
- result["global_step"] = self.global_step
- result["loss"] = loss
-
- output_eval_file = os.path.join(self.args.model_dir, "eval_results.txt")
- with open(output_eval_file, "w") as writer:
- self.logger.info("***** Eval results *****")
- for key in sorted(result.keys()):
- self.logger.info(" %s = %s", key, str(result[key]))
- writer.write("%s = %s\n" % (key, str(result[key])))
-
- self.logger.info("DONE EVALUATING.")
-
- def _prepare(self, cleanup_output_dir: bool = False) -> None:
- if self.args.local_rank == -1 or self.args.no_cuda:
- self.device = torch.device(
- "cuda" if torch.cuda.is_available() and not self.args.no_cuda else "cpu"
- )
- self.n_gpu = torch.cuda.device_count()
- else:
- torch.cuda.set_device(self.args.local_rank)
- self.device = torch.device("cuda", self.args.local_rank)
- self.n_gpu = 1
- # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
- torch.distributed.init_process_group(backend="nccl")
-
- logging.basicConfig(
- format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
- datefmt="%m/%d/%Y %H:%M:%S",
- level=logging.INFO if self.args.local_rank in [-1, 0] else logging.WARN,
- )
-
- self.logger.info(
- "device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
- self.device,
- self.n_gpu,
- bool(self.args.local_rank != -1),
- self.args.fp16,
- )
- )
-
- if self.args.gradient_accumulation_steps < 1:
- raise ValueError(
- "Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
- self.args.gradient_accumulation_steps
- )
- )
-
- self.args.train_batch_size = (
- self.args.train_batch_size // self.args.gradient_accumulation_steps
- )
-
- random.seed(self.args.seed)
- np.random.seed(self.args.seed)
- torch.manual_seed(self.args.seed)
- if self.n_gpu > 0:
- torch.cuda.manual_seed_all(self.args.seed)
-
- if not self.args.do_train and not self.args.do_eval:
- raise ValueError("At least one of `do_train` or `do_eval` must be True.")
-
- if self.args.cleanup_output_dir:
- if os.path.exists(self.args.model_dir):
- shutil.rmtree(self.args.model_dir)
-
- if (
- os.path.exists(self.args.model_dir)
- and os.listdir(self.args.model_dir)
- and self.args.do_train
- ):
- raise ValueError(
- "Output directory ({}) already exists and is not empty.".format(
- self.args.model_dir
- )
- )
- if not os.path.exists(self.args.model_dir):
- os.makedirs(self.args.model_dir)
-
- self.task_name = self.args.task_name.lower()
-
- self.label_list = self.processor.get_labels()
- self.num_labels = len(self.label_list)
-
- self.tokenizer = BertTokenizer.from_pretrained(
- self.args.bert_model, do_lower_case=self.args.do_lower_case
- )
-
- self.train_examples = None
- self.num_train_optimization_steps = None
- if self.args.do_train:
- self.train_examples = self.processor.get_train_examples(
- self.args.training_data_dir
- )
- self.num_train_optimization_steps = (
- int(
- len(self.train_examples)
- / self.args.train_batch_size
- / self.args.gradient_accumulation_steps
- )
- * self.args.num_train_epochs
- )
- if self.args.local_rank != -1:
- self.num_train_optimization_steps = (
- self.num_train_optimization_steps
- // torch.distributed.get_world_size()
- )
-
- def _prepare_model(self) -> BertPreTrainedModel:
- if self.args.cache_dir:
- cache_dir = self.args.cache_dir
- else:
- cache_dir = os.path.join(
- str(PYTORCH_PRETRAINED_BERT_CACHE),
- f"distributed_{self.args.local_rank}",
- )
- model = BertForSequenceClassification.from_pretrained(
- self.args.bert_model, cache_dir=cache_dir, num_labels=self.num_labels
- )
- model.to(self.device)
- return model
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/flight_booking_processor.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/flight_booking_processor.py
deleted file mode 100644
index b1104ce92..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bert/train/flight_booking_processor.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import json
-import os
-from typing import List, Tuple
-
-from model_corebot101.bert.common.input_example import InputExample
-
-
-class FlightBookingProcessor:
- """Processor for the flight booking data set."""
-
- def get_train_examples(self, data_dir):
- """See base class."""
- return self._create_examples(
- self._read_json(os.path.join(data_dir, "FlightBooking.json")), "train"
- )
-
- def get_dev_examples(self, data_dir):
- """See base class."""
- return self._create_examples(
- self._read_json(os.path.join(data_dir, "FlightBooking.json")), "dev"
- )
-
- def get_labels(self):
- """See base class."""
- return ["Book flight", "Cancel"]
-
- def _create_examples(self, lines, set_type):
- """Creates examples for the training and dev sets."""
- examples = []
- for (i, line) in enumerate(lines):
- guid = "%s-%s" % (set_type, i)
- text_a = line[1]
- label = line[0]
- examples.append(
- InputExample(guid=guid, text_a=text_a, text_b=None, label=label)
- )
- return examples
-
- @classmethod
- def _read_json(cls, input_file):
- with open(input_file, "r", encoding="utf-8") as f:
- obj = json.load(f)
- examples = obj["utterances"]
- lines: List[Tuple[str, str]] = []
- for example in examples:
- lines.append((example["intent"], example["text"]))
-
- return lines
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/__init__.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/__init__.py
deleted file mode 100644
index 9d191b568..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .bidaf_model_runtime import BidafModelRuntime
-
-__all__ = ["BidafModelRuntime"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/bidaf_model_runtime.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/bidaf_model_runtime.py
deleted file mode 100644
index 2f3ed506e..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/model_runtime/bidaf_model_runtime.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-import os
-import sys
-import requests
-import shutil
-from typing import Dict, List, Tuple
-import nltk
-import numpy as np
-from nltk import word_tokenize
-from onnxruntime import InferenceSession
-
-# pylint:disable=line-too-long
-class BidafModelRuntime:
- def __init__(self, targets: List[str], queries: Dict[str, str], model_dir: str):
- self.queries = queries
- self.targets = targets
- bidaf_model = os.path.abspath(os.path.join(model_dir, "bidaf.onnx"))
- print(f"Loading Inference session from {bidaf_model}..", file=sys.stderr)
- self.session = InferenceSession(bidaf_model)
- print(f"Inference session loaded..", file=sys.stderr)
- self.processed_queries = self._process_queries()
- print(f"Processed queries..", file=sys.stderr)
-
- @staticmethod
- def init_bidaf(bidaf_model_dir: str, download_ntlk_punkt: bool = False) -> bool:
- if os.path.isdir(bidaf_model_dir):
- print("bidaf model directory already present..", file=sys.stderr)
- else:
- print("Creating bidaf model directory..", file=sys.stderr)
- os.makedirs(bidaf_model_dir, exist_ok=True)
-
- # Download Punkt Sentence Tokenizer
- if download_ntlk_punkt:
- nltk.download("punkt", download_dir=bidaf_model_dir)
- nltk.download("punkt")
-
- # Download bidaf onnx model
- onnx_model_file = os.path.abspath(os.path.join(bidaf_model_dir, "bidaf.onnx"))
-
- print(f"Checking file {onnx_model_file}..", file=sys.stderr)
- if os.path.isfile(onnx_model_file):
- print("bidaf.onnx downloaded already!", file=sys.stderr)
- else:
- print("Downloading bidaf.onnx...", file=sys.stderr)
- response = requests.get(
- "https://onnxzoo.blob.core.windows.net/models/opset_9/bidaf/bidaf.onnx",
- stream=True,
- )
- with open(onnx_model_file, "wb") as f:
- response.raw.decode_content = True
- shutil.copyfileobj(response.raw, f)
- return True
-
- def serve(self, context: str) -> Dict[str, str]:
- result = {}
- cw, cc = BidafModelRuntime._preprocess(context)
- for target in self.targets:
- qw, qc = self.processed_queries[target]
- answer = self.session.run(
- ["start_pos", "end_pos"],
- {
- "context_word": cw,
- "context_char": cc,
- "query_word": qw,
- "query_char": qc,
- },
- )
- start = answer[0].item()
- end = answer[1].item()
- result_item = cw[start : end + 1]
- result[target] = BidafModelRuntime._convert_result(result_item)
-
- return result
-
- def _process_queries(self) -> Dict[str, Tuple[np.ndarray, np.ndarray]]:
- result = {}
- for target in self.targets:
- question = self.queries[target]
- result[target] = BidafModelRuntime._preprocess(question)
-
- return result
-
- @staticmethod
- def _convert_result(result_item: np.ndarray) -> str:
- result = []
- for item in result_item:
- result.append(item[0])
-
- return " ".join(result)
-
- @staticmethod
- def _preprocess(text: str) -> Tuple[np.ndarray, np.ndarray]:
- tokens = word_tokenize(text)
- # split into lower-case word tokens, in numpy array with shape of (seq, 1)
- words = np.asarray([w.lower() for w in tokens]).reshape(-1, 1)
- # split words into chars, in numpy array with shape of (seq, 1, 1, 16)
- chars = [[c for c in t][:16] for t in tokens]
- chars = [cs + [""] * (16 - len(cs)) for cs in chars]
- chars = np.asarray(chars).reshape(-1, 1, 1, 16)
- return words, chars
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/requirements.txt b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/requirements.txt
deleted file mode 100644
index bb0cd1821..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/bidaf/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-nltk
-numpy
-onnxruntime
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/booking_details.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/booking_details.py
deleted file mode 100644
index 81f3ee5b8..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/booking_details.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Booking Details.
-The lu model will detect the properties of a flight booking.
-"""
-
-
-class BookingDetails:
- """Booking properties from lu model."""
-
- def __init__(
- self, destination: str = None, origin: str = None, travel_date: str = None
- ):
- self.destination = destination
- self.origin = origin
- self.travel_date = travel_date
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/language_helper.py b/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/language_helper.py
deleted file mode 100644
index c98ae0d09..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/model_corebot101/language_helper.py
+++ /dev/null
@@ -1,212 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Language helper that invokes the language model.
-This is used from the Bot and Model Runtime to load and invoke the language models.
-"""
-
-import os
-import sys
-from typing import Dict
-from pathlib import Path
-import requests
-from datatypes_date_time.timex import Timex
-from model_corebot101.booking_details import BookingDetails
-from model_corebot101.bidaf.model_runtime import BidafModelRuntime
-from model_corebot101.bert.model_runtime import BertModelRuntime
-from model_corebot101.bert.train import BertTrainEval
-
-# pylint:disable=line-too-long
-class LanguageHelper:
- """Language helper that invokes the language model."""
-
- home_dir = str(Path.home())
- bert_model_dir_default = os.path.abspath(os.path.join(home_dir, "models/bert"))
- bidaf_model_dir_default = os.path.abspath(os.path.join(home_dir, "models/bidaf"))
-
- # pylint:disable=bad-continuation
- def __init__(self):
- """Create Language Helper.
- Note: Creating the Bert/Bidaf Model Runtime is only necessary for in-proc usage.
- """
- self._bidaf_entities = None
- self._bert_intents = None
-
- @property
- def entities(self) -> BidafModelRuntime:
- """Model used to detect entities."""
- return self._bidaf_entities
-
- @property
- def intents(self) -> BertModelRuntime:
- """Model used to detect intents."""
- return self._bert_intents
-
- def initialize_models(
- self,
- bert_model_dir: str = bert_model_dir_default,
- bidaf_model_dir: str = bidaf_model_dir_default,
- ) -> bool:
- """ Initialize models.
- Perform initialization of the models.
- """
- if not BidafModelRuntime.init_bidaf(bidaf_model_dir, download_ntlk_punkt=True):
- print(
- f"bidaf model creation failed at model directory {bidaf_model_dir}..",
- file=sys.stderr,
- )
- return False
-
- if not BertModelRuntime.init_bert(bert_model_dir):
- print(
- "bert model creation failed at model directory {bert_model_dir}..",
- file=sys.stderr,
- )
- return False
-
- print(f"Loading BERT model from {bert_model_dir}...", file=sys.stderr)
- if not os.listdir(bert_model_dir):
- print(f"No BERT model present, building model..", file=sys.stderr)
- BertTrainEval.train_eval(cleanup_output_dir=True)
-
- self._bert_intents = BertModelRuntime(
- model_dir=bert_model_dir, label_list=["Book flight", "Cancel"]
- )
- print(f"Loaded BERT model. Loading BiDaf model..", file=sys.stderr)
-
- self._bidaf_entities = BidafModelRuntime(
- targets=["from", "to", "date"],
- queries={
- "from": "which city will you travel from?",
- "to": "which city will you travel to?",
- "date": "which date will you travel?",
- },
- model_dir=bidaf_model_dir,
- )
- print(f"Loaded BiDAF model from {bidaf_model_dir}.", file=sys.stderr)
-
- return True
-
- async def excecute_query_inproc(self, utterance: str) -> BookingDetails:
- """Exeecute a query against language model."""
- booking_details = BookingDetails()
- intent = self.intents.serve(utterance)
- print(f'Recognized intent "{intent}" from "{utterance}".', file=sys.stderr)
- if intent == "Book flight":
- # Bert gave us the intent.
- # Now look for entities with BiDAF..
- entities = self.entities.serve(utterance)
-
- if "to" in entities:
- print(f' Recognized "to" entitiy: {entities["to"]}.', file=sys.stderr)
- booking_details.destination = entities["to"]
- if "from" in entities:
- print(
- f' Recognized "from" entitiy: {entities["from"]}.',
- file=sys.stderr,
- )
- booking_details.origin = entities["from"]
- if "date" in entities:
- # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
- # TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
- print(
- f' Recognized "date" entitiy: {entities["date"]}.',
- file=sys.stderr,
- )
- travel_date = entities["date"]
- if await LanguageHelper.validate_timex(travel_date):
- booking_details.travel_date = travel_date
-
- return booking_details
-
- @staticmethod
- async def excecute_query_service(
- configuration: dict, utterance: str
- ) -> BookingDetails:
- """Invoke lu service to perform prediction/evaluation of utterance."""
- booking_details = BookingDetails()
- lu_response = await LanguageHelper.call_model_runtime(configuration, utterance)
- if lu_response.status_code == 200:
-
- response_json = lu_response.json()
- intent = response_json["intent"] if "intent" in response_json else None
- entities = await LanguageHelper.validate_entities(
- response_json["entities"] if "entities" in response_json else None
- )
- if intent:
- if "to" in entities:
- print(
- f' Recognized "to" entity: {entities["to"]}.', file=sys.stderr
- )
- booking_details.destination = entities["to"]
- if "from" in entities:
- print(
- f' Recognized "from" entity: {entities["from"]}.',
- file=sys.stderr,
- )
- booking_details.origin = entities["from"]
- if "date" in entities:
- # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
- # TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
- print(
- f' Recognized "date" entity: {entities["date"]}.',
- file=sys.stderr,
- )
- travel_date = entities["date"]
- if await LanguageHelper.validate_timex(travel_date):
- booking_details.travel_date = travel_date
- return booking_details
-
- @staticmethod
- async def call_model_runtime(
- configuration: Dict[str, object], text: str
- ) -> requests.Request:
- """ Makes a call to the model runtime api
-
- The model runtime api signature is:
- http://:/v1.0/model?q=
-
- where:
-
- model_runtime_host - The host running the model runtime api. To resolve
- the host running the model runtime api (in the following order):
- - MODEL_RUNTIME_API environment variable. Used in docker.
- - config.py (which contains the DefaultConfig class). Used running
- locally.
-
- port - http port number (ie, 8880)
-
- q - A query string to process (ie, the text utterance from user)
-
- For more details: (See TBD swagger file)
- """
- port = os.environ.get("MODEL_RUNTIME_SERVICE_PORT")
- host = os.environ.get("MODEL_RUNTIME_SERVICE_HOST")
- if host is None:
- host = configuration["MODEL_RUNTIME_SERVICE_HOST"]
- if port is None:
- port = configuration["MODEL_RUNTIME_SERVICE_PORT"]
-
- api_url = f"http://{host}:{port}/v1.0/model"
- qstrings = {"q": text}
- return requests.get(api_url, params=qstrings)
-
- @staticmethod
- async def validate_entities(entities: Dict[str, str]) -> bool:
- """Validate the entities.
- The to and from cities can't be the same. If this is detected,
- remove the ambiguous results. """
- if "to" in entities and "from" in entities:
- if entities["to"] == entities["from"]:
- del entities["to"]
- del entities["from"]
- return entities
-
- @staticmethod
- async def validate_timex(travel_date: str) -> bool:
- """Validate the time.
- Make sure time given in the right format. """
- # uncomment the following line for debugging.
- # import pdb; pdb.set_trace()
- timex_property = Timex(travel_date)
-
- return len(timex_property.types) > 0 and "definite" not in timex_property.types
diff --git a/tests/experimental/101.corebot-bert-bidaf/model/setup.py b/tests/experimental/101.corebot-bert-bidaf/model/setup.py
deleted file mode 100644
index 86a7180b7..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model/setup.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-from setuptools import setup
-
-REQUIRES = [
- "torch",
- "tqdm",
- "pytorch-pretrained-bert",
- "onnxruntime>=0.4.0",
- "onnx>=1.5.0",
- "datatypes-date-time>=1.0.0.a1",
- "nltk>=3.4.1",
-]
-
-
-root = os.path.abspath(os.path.dirname(__file__))
-
-with open(os.path.join(root, "model_corebot101", "about.py")) as f:
- package_info = {}
- info = f.read()
- exec(info, package_info)
-
-setup(
- name=package_info["__title__"],
- version=package_info["__version__"],
- url=package_info["__uri__"],
- author=package_info["__author__"],
- description=package_info["__description__"],
- keywords="botframework azure botbuilder",
- long_description=package_info["__summary__"],
- license=package_info["__license__"],
- packages=[
- "model_corebot101.bert.train",
- "model_corebot101.bert.common",
- "model_corebot101.bert.model_runtime",
- "model_corebot101.bidaf.model_runtime",
- ],
- install_requires=REQUIRES,
- dependency_links=["https://github.com/pytorch/pytorch"],
- include_package_data=True,
- classifiers=[
- "Programming Language :: Python :: 3.6",
- "Intended Audience :: Developers",
- "License :: OSI Approved :: MIT License",
- "Operating System :: OS Independent",
- "Development Status :: 3 - Alpha",
- "Topic :: Scientific/Engineering :: Artificial Intelligence",
- ],
-)
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/__init__.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/__init__.py
deleted file mode 100644
index c702f213e..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Model Runtime."""
-from .model_cache import ModelCache
-
-__all__ = ["ModelCache"]
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/about.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/about.py
deleted file mode 100644
index ce4ebf0e1..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/about.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-__title__ = "model_runtime_svc_corebot101"
-__version__ = (
- os.environ["packageVersion"] if "packageVersion" in os.environ else "0.0.1"
-)
-__uri__ = "https://www.github.com/Microsoft/botbuilder-python"
-__author__ = "Microsoft"
-__description__ = "Microsoft Bot Framework Bot Builder"
-__summary__ = "Microsoft Bot Framework Bot Builder SDK for Python."
-__license__ = "MIT"
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/docker_init.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/docker_init.py
deleted file mode 100644
index c59fde586..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/docker_init.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Docker initialization.
-This is called from the Dockerfile when creating the model runtime service API
-container.
-"""
-import os
-from pathlib import Path
-from model_corebot101.language_helper import LanguageHelper
-
-# Initialize the models
-LH = LanguageHelper()
-HOME_DIR = str(Path.home())
-BERT_MODEL_DIR_DEFAULT = os.path.abspath(os.path.join(HOME_DIR, "models/bert"))
-BIDAF_MODEL_DIR_DEFAULT = os.path.abspath(os.path.join(HOME_DIR, "models/bidaf"))
-
-LH.initialize_models(
- bert_model_dir=BERT_MODEL_DIR_DEFAULT, bidaf_model_dir=BIDAF_MODEL_DIR_DEFAULT
-)
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/handlers/model_handler.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/handlers/model_handler.py
deleted file mode 100644
index ef6e78a86..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/handlers/model_handler.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Tornado handler to access the model runtime.
-
-To invoke:
- /v1.0/model?q=
-"""
-
-import logging
-import json
-from tornado.web import RequestHandler
-from model_corebot101.language_helper import LanguageHelper
-
-# pylint:disable=abstract-method
-class ModelHandler(RequestHandler):
- """Model Handler implementation to access the model runtime."""
-
- _handler_routes = ["/v1.0/model/$", "/v1.0/model$"]
-
- @classmethod
- def build_config(cls, ref_obj: dict):
- """Build the Tornado configuration for this handler."""
- return [(route, ModelHandler, ref_obj) for route in cls._handler_routes]
-
- def set_default_headers(self):
- """Set the default HTTP headers."""
- RequestHandler.set_default_headers(self)
- self.set_header("Content-Type", "application/json")
- self.set_header("Access-Control-Allow-Origin", "*")
- self.set_header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
- self.set_header("Access-Control-Allow-Methods", "OPTIONS, GET")
-
- # pylint:disable=attribute-defined-outside-init
- def initialize(self, language_helper: LanguageHelper):
- """Initialize the handler."""
- RequestHandler.initialize(self)
- self._language_helper = language_helper
- self._logger = logging.getLogger("MODEL_HANDLER")
-
- async def get(self):
- """Handle HTTP GET request."""
- text = self.get_argument("q", None, True)
- if not text:
- return (404, "Missing the q query string with the text")
-
- response = {}
- intent = self._language_helper.intents.serve(text)
- response["intent"] = intent if intent else "None"
- entities = self._language_helper.entities.serve(text)
- response["entities"] = entities if entities else "None"
- self.write(json.dumps(response))
- return (200, "Complete")
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/main.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/main.py
deleted file mode 100644
index a8f6ba5ca..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/main.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Model Runtime.
-Entry point for the model runtime.
-"""
-import os
-import signal
-import logging
-from logging.handlers import RotatingFileHandler
-import tornado
-from tornado.options import define, options
-from pathlib import Path
-from model_corebot101.language_helper import LanguageHelper
-from handlers.model_handler import ModelHandler
-
-HOME_DIR = str(Path.home())
-
-# Define Tornado options
-define("port", default=8880, help="HTTP port for model runtime to listen on", type=int)
-define(
- "bidaf_model_dir",
- default=os.path.abspath(os.path.join(HOME_DIR, "models/bidaf")),
- help="bidaf model directory",
-)
-define(
- "bert_model_dir",
- default=os.path.abspath(os.path.join(HOME_DIR, "models/bert")),
- help="bert model directory",
-)
-
-
-def setup_logging():
- """Set up logging."""
- logging.info("Setting up logging infrastructure")
-
- # Create the rotating log handler
- if not os.path.exists("logs"):
- os.mkdir("logs")
- handler = RotatingFileHandler(
- os.path.join("./logs", "model-runtime.log"),
- maxBytes=5 * 1024 ** 2, # 5 MB chunks,
- backupCount=5, # limit to 25 MB logs max
- )
-
- # Set the formatter
- handler.setFormatter(
- logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
- )
-
- # Setup the root logging with the necessary handlers
- log = logging.getLogger()
- log.addHandler(handler)
-
- # Set to info for normal processing
- log.setLevel(logging.INFO)
-
-
-# pylint:disable=unused-argument
-def signal_handler(sig_num, frame):
- """Stop activity on signal."""
- tornado.ioloop.IOLoop.instance().stop()
-
-
-def run():
- """Main entry point for model runtime api."""
-
- # Register signal handlers.
- logging.info("Preparing signal handlers..")
- signal.signal(signal.SIGINT, signal_handler)
- signal.signal(signal.SIGTERM, signal_handler)
-
- # Set up model cache.
- # If containerizing, suggest initializing the directories (and associated
- # file downloads) be performed during container build time.
- logging.info("Initializing model directories:")
- logging.info(" bert : %s", options.bert_model_dir)
- logging.info(" bidaf : %s", options.bidaf_model_dir)
-
- language_helper = LanguageHelper()
- if (
- language_helper.initialize_models(
- options.bert_model_dir, options.bidaf_model_dir
- )
- is False
- ):
- logging.error("Could not initilize model directories. Exiting..")
- return
-
- # Build the configuration
- logging.info("Building config..")
- ref_obj = {"language_helper": language_helper}
- app_config = ModelHandler.build_config(ref_obj)
-
- logging.info("Starting Tornado model runtime service..")
- application = tornado.web.Application(app_config)
- application.listen(options.port)
-
- # Protect the loop with a try/catch
- try:
- # Start the app and wait for a close
- tornado.ioloop.IOLoop.instance().start()
- finally:
- # handle error with shutting down loop
- tornado.ioloop.IOLoop.instance().stop()
-
-
-if __name__ == "__main__":
- setup_logging()
- run()
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/model_cache.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/model_cache.py
deleted file mode 100644
index 4b989a821..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/model_runtime_svc_corebot101/model_cache.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-"""Model Cache.
-Simple container for bidaf/bert models.
-"""
-import os
-import logging
-
-from model_corebot101.bidaf.model_runtime import BidafModelRuntime
-from model_corebot101.bert.model_runtime import BertModelRuntime
-
-# pylint:disable=line-too-long,bad-continuation
-class DeprecateModelCache(object):
- """Model Cache implementation."""
-
- def __init__(self):
- self._logger = logging.getLogger("ModelCache")
- self._bert_model_dir = None
- self._bidaf_model_dir = None
- self._bert_intents = None
- self._bidaf_entities = None
-
- def init_model_dir(self, bidaf_model_dir: str, bert_model_dir: str) -> bool:
- """ Initialize models """
- if not os.path.exists(bidaf_model_dir):
- # BiDAF needs no training, just download
- if not BidafModelRuntime.init_bidaf(bidaf_model_dir, True):
- self._logger.error(
- "bidaf model creation failed at model directory %s..",
- bidaf_model_dir,
- )
- return False
-
- if not os.path.exists(bert_model_dir):
- self._logger.error(
- 'BERT model directory does not exist "%s"', bert_model_dir
- )
- return False
-
- self._bert_model_dir = os.path.normpath(bert_model_dir)
- self._bidaf_model_dir = os.path.normpath(bidaf_model_dir)
-
- self._bert_intents = BertModelRuntime(
- model_dir=self._bert_model_dir, label_list=["Book flight", "Cancel"]
- )
- self._bidaf_entities = BidafModelRuntime(
- targets=["from", "to", "date"],
- queries={
- "from": "which city will you travel from?",
- "to": "which city will you travel to?",
- "date": "which date will you travel?",
- },
- model_dir=self._bidaf_model_dir,
- )
- self._logger.info("bidaf entities model created : %s..", self._bidaf_model_dir)
-
- return True
-
- @property
- def entities(self):
- """Get the model that detect entities: bidaf."""
- return self._bidaf_entities
-
- @property
- def intents(self):
- """Get the model that detect intents: bert."""
- return self._bert_intents
diff --git a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/setup.py b/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/setup.py
deleted file mode 100644
index 95958734c..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/model_runtime_svc/setup.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-from setuptools import setup
-
-REQUIRES = [
- "scikit-learn>=0.21.2",
- "scipy>=1.3.0",
- "tornado>=6.0.2",
- "model_corebot101>=0.0.1",
-]
-
-root = os.path.abspath(os.path.dirname(__file__))
-
-with open(os.path.join(root, "model_runtime_svc_corebot101", "about.py")) as f:
- package_info = {}
- info = f.read()
- exec(info, package_info)
-
-setup(
- name=package_info["__title__"],
- version=package_info["__version__"],
- url=package_info["__uri__"],
- author=package_info["__author__"],
- description=package_info["__description__"],
- keywords="botframework azure botbuilder",
- long_description=package_info["__summary__"],
- license=package_info["__license__"],
- packages=["model_runtime_svc_corebot101", "model_runtime_svc_corebot101.handlers"],
- install_requires=REQUIRES,
- dependency_links=["https://github.com/pytorch/pytorch"],
- include_package_data=True,
- classifiers=[
- "Programming Language :: Python :: 3.6",
- "Intended Audience :: Developers",
- "License :: OSI Approved :: MIT License",
- "Operating System :: OS Independent",
- "Development Status :: 3 - Alpha",
- "Topic :: Scientific/Engineering :: Artificial Intelligence",
- ],
-)
diff --git a/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_model_runtime.ipynb b/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_model_runtime.ipynb
deleted file mode 100644
index fc32cd77e..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_model_runtime.ipynb
+++ /dev/null
@@ -1,323 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Test the intent classifier\n",
- "This notebook uses the model trained in [bert_train.ipynb notebook](bert_train.ipynb). See the [README.md](../README.md) for instructions on how to use that notebook.\n",
- "\n",
- "## `model_corebot101` package\n",
- "This sample creates a separate python package (`model_corebot101`) which contains code to train (tune), evaluate and infer intent classifiers for this sample.\n",
- "\n",
- "\n",
- "## See also:\n",
- "- [bert_train.ipynb](bert_train.ipynb) to train the intent classifier model.\n",
- "- [bidaf_model_runtime.ipynb](bidaf_model_runtime.ipynb) to test the associated BiDAF model to test the entity classifier model.\n",
- "- [The model runtime](model_runtime.ipynb) to test the both the BERT and BiDAF model together."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "from model_corebot101.bert.model_runtime.bert_model_runtime import BertModelRuntime"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BertModelRuntime` class\n",
- "The `BertModelRuntime` class is used to perform the inferences against the bot utterances.\n",
- "\n",
- "The model is placed (during training) in the `/models/bert` directory which is packaged with the bot.\n",
- "\n",
- "The `label_list` is an array of intents."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "from pathlib import Path\n",
- "bert_model_dir = os.path.abspath(os.path.join(Path.home(), \"models/bert\"))\n",
- "s = BertModelRuntime(model_dir=bert_model_dir, label_list=[\"Book flight\", \"Cancel\"])"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BertModelRuntime.serve` method\n",
- "The `BertModelRuntime.serve` method is used to perform the classification against the bot utterances."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 3,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve('i want to travel from new york to berlin')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 4,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"please book a flight for me\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 5,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"from seattle to san\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 6,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"random random random 42\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 7,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"any\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 8,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"take me to New York\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 9,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"we'd like to go to seattle\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 10,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"not this one\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 11,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"I don't care about this one\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 12,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"I don't want to see that\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Cancel'"
- ]
- },
- "execution_count": 13,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"boring\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "'Book flight'"
- ]
- },
- "execution_count": 14,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"you have no clue how to book a flight\")"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "botsample",
- "language": "python",
- "name": "botsample"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.6.8"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_train.ipynb b/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_train.ipynb
deleted file mode 100644
index fe95eb688..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/notebooks/bert_train.ipynb
+++ /dev/null
@@ -1,281 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Train the intent classifier using pretrained BERT model as featurizer\n",
- "This notebook creates the BERT language classifier model. See the [README.md](../README.md) for instructions on how to run this sample.\n",
- "The resulting model is placed in the `/models/bert` directory which is packaged with the bot.\n",
- "\n",
- "## `model_corebot101` package\n",
- "This sample creates a separate python package (`model_corebot101`) which contains all the code to train, evaluate and infer intent classifiers for this sample.\n",
- "\n",
- "## See also:\n",
- "- [The BERT runtime model](bert_model_runtime.ipynb) to test the resulting intent classifier model.\n",
- "- [The BiDAF runtime model](bidaf_model_runtime.ipynb) to test the associated BiDAF model to test the entity classifier model.\n",
- "- [The model runtime](model_runtime.ipynb) to test the both the BERT and BiDAF model together.\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "from model_corebot101.bert.train import BertTrainEval"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BertTrainEvan.train_eval` method\n",
- "This method performs all the training and performs evaluation that's listed at the bottom of the output. Training may take several minutes to complete.\n",
- "\n",
- "The evaluation output should look something like the following:\n",
- "```bash\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - ***** Eval results *****\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - acc = 1.0\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - acc_and_f1 = 1.0\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - eval_loss = 0.06498947739601135\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - f1 = 1.0\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - global_step = 12\n",
- "06/02/2019 19:46:52 - INFO - model_corebot101.bert.train.bert_train_eval - loss = 0.02480666587750117\n",
- "```"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Bert Model training_data_dir is set to d:\\python\\daveta-docker-wizard\\apub\\samples\\flask\\101.corebot-bert-bidaf\\model\\model_corebot101\\bert\\training_data\n",
- "Bert Model model_dir is set to C:\\Users\\daveta\\models\\bert\n",
- "07/02/2019 07:16:09 - INFO - model_corebot101.bert.train.bert_train_eval - device: cpu n_gpu: 0, distributed training: False, 16-bits training: None\n",
- "07/02/2019 07:16:09 - INFO - pytorch_pretrained_bert.tokenization - loading vocabulary file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt from cache at C:\\Users\\daveta\\.pytorch_pretrained_bert\\26bc1ad6c0ac742e9b52263248f6d0f00068293b33709fae12320c0e35ccfbbb.542ce4285a40d23a559526243235df47c5f75c197f04f37d1a0c124c32c9a084\n",
- "07/02/2019 07:16:10 - INFO - pytorch_pretrained_bert.modeling - loading archive file https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz from cache at C:\\Users\\daveta\\.pytorch_pretrained_bert\\distributed_-1\\9c41111e2de84547a463fd39217199738d1e3deb72d4fec4399e6e241983c6f0.ae3cef932725ca7a30cdcb93fc6e09150a55e2a130ec7af63975a16c153ae2ba\n",
- "07/02/2019 07:16:10 - INFO - pytorch_pretrained_bert.modeling - extracting archive file C:\\Users\\daveta\\.pytorch_pretrained_bert\\distributed_-1\\9c41111e2de84547a463fd39217199738d1e3deb72d4fec4399e6e241983c6f0.ae3cef932725ca7a30cdcb93fc6e09150a55e2a130ec7af63975a16c153ae2ba to temp dir C:\\Users\\daveta\\AppData\\Local\\Temp\\tmp9hepebcl\n",
- "07/02/2019 07:16:13 - INFO - pytorch_pretrained_bert.modeling - Model config {\n",
- " \"attention_probs_dropout_prob\": 0.1,\n",
- " \"hidden_act\": \"gelu\",\n",
- " \"hidden_dropout_prob\": 0.1,\n",
- " \"hidden_size\": 768,\n",
- " \"initializer_range\": 0.02,\n",
- " \"intermediate_size\": 3072,\n",
- " \"max_position_embeddings\": 512,\n",
- " \"num_attention_heads\": 12,\n",
- " \"num_hidden_layers\": 12,\n",
- " \"type_vocab_size\": 2,\n",
- " \"vocab_size\": 30522\n",
- "}\n",
- "\n",
- "07/02/2019 07:16:16 - INFO - pytorch_pretrained_bert.modeling - Weights of BertForSequenceClassification not initialized from pretrained model: ['classifier.weight', 'classifier.bias']\n",
- "07/02/2019 07:16:16 - INFO - pytorch_pretrained_bert.modeling - Weights from pretrained model not used in BertForSequenceClassification: ['cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.seq_relationship.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.transform.LayerNorm.bias']\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - Writing example 0 of 16\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - guid: train-0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book flight from london to paris on feb 14th [SEP]\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 3462 2013 2414 2000 3000 2006 13114 6400 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - guid: train-1\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book flight to berlin on feb 14th [SEP]\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 3462 2000 4068 2006 13114 6400 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - guid: train-2\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book me a flight from london to paris [SEP]\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 2033 1037 3462 2013 2414 2000 3000 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - guid: train-3\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] bye [SEP]\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 9061 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - label: Cancel (id = 1)\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - guid: train-4\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] cancel booking [SEP]\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 17542 21725 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.common.bert_util - label: Cancel (id = 1)\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.train.bert_train_eval - ***** Running training *****\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.train.bert_train_eval - Num examples = 16\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.train.bert_train_eval - Batch size = 4\n",
- "07/02/2019 07:16:16 - INFO - model_corebot101.bert.train.bert_train_eval - Num steps = 12\n",
- "Epoch: 0%| | 0/3 [00:00, ?it/s]\n",
- "Iteration: 0%| | 0/4 [00:00, ?it/s]\n",
- "Iteration: 25%|██████████████████▎ | 1/4 [00:05<00:16, 5.40s/it]\n",
- "Iteration: 50%|████████████████████████████████████▌ | 2/4 [00:11<00:11, 5.60s/it]\n",
- "Iteration: 75%|██████████████████████████████████████████████████████▊ | 3/4 [00:17<00:05, 5.63s/it]\n",
- "Epoch: 33%|█████████████████████████▋ | 1/3 [00:22<00:45, 22.85s/it]\n",
- "Iteration: 0%| | 0/4 [00:00, ?it/s]\n",
- "Iteration: 25%|██████████████████▎ | 1/4 [00:05<00:17, 5.83s/it]\n",
- "Iteration: 50%|████████████████████████████████████▌ | 2/4 [00:11<00:11, 5.78s/it]\n",
- "Iteration: 75%|██████████████████████████████████████████████████████▊ | 3/4 [00:17<00:05, 5.73s/it]\n",
- "Epoch: 67%|███████████████████████████████████████████████████▎ | 2/3 [00:45<00:22, 22.85s/it]\n",
- "Iteration: 0%| | 0/4 [00:00, ?it/s]\n",
- "Iteration: 25%|██████████████████▎ | 1/4 [00:05<00:16, 5.50s/it]\n",
- "Iteration: 50%|████████████████████████████████████▌ | 2/4 [00:11<00:11, 5.51s/it]\n",
- "Iteration: 75%|██████████████████████████████████████████████████████▊ | 3/4 [00:16<00:05, 5.47s/it]\n",
- "Epoch: 100%|█████████████████████████████████████████████████████████████████████████████| 3/3 [01:07<00:00, 22.61s/it]\n",
- "07/02/2019 07:17:24 - INFO - pytorch_pretrained_bert.modeling - loading archive file C:\\Users\\daveta\\models\\bert\n",
- "07/02/2019 07:17:24 - INFO - pytorch_pretrained_bert.modeling - Model config {\n",
- " \"attention_probs_dropout_prob\": 0.1,\n",
- " \"hidden_act\": \"gelu\",\n",
- " \"hidden_dropout_prob\": 0.1,\n",
- " \"hidden_size\": 768,\n",
- " \"initializer_range\": 0.02,\n",
- " \"intermediate_size\": 3072,\n",
- " \"max_position_embeddings\": 512,\n",
- " \"num_attention_heads\": 12,\n",
- " \"num_hidden_layers\": 12,\n",
- " \"type_vocab_size\": 2,\n",
- " \"vocab_size\": 30522\n",
- "}\n",
- "\n",
- "07/02/2019 07:17:26 - INFO - pytorch_pretrained_bert.tokenization - loading vocabulary file C:\\Users\\daveta\\models\\bert\\vocab.txt\n",
- "07/02/2019 07:17:26 - INFO - model_corebot101.bert.train.bert_train_eval - DONE TRAINING.\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - Writing example 0 of 16\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - guid: dev-0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book flight from london to paris on feb 14th [SEP]\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 3462 2013 2414 2000 3000 2006 13114 6400 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - guid: dev-1\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book flight to berlin on feb 14th [SEP]\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 3462 2000 4068 2006 13114 6400 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - guid: dev-2\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] book me a flight from london to paris [SEP]\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 2338 2033 1037 3462 2013 2414 2000 3000 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - label: Book flight (id = 0)\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - guid: dev-3\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] bye [SEP]\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 9061 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - label: Cancel (id = 1)\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - *** Example ***\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - guid: dev-4\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - tokens: [CLS] cancel booking [SEP]\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_ids: 101 17542 21725 102 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - input_mask: 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - segment_ids: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.common.bert_util - label: Cancel (id = 1)\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.train.bert_train_eval - ***** Running evaluation *****\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.train.bert_train_eval - Num examples = 16\n",
- "07/02/2019 07:17:27 - INFO - model_corebot101.bert.train.bert_train_eval - Batch size = 8\n",
- "Evaluating: 100%|████████████████████████████████████████████████████████████████████████| 2/2 [00:04<00:00, 2.46s/it]\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - ***** Eval results *****\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - acc = 1.0\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - acc_and_f1 = 1.0\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - eval_loss = 0.026343628764152527\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - f1 = 1.0\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - global_step = 12\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - loss = 0.01322490597764651\n",
- "07/02/2019 07:17:32 - INFO - model_corebot101.bert.train.bert_train_eval - DONE EVALUATING.\n"
- ]
- }
- ],
- "source": [
- "BertTrainEval.train_eval(cleanup_output_dir=True)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Verify the output directory"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "0cd881fcb42b4d76a877907936a8d245",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(IntProgress(value=0, description='Verify Output', max=4, style=ProgressStyle(description_width=…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n"
- ]
- }
- ],
- "source": [
- "import os\n",
- "from pathlib import Path\n",
- "from tqdm import tqdm_notebook\n",
- "home_dir = str(Path.home())\n",
- "path = os.path.abspath(os.path.join(home_dir, \"models/bert\"))\n",
- "files_with_size = {file:os.path.getsize(os.path.join(path, file)) for file in os.listdir(path)}\n",
- "expected = {'config.json':326, 'eval_results.txt':119, 'pytorch_model.bin':437982182, 'vocab.txt':262030}\n",
- "for f in tqdm_notebook(expected.keys(), desc='Verify Output'):\n",
- " if f in files_with_size:\n",
- " delta = abs(expected[f] - files_with_size[f]) / expected[f]\n",
- " if delta > float(.30):\n",
- " raise Exception(f'Size of output file {f} is out of range of expected.')\n",
- " else:\n",
- " raise Exception(f'Expected file {f} missing from output.')"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "botsample",
- "language": "python",
- "name": "botsample"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.6.8"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests/experimental/101.corebot-bert-bidaf/notebooks/bidaf_model_runtime.ipynb b/tests/experimental/101.corebot-bert-bidaf/notebooks/bidaf_model_runtime.ipynb
deleted file mode 100644
index 1b145d4af..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/notebooks/bidaf_model_runtime.ipynb
+++ /dev/null
@@ -1,228 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Test the BiDAF runtime model\n",
- "This notebook uses the BiDAF language entitiy recognizer model. See the [README.md](../README.md) for instructions on how to run this sample.\n",
- "\n",
- "## `model_corebot101` package\n",
- "This sample creates a python package (`model_corebot101`) which contains all the code to train, evaluate and infer intent classifier for this sample.\n",
- "\n",
- "## See also:\n",
- "- [The BERT training model](bert_train.ipynb) to train the intent classifier model.\n",
- "- [The BERT runtime model](bert_model_runtime.ipynb) to test the BERT model to test the intent classifier model.\n",
- "- [The model runtime](model_runtime.ipynb) to test the both the BERT and BiDAF model together."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "from model_corebot101.bidaf.model_runtime.bidaf_model_runtime import BidafModelRuntime\n",
- "import os\n",
- "from pathlib import Path\n",
- "from IPython.display import display\n",
- "\n",
- "bidaf_model_dir = os.path.abspath(os.path.join(Path.home(), \"models/bidaf\"))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BidafModelRuntime` class\n",
- "The `BidafModelRuntime` class is used to perform the classification for entities on the bot utterances.\n",
- "\n",
- "The model is completely is downloaded and placed in the `/models/bidaf` directory.\n",
- "\n",
- "## `BidafModelRuntime.init_bidaf` method\n",
- "The `BidafModelRuntime.init_bidaf` method downloads the necessary ONNX model.\n",
- "\n",
- "Output should look like the following: \n",
- "\n",
- "```bash\n",
- "Creating bidaf model directory..\n",
- "Checking file ../../bot/cognitiveModels/bidaf\\bidaf.onnx..\n",
- "Downloading bidaf.onnx...\n",
- "```"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "bidaf model directory already present..\n",
- "[nltk_data] Downloading package punkt to\n",
- "[nltk_data] C:\\Users\\daveta\\models\\bidaf...\n",
- "[nltk_data] Package punkt is already up-to-date!\n",
- "[nltk_data] Downloading package punkt to\n",
- "[nltk_data] C:\\Users\\daveta\\AppData\\Roaming\\nltk_data...\n",
- "[nltk_data] Package punkt is already up-to-date!\n",
- "Checking file C:\\Users\\daveta\\models\\bidaf\\bidaf.onnx..\n",
- "bidaf.onnx downloaded already!\n"
- ]
- },
- {
- "data": {
- "text/plain": [
- "'The BiDAF model successfully downloaded.'"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- }
- ],
- "source": [
- "if not BidafModelRuntime.init_bidaf(bidaf_model_dir, True):\n",
- " display('The BiDAF model was not downloaded successfully. See output below for more details.')\n",
- "else:\n",
- " display('The BiDAF model successfully downloaded.')"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BidafModelRuntime` class\n",
- "The `BidafModelRuntime` class is used to perform the classification against the bot utterances.\n",
- "\n",
- "- `targets` : an array of entities to classify.\n",
- "- `queries` : examples passed to assist the classifier\n",
- "- `model_dir` : path to the model\n",
- "\n",
- "The output should resemble the following:\n",
- "\n",
- "```bash\n",
- "Loading Inference session from C:\\Users\\<>\\models\\bidaf\\bidaf.onnx..\n",
- "Inference session loaded..\n",
- "Processed queries..\n",
- "```\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "Loading Inference session from C:\\Users\\daveta\\models\\bidaf\\bidaf.onnx..\n",
- "Inference session loaded..\n",
- "Processed queries..\n"
- ]
- }
- ],
- "source": [
- "s = BidafModelRuntime(\n",
- " targets=[\"from\", \"to\", \"date\"],\n",
- " queries={\n",
- " \"from\": \"which city will you travel from?\",\n",
- " \"to\": \"which city will you travel to?\",\n",
- " \"date\": \"which date will you travel?\",\n",
- " },\n",
- " model_dir = bidaf_model_dir\n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'from': 'london', 'to': 'paris', 'date': 'feb 14th'}"
- ]
- },
- "execution_count": 4,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"flight to paris from london on feb 14th\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'from': 'london', 'to': 'paris', 'date': 'feb 14th'}"
- ]
- },
- "execution_count": 5,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"book flight from london to paris on feb 14th\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'from': 'berlin', 'to': 'berlin', 'date': '5th'}"
- ]
- },
- "execution_count": 6,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "s.serve(\"fly from berlin to paris on may 5th\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "botsample",
- "language": "python",
- "name": "botsample"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.6.8"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests/experimental/101.corebot-bert-bidaf/notebooks/model_runtime.ipynb b/tests/experimental/101.corebot-bert-bidaf/notebooks/model_runtime.ipynb
deleted file mode 100644
index 4b6b71c60..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/notebooks/model_runtime.ipynb
+++ /dev/null
@@ -1,206 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Test the intent classifier and entity extractor\n",
- "This notebook uses the pretrained BiDAF model and BERT model tuned in [bert_train.ipynb notebook](bert_train.ipynb). See the [README.md](../README.md) for instructions on how to use that notebook.\n",
- "\n",
- "## See also:\n",
- "- [bert_train.ipynb](bert_train.ipynb) to train the intent classifier model.\n",
- "- [bert_model_runtime.ipynb](bert_model_runtime.ipynb) to test the BERT intent classifier model.\n",
- "- [bidaf_model_runtime.ipynb](bidaf_model_runtime.ipynb) to test the associated BiDAF model to test the entity extractor model."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "from model_corebot101.bert.model_runtime.bert_model_runtime import BertModelRuntime\n",
- "from model_corebot101.bidaf.model_runtime.bidaf_model_runtime import BidafModelRuntime\n",
- "import os\n",
- "from pathlib import Path\n",
- "bidaf_model_dir = os.path.abspath(os.path.join(Path.home(), \"models/bidaf\"))\n",
- "bert_model_dir = os.path.abspath(os.path.join(Path.home(), \"models/bert\"))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "bidaf model directory already present..\n"
- ]
- }
- ],
- "source": [
- "BidafModelRuntime.init_bidaf(bidaf_model_dir, True)\n",
- "bidaf = BidafModelRuntime(\n",
- " targets=[\"from\", \"to\", \"date\"],\n",
- " queries={\n",
- " \"from\": \"which city will you travel from?\",\n",
- " \"to\": \"which city will you travel to?\",\n",
- " \"date\": \"which date will you travel?\",\n",
- " },\n",
- " model_dir = bidaf_model_dir\n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "bert = BertModelRuntime(model_dir=bert_model_dir, label_list=[\"Book flight\", \"Cancel\"])"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def serve(utterance):\n",
- " intent = bert.serve(utterance)\n",
- " entities = bidaf.serve(utterance)\n",
- " return intent, entities"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## `BertModelRuntime.serve` method\n",
- "The `BertModelRuntime.serve` method is used to perform the classification against the bot utterances."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"flight to paris from london on feb 14th\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"from seattle to san\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"random random random 42\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"any\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"take me to New York\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"we'd like to go to seattle\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"not this one\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"I don't care about this one\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"I don't want to see that\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"boring\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "serve(\"you have no clue how to book a flight\")"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.6.8"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests/experimental/101.corebot-bert-bidaf/requirements.txt b/tests/experimental/101.corebot-bert-bidaf/requirements.txt
deleted file mode 100644
index 496696f2c..000000000
--- a/tests/experimental/101.corebot-bert-bidaf/requirements.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-# Note: The model must be built first!
-# cd model
-#
-
-# The following are installed outside of requirements.txt
-# conda install -c pytorch pytorch -y
-# pip install onnxruntime
-# Install python package dependencies with the following:
-# `pip install -r requirements.txt`
-
-# Bot
-Flask>=1.0.2
-asyncio>=3.4.3
-requests>=2.18.1
-
-# Bot Framework
-botframework-connector>=4.4.0.b1
-botbuilder-schema>=4.4.0.b1
-botbuilder-core>=4.4.0.b1
-botbuilder-dialogs>=4.4.0.b1
-botbuilder-ai>=4.4.0.b1
-datatypes-date-time>=1.0.0.a1
-azure-cognitiveservices-language-luis>=0.2.0
-msrest>=0.6.6
-
-# Internal library - must be built first!
-model_corebot101>=0.0.1
-
-torch
-onnx
-onnxruntime
-tqdm>=4.32.1
-pytorch-pretrained-bert>=0.6.2
-nltk>=3.4.1
-numpy>=1.16.3
-scipy>=1.3.0
-scikit-learn>=0.21.2
-
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/__init__.py b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/__init__.py
deleted file mode 100644
index fe9caf948..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .action_based_messaging_extension_fetch_task_bot import (
- ActionBasedMessagingExtensionFetchTaskBot,
-)
-
-__all__ = ["ActionBasedMessagingExtensionFetchTaskBot"]
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/action_based_messaging_extension_fetch_task_bot.py b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/action_based_messaging_extension_fetch_task_bot.py
deleted file mode 100644
index 9e9c13fa9..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/bots/action_based_messaging_extension_fetch_task_bot.py
+++ /dev/null
@@ -1,229 +0,0 @@
-# Copyright (c) Microsoft Corp. All rights reserved.
-# Licensed under the MIT License.
-
-from typing import List
-import random
-from botbuilder.core import (
- CardFactory,
- MessageFactory,
- TurnContext,
-)
-from botbuilder.schema import Attachment
-from botbuilder.schema.teams import (
- MessagingExtensionAction,
- MessagingExtensionActionResponse,
- TaskModuleContinueResponse,
- MessagingExtensionResult,
- TaskModuleTaskInfo,
-)
-from botbuilder.core.teams import TeamsActivityHandler
-from example_data import ExampleData
-
-
-class ActionBasedMessagingExtensionFetchTaskBot(TeamsActivityHandler):
- async def on_message_activity(self, turn_context: TurnContext):
- value = turn_context.activity.value
- if value is not None:
- # This was a message from the card.
- answer = value["Answer"]
- choices = value["Choices"]
- reply = MessageFactory.text(
- f"{turn_context.activity.from_property.name} answered '{answer}' and chose '{choices}'."
- )
- await turn_context.send_activity(reply)
- else:
- # This is a regular text message.
- reply = MessageFactory.text(
- "Hello from ActionBasedMessagingExtensionFetchTaskBot."
- )
- await turn_context.send_activity(reply)
-
- async def on_teams_messaging_extension_fetch_task(
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- card = self._create_adaptive_card_editor()
- task_info = TaskModuleTaskInfo(
- card=card, height=450, title="Task Module Fetch Example", width=500
- )
- continue_response = TaskModuleContinueResponse(type="continue", value=task_info)
- return MessagingExtensionActionResponse(task=continue_response)
-
- async def on_teams_messaging_extension_submit_action( # pylint: disable=unused-argument
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- question = action.data["Question"]
- multi_select = action.data["MultiSelect"]
- option1 = action.data["Option1"]
- option2 = action.data["Option2"]
- option3 = action.data["Option3"]
- preview_card = self._create_adaptive_card_preview(
- user_text=question,
- is_multi_select=multi_select,
- option1=option1,
- option2=option2,
- option3=option3,
- )
-
- extension_result = MessagingExtensionResult(
- type="botMessagePreview",
- activity_preview=MessageFactory.attachment(preview_card),
- )
- return MessagingExtensionActionResponse(compose_extension=extension_result)
-
- async def on_teams_messaging_extension_bot_message_preview_edit( # pylint: disable=unused-argument
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- activity_preview = action.bot_activity_preview[0]
- content = activity_preview.attachments[0].content
- data = self._get_example_data(content)
- card = self._create_adaptive_card_editor(
- data.question,
- data.is_multi_select,
- data.option1,
- data.option2,
- data.option3,
- )
- task_info = TaskModuleTaskInfo(
- card=card, height=450, title="Task Module Fetch Example", width=500
- )
- continue_response = TaskModuleContinueResponse(type="continue", value=task_info)
- return MessagingExtensionActionResponse(task=continue_response)
-
- async def on_teams_messaging_extension_bot_message_preview_send( # pylint: disable=unused-argument
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- activity_preview = action.bot_activity_preview[0]
- content = activity_preview.attachments[0].content
- data = self._get_example_data(content)
- card = self._create_adaptive_card_preview(
- data.question,
- data.is_multi_select,
- data.option1,
- data.option2,
- data.option3,
- )
- message = MessageFactory.attachment(card)
- await turn_context.send_activity(message)
-
- def _get_example_data(self, content: dict) -> ExampleData:
- body = content["body"]
- question = body[1]["text"]
- choice_set = body[3]
- multi_select = "isMultiSelect" in choice_set
- option1 = choice_set["choices"][0]["value"]
- option2 = choice_set["choices"][1]["value"]
- option3 = choice_set["choices"][2]["value"]
- return ExampleData(question, multi_select, option1, option2, option3)
-
- def _create_adaptive_card_editor(
- self,
- user_text: str = None,
- is_multi_select: bool = False,
- option1: str = None,
- option2: str = None,
- option3: str = None,
- ) -> Attachment:
- return CardFactory.adaptive_card(
- {
- "actions": [
- {
- "data": {"submitLocation": "messagingExtensionFetchTask"},
- "title": "Submit",
- "type": "Action.Submit",
- }
- ],
- "body": [
- {
- "text": "This is an Adaptive Card within a Task Module",
- "type": "TextBlock",
- "weight": "bolder",
- },
- {"type": "TextBlock", "text": "Enter text for Question:"},
- {
- "id": "Question",
- "placeholder": "Question text here",
- "type": "Input.Text",
- "value": user_text,
- },
- {"type": "TextBlock", "text": "Options for Question:"},
- {"type": "TextBlock", "text": "Is Multi-Select:"},
- {
- "choices": [
- {"title": "True", "value": "true"},
- {"title": "False", "value": "false"},
- ],
- "id": "MultiSelect",
- "isMultiSelect": "false",
- "style": "expanded",
- "type": "Input.ChoiceSet",
- "value": "true" if is_multi_select else "false",
- },
- {
- "id": "Option1",
- "placeholder": "Option 1 here",
- "type": "Input.Text",
- "value": option1,
- },
- {
- "id": "Option2",
- "placeholder": "Option 2 here",
- "type": "Input.Text",
- "value": option2,
- },
- {
- "id": "Option3",
- "placeholder": "Option 3 here",
- "type": "Input.Text",
- "value": option3,
- },
- ],
- "type": "AdaptiveCard",
- "version": "1.0",
- }
- )
-
- def _create_adaptive_card_preview(
- self,
- user_text: str = None,
- is_multi_select: bool = False,
- option1: str = None,
- option2: str = None,
- option3: str = None,
- ) -> Attachment:
- return CardFactory.adaptive_card(
- {
- "actions": [
- {
- "type": "Action.Submit",
- "title": "Submit",
- "data": {"submitLocation": "messagingExtensionSubmit"},
- }
- ],
- "body": [
- {
- "text": "Adaptive Card from Task Module",
- "type": "TextBlock",
- "weight": "bolder",
- },
- {"text": user_text, "type": "TextBlock", "id": "Question"},
- {
- "id": "Answer",
- "placeholder": "Answer here...",
- "type": "Input.Text",
- },
- {
- "choices": [
- {"title": option1, "value": option1},
- {"title": option2, "value": option2},
- {"title": option3, "value": option3},
- ],
- "id": "Choices",
- "isMultiSelect": is_multi_select,
- "style": "expanded",
- "type": "Input.ChoiceSet",
- },
- ],
- "type": "AdaptiveCard",
- "version": "1.0",
- }
- )
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/example_data.py b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/example_data.py
deleted file mode 100644
index 79dede038..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/example_data.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-
-class ExampleData(object):
- def __init__(
- self,
- question: str = None,
- is_multi_select: bool = False,
- option1: str = None,
- option2: str = None,
- option3: str = None,
- ):
- self.question = question
- self.is_multi_select = is_multi_select
- self.option1 = option1
- self.option2 = option2
- self.option3 = option3
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/requirements.txt b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-color.png b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-color.png and /dev/null differ
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-outline.png b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/icon-outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/manifest.json b/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/manifest.json
deleted file mode 100644
index 8c87f9f40..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension-fetch-task/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,67 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "<>",
- "packageName": "com.microsoft.teams.samples",
- "developer": {
- "name": "Microsoft",
- "websiteUrl": "https://dev.botframework.com",
- "privacyUrl": "https://privacy.microsoft.com",
- "termsOfUseUrl": "https://www.microsoft.com/en-us/legal/intellectualproperty/copyright/default.aspx"
- },
- "icons": {
- "color": "icon-color.png",
- "outline": "icon-outline.png"
- },
- "name": {
- "short": "Preview Messaging Extension",
- "full": "Microsoft Teams Action Based Messaging Extension with Preview"
- },
- "description": {
- "short": "Sample demonstrating an Action Based Messaging Extension with Preview",
- "full": "Sample Action Messaging Extension built with the Bot Builder SDK demonstrating Preview"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "team"
- ]
- }
- ],
- "composeExtensions": [
- {
- "botId": "<>",
- "canUpdateConfiguration": false,
- "commands": [
- {
- "id": "createWithPreview",
- "type": "action",
- "title": "Create Card",
- "description": "Example of creating a Card",
- "initialRun": false,
- "fetchTask": true,
- "context": [
- "commandBox",
- "compose",
- "message"
- ],
- "parameters": [
- {
- "name": "param",
- "title": "param",
- "description": ""
- }
- ]
- }
- ]
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/action-based-messaging-extension/app.py b/tests/teams/scenarios/action-based-messaging-extension/app.py
deleted file mode 100644
index a65ff81f1..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/app.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import json
-import sys
-from datetime import datetime
-
-from aiohttp import web
-from aiohttp.web import Request, Response, json_response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-from bots import TeamsMessagingExtensionsActionBot
-from config import DefaultConfig
-
-CONFIG = DefaultConfig()
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error(context: TurnContext, error: Exception):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = on_error
-
-# Create the Bot
-BOT = TeamsMessagingExtensionsActionBot()
-
-
-# Listen for incoming requests on /api/messages
-async def messages(req: Request) -> Response:
- # Main bot message handler.
- if "application/json" in req.headers["Content-Type"]:
- body = await req.json()
- else:
- return Response(status=415)
-
- activity = Activity().deserialize(body)
- auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
-
- try:
- invoke_response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- if invoke_response:
- return json_response(data=invoke_response.body, status=invoke_response.status)
- return Response(status=201)
- except PermissionError:
- return Response(status=401)
- except Exception:
- return Response(status=500)
-
-
-APP = web.Application()
-APP.router.add_post("/api/messages", messages)
-
-if __name__ == "__main__":
- try:
- web.run_app(APP, host="localhost", port=CONFIG.PORT)
- except Exception as error:
- raise error
diff --git a/tests/teams/scenarios/action-based-messaging-extension/bots/__init__.py b/tests/teams/scenarios/action-based-messaging-extension/bots/__init__.py
deleted file mode 100644
index f67c560a6..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .teams_messaging_extensions_action_bot import TeamsMessagingExtensionsActionBot
-
-__all__ = ["TeamsMessagingExtensionsActionBot"]
diff --git a/tests/teams/scenarios/action-based-messaging-extension/bots/teams_messaging_extensions_action_bot.py b/tests/teams/scenarios/action-based-messaging-extension/bots/teams_messaging_extensions_action_bot.py
deleted file mode 100644
index 014e992a0..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/bots/teams_messaging_extensions_action_bot.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corp. All rights reserved.
-# Licensed under the MIT License.
-
-from typing import List
-import random
-from botbuilder.core import (
- CardFactory,
- MessageFactory,
- TurnContext,
- UserState,
- ConversationState,
- PrivateConversationState,
-)
-from botbuilder.schema import ChannelAccount, HeroCard, CardAction, CardImage
-from botbuilder.schema.teams import (
- MessagingExtensionAction,
- MessagingExtensionActionResponse,
- MessagingExtensionAttachment,
- MessagingExtensionResult,
-)
-from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
-from botbuilder.azure import CosmosDbPartitionedStorage
-
-
-class TeamsMessagingExtensionsActionBot(TeamsActivityHandler):
- async def on_teams_messaging_extension_submit_action_dispatch(
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- if action.command_id == "createCard":
- return await self.create_card_command(turn_context, action)
- elif action.command_id == "shareMessage":
- return await self.share_message_command(turn_context, action)
-
- async def create_card_command(
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- title = action.data["title"]
- subTitle = action.data["subTitle"]
- text = action.data["text"]
-
- card = HeroCard(title=title, subtitle=subTitle, text=text)
- cardAttachment = CardFactory.hero_card(card)
- attachment = MessagingExtensionAttachment(
- content=card,
- content_type=CardFactory.content_types.hero_card,
- preview=cardAttachment,
- )
- attachments = [attachment]
-
- extension_result = MessagingExtensionResult(
- attachment_layout="list", type="result", attachments=attachments
- )
- return MessagingExtensionActionResponse(compose_extension=extension_result)
-
- async def share_message_command(
- self, turn_context: TurnContext, action: MessagingExtensionAction
- ) -> MessagingExtensionActionResponse:
- # The user has chosen to share a message by choosing the 'Share Message' context menu command.
-
- # TODO: .user is None
- title = "Shared Message" # f'{action.message_payload.from_property.user.display_name} orignally sent this message:'
- text = action.message_payload.body.content
- card = HeroCard(title=title, text=text)
-
- if not action.message_payload.attachments is None:
- # This sample does not add the MessagePayload Attachments. This is left as an
- # exercise for the user.
- card.subtitle = (
- f"({len(action.message_payload.attachments)} Attachments not included)"
- )
-
- # This Messaging Extension example allows the user to check a box to include an image with the
- # shared message. This demonstrates sending custom parameters along with the message payload.
- include_image = action.data["includeImage"]
- if include_image == "true":
- image = CardImage(
- url="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"
- )
- card.images = [image]
-
- cardAttachment = CardFactory.hero_card(card)
- attachment = MessagingExtensionAttachment(
- content=card,
- content_type=CardFactory.content_types.hero_card,
- preview=cardAttachment,
- )
- attachments = [attachment]
-
- extension_result = MessagingExtensionResult(
- attachment_layout="list", type="result", attachments=attachments
- )
- return MessagingExtensionActionResponse(compose_extension=extension_result)
diff --git a/tests/teams/scenarios/action-based-messaging-extension/config.py b/tests/teams/scenarios/action-based-messaging-extension/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/action-based-messaging-extension/requirements.txt b/tests/teams/scenarios/action-based-messaging-extension/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-color.png b/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-color.png and /dev/null differ
diff --git a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-outline.png b/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/icon-outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/manifest.json b/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/manifest.json
deleted file mode 100644
index 1b24a5665..000000000
--- a/tests/teams/scenarios/action-based-messaging-extension/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,78 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "00000000-0000-0000-0000-000000000000",
- "packageName": "com.microsoft.teams.samples",
- "developer": {
- "name": "Microsoft",
- "websiteUrl": "https://dev.botframework.com",
- "privacyUrl": "https://privacy.microsoft.com",
- "termsOfUseUrl": "https://www.microsoft.com/en-us/legal/intellectualproperty/copyright/default.aspx"
- },
- "name": {
- "short": "Action Messaging Extension",
- "full": "Microsoft Teams Action Based Messaging Extension"
- },
- "description": {
- "short": "Sample demonstrating an Action Based Messaging Extension",
- "full": "Sample Action Messaging Extension built with the Bot Builder SDK"
- },
- "icons": {
- "outline": "icon-outline.png",
- "color": "icon-color.png"
- },
- "accentColor": "#FFFFFF",
- "composeExtensions": [
- {
- "botId": "00000000-0000-0000-0000-000000000000",
- "commands": [
- {
- "id": "createCard",
- "type": "action",
- "context": [ "compose" ],
- "description": "Command to run action to create a Card from Compose Box",
- "title": "Create Card",
- "parameters": [
- {
- "name": "title",
- "title": "Card title",
- "description": "Title for the card",
- "inputType": "text"
- },
- {
- "name": "subTitle",
- "title": "Subtitle",
- "description": "Subtitle for the card",
- "inputType": "text"
- },
- {
- "name": "text",
- "title": "Text",
- "description": "Text for the card",
- "inputType": "textarea"
- }
- ]
- },
- {
- "id": "shareMessage",
- "type": "action",
- "context": [ "message" ],
- "description": "Test command to run action on message context (message sharing)",
- "title": "Share Message",
- "parameters": [
- {
- "name": "includeImage",
- "title": "Include Image",
- "description": "Include image in Hero Card",
- "inputType": "toggle"
- }
- ]
- }
- ]
- }
- ],
- "permissions": [
- "identity"
- ]
-}
diff --git a/tests/teams/scenarios/activity-update-and-delete/README.md b/tests/teams/scenarios/activity-update-and-delete/README.md
deleted file mode 100644
index f1a48af72..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# EchoBot
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/activity-update-and-delete/app.py b/tests/teams/scenarios/activity-update-and-delete/app.py
deleted file mode 100644
index d897fb8e7..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/app.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import ActivitiyUpdateAndDeleteBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-ACTIVITY_IDS = []
-# Create the Bot
-BOT = ActivitiyUpdateAndDeleteBot(ACTIVITY_IDS)
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/activity-update-and-delete/bots/__init__.py b/tests/teams/scenarios/activity-update-and-delete/bots/__init__.py
deleted file mode 100644
index 8aa561191..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .activity_update_and_delete_bot import ActivitiyUpdateAndDeleteBot
-
-__all__ = ["ActivitiyUpdateAndDeleteBot"]
diff --git a/tests/teams/scenarios/activity-update-and-delete/bots/activity_update_and_delete_bot.py b/tests/teams/scenarios/activity-update-and-delete/bots/activity_update_and_delete_bot.py
deleted file mode 100644
index 1a90329a8..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/bots/activity_update_and_delete_bot.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import MessageFactory, TurnContext, ActivityHandler
-
-
-class ActivitiyUpdateAndDeleteBot(ActivityHandler):
- def __init__(self, activity_ids):
- self.activity_ids = activity_ids
-
- async def on_message_activity(self, turn_context: TurnContext):
- TurnContext.remove_recipient_mention(turn_context.activity)
- if turn_context.activity.text == "delete":
- for activity in self.activity_ids:
- await turn_context.delete_activity(activity)
-
- self.activity_ids = []
- else:
- await self._send_message_and_log_activity_id(
- turn_context, turn_context.activity.text
- )
-
- for activity_id in self.activity_ids:
- new_activity = MessageFactory.text(turn_context.activity.text)
- new_activity.id = activity_id
- await turn_context.update_activity(new_activity)
-
- async def _send_message_and_log_activity_id(
- self, turn_context: TurnContext, text: str
- ):
- reply_activity = MessageFactory.text(text)
- resource_response = await turn_context.send_activity(reply_activity)
- self.activity_ids.append(resource_response.id)
diff --git a/tests/teams/scenarios/activity-update-and-delete/config.py b/tests/teams/scenarios/activity-update-and-delete/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/activity-update-and-delete/requirements.txt b/tests/teams/scenarios/activity-update-and-delete/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/color.png b/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/manifest.json b/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/manifest.json
deleted file mode 100644
index 697a9a3e8..000000000
--- a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "",
- "packageName": "com.teams.sample.conversationUpdate",
- "developer": {
- "name": "ConversationUpdatesBot",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "ConversationUpdatesBot",
- "full": "ConversationUpdatesBot"
- },
- "description": {
- "short": "ConversationUpdatesBot",
- "full": "ConversationUpdatesBot"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "",
- "scopes": [
- "groupchat",
- "team",
- "personal"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/outline.png b/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/activity-update-and-delete/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/conversation-update/README.md b/tests/teams/scenarios/conversation-update/README.md
deleted file mode 100644
index f1a48af72..000000000
--- a/tests/teams/scenarios/conversation-update/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# EchoBot
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/conversation-update/app.py b/tests/teams/scenarios/conversation-update/app.py
deleted file mode 100644
index 17590f61d..000000000
--- a/tests/teams/scenarios/conversation-update/app.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import ConversationUpdateBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-
-# Create the Bot
-BOT = ConversationUpdateBot()
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/conversation-update/bots/__init__.py b/tests/teams/scenarios/conversation-update/bots/__init__.py
deleted file mode 100644
index ae2bc0930..000000000
--- a/tests/teams/scenarios/conversation-update/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .conversation_update_bot import ConversationUpdateBot
-
-__all__ = ["ConversationUpdateBot"]
diff --git a/tests/teams/scenarios/conversation-update/bots/conversation_update_bot.py b/tests/teams/scenarios/conversation-update/bots/conversation_update_bot.py
deleted file mode 100644
index 6522a633f..000000000
--- a/tests/teams/scenarios/conversation-update/bots/conversation_update_bot.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import MessageFactory, TurnContext
-from botbuilder.core.teams import TeamsActivityHandler
-from botbuilder.schema.teams import ChannelInfo, TeamInfo, TeamsChannelAccount
-
-
-class ConversationUpdateBot(TeamsActivityHandler):
- async def on_teams_channel_created_activity(
- self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
- ):
- return await turn_context.send_activity(
- MessageFactory.text(
- f"The new channel is {channel_info.name}. The channel id is {channel_info.id}"
- )
- )
-
- async def on_teams_channel_deleted_activity(
- self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
- ):
- return await turn_context.send_activity(
- MessageFactory.text(f"The deleted channel is {channel_info.name}")
- )
-
- async def on_teams_channel_renamed_activity(
- self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
- ):
- return await turn_context.send_activity(
- MessageFactory.text(f"The new channel name is {channel_info.name}")
- )
-
- async def on_teams_team_renamed_activity(
- self, team_info: TeamInfo, turn_context: TurnContext
- ):
- return await turn_context.send_activity(
- MessageFactory.text(f"The new team name is {team_info.name}")
- )
-
- async def on_teams_members_added_activity(
- self, teams_members_added: [TeamsChannelAccount], turn_context: TurnContext
- ):
- for member in teams_members_added:
- await turn_context.send_activity(
- MessageFactory.text(f"Welcome your new team member {member.id}")
- )
- return
-
- async def on_teams_members_removed_activity(
- self, teams_members_removed: [TeamsChannelAccount], turn_context: TurnContext
- ):
- for member in teams_members_removed:
- await turn_context.send_activity(
- MessageFactory.text(f"Say goodbye to your team member {member.id}")
- )
- return
diff --git a/tests/teams/scenarios/conversation-update/requirements.txt b/tests/teams/scenarios/conversation-update/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/conversation-update/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/conversation-update/teams_app_manifest/color.png b/tests/teams/scenarios/conversation-update/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/conversation-update/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/conversation-update/teams_app_manifest/manifest.json b/tests/teams/scenarios/conversation-update/teams_app_manifest/manifest.json
deleted file mode 100644
index 697a9a3e8..000000000
--- a/tests/teams/scenarios/conversation-update/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "",
- "packageName": "com.teams.sample.conversationUpdate",
- "developer": {
- "name": "ConversationUpdatesBot",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "ConversationUpdatesBot",
- "full": "ConversationUpdatesBot"
- },
- "description": {
- "short": "ConversationUpdatesBot",
- "full": "ConversationUpdatesBot"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "",
- "scopes": [
- "groupchat",
- "team",
- "personal"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/conversation-update/teams_app_manifest/outline.png b/tests/teams/scenarios/conversation-update/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/conversation-update/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/create-thread-in-channel/README.md b/tests/teams/scenarios/create-thread-in-channel/README.md
deleted file mode 100644
index 40e84f525..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# EchoBot
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/create-thread-in-channel/app.py b/tests/teams/scenarios/create-thread-in-channel/app.py
deleted file mode 100644
index 3c55decbe..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/app.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import CreateThreadInTeamsBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-
-# Create the Bot
-BOT = CreateThreadInTeamsBot(APP.config["APP_ID"])
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/create-thread-in-channel/bots/__init__.py b/tests/teams/scenarios/create-thread-in-channel/bots/__init__.py
deleted file mode 100644
index f5e8a121c..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .create_thread_in_teams_bot import CreateThreadInTeamsBot
-
-__all__ = ["CreateThreadInTeamsBot"]
diff --git a/tests/teams/scenarios/create-thread-in-channel/bots/create_thread_in_teams_bot.py b/tests/teams/scenarios/create-thread-in-channel/bots/create_thread_in_teams_bot.py
deleted file mode 100644
index 6feca9af4..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/bots/create_thread_in_teams_bot.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import MessageFactory, TurnContext
-from botbuilder.core.teams import (
- teams_get_channel_id,
- TeamsActivityHandler,
- TeamsInfo
-)
-
-
-class CreateThreadInTeamsBot(TeamsActivityHandler):
- def __init__(self, id):
- self.id = id
-
- async def on_message_activity(self, turn_context: TurnContext):
- message = MessageFactory.text("first message")
- channel_id = teams_get_channel_id(turn_context.activity)
- result = await TeamsInfo.send_message_to_teams_channel(turn_context, message, channel_id)
-
- await turn_context.adapter.continue_conversation(result[0], self._continue_conversation_callback, self.id)
-
- async def _continue_conversation_callback(self, turn_context):
- await turn_context.send_activity(MessageFactory.text("second message"))
diff --git a/tests/teams/scenarios/create-thread-in-channel/requirements.txt b/tests/teams/scenarios/create-thread-in-channel/requirements.txt
deleted file mode 100644
index 7e54b62ec..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.4.0b1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/color.png b/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/manifest.json b/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/manifest.json
deleted file mode 100644
index b9d5b596f..000000000
--- a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "<>",
- "packageName": "com.teams.sample.conversationUpdate",
- "developer": {
- "name": "MentionBot",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "MentionBot",
- "full": "MentionBot"
- },
- "description": {
- "short": "MentionBot",
- "full": "MentionBot"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "groupchat",
- "team",
- "personal"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/outline.png b/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/create-thread-in-channel/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/file-upload/README.md b/tests/teams/scenarios/file-upload/README.md
deleted file mode 100644
index f68159779..000000000
--- a/tests/teams/scenarios/file-upload/README.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# FileUpload
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Prerequisites
-- Open Notepad (or another text editor) to save some values as you complete the setup.
-
-- Ngrok setup
-1. Download and install [Ngrok](https://ngrok.com/download)
-2. In terminal navigate to the directory where Ngrok is installed
-3. Run this command: ```ngrok http -host-header=rewrite 3978 ```
-4. Copy the https://xxxxxxxx.ngrok.io address and put it into notepad. **NOTE** You want the https address.
-
-- Azure setup
-1. Login to the [Azure Portal]((https://portal.azure.com)
-2. (optional) create a new resource group if you don't currently have one
-3. Go to your resource group
-4. Click "Create a new resource"
-5. Search for "Bot Channel Registration"
-6. Click Create
-7. Enter bot name, subscription
-8. In the "Messaging endpoint url" enter the ngrok address from earlier.
-8a. Finish the url with "/api/messages. It should look like ```https://xxxxxxxxx.ngrok.io/api/messages```
-9. Click the "Microsoft App Id and password" box
-10. Click on "Create New"
-11. Click on "Create App ID in the App Registration Portal"
-12. Click "New registration"
-13. Enter a name
-14. Under "Supported account types" select "Accounts in any organizational directory and personal Microsoft accounts"
-15. Click register
-16. Copy the application (client) ID and put it in Notepad. Label it "Microsoft App ID"
-17. Go to "Certificates & Secrets"
-18. Click "+ New client secret"
-19. Enter a description
-20. Click "Add"
-21. Copy the value and put it into Notepad. Label it "Password"
-22. (back in the channel registration view) Copy/Paste the Microsoft App ID and Password into their respective fields
-23. Click Create
-24. Go to "Resource groups" on the left
-25. Select the resource group that the bot channel reg was created in
-26. Select the bot channel registration
-27. Go to Channels
-28. Select the "Teams" icon under "Add a featured channel
-29. Click Save
-
-- Updating Sample Project Settings
-1. Open the project
-2. Open config.py
-3. Enter the app id under the ```MicrosoftAppId``` and the password under the ```MicrosoftAppPassword```
-4. Save the close the file
-5. Under the teams_app_manifest folder open the manifest.json file
-6. Update the ```botId``` with the Microsoft App ID from before
-7. Update the ```id``` with the Microsoft App ID from before
-8. Save the close the file
-
-- Uploading the bot to Teams
-1. In file explorer navigate to the TeamsAppManifest folder in the project
-2. Select the 3 files and zip them
-3. Open Teams
-4. Click on "Apps"
-5. Select "Upload a custom app" on the left at the bottom
-6. Select the zip
-7. Select for you
-8. (optionally) click install if prompted
-9. Click open
-
-## To try this sample
-
-- Clone the repository
-
- ```bash
- git clone https://github.com/Microsoft/botbuilder-python.git
- ```
-
-- In a terminal, navigate to `samples/python/scenarios/file-upload`
-
- - From a terminal
-
- ```bash
- pip install -r requirements.txt
- python app.py
- ```
-
-- Interacting with the bot
-1. Send a message to your bot in Teams
-2. Confirm you are getting a 200 back in Ngrok
-3. Click Accept on the card that is shown
-4. Confirm you see a 2nd 200 in Ngrok
-5. In Teams go to Files -> OneDrive -> Applications
-
-## Testing the bot using Bot Framework Emulator
-
-[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to the bot using Bot Framework Emulator
-
-- Launch Bot Framework Emulator
-- File -> Open Bot
-- Enter a Bot URL of `http://localhost:3978/api/messages`
-
-## Deploy the bot to Azure
-
-To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
-- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
-- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
-- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
-- [Azure Portal](https://portal.azure.com)
-- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/)
-- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/file-upload/app.py b/tests/teams/scenarios/file-upload/app.py
deleted file mode 100644
index 17cbac17b..000000000
--- a/tests/teams/scenarios/file-upload/app.py
+++ /dev/null
@@ -1,91 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-import traceback
-from datetime import datetime
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import TeamsFileBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error(context: TurnContext, error: Exception):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
- print(traceback.format_exc())
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = on_error
-
-# Create the Bot
-BOT = TeamsFileBot()
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/file-upload/bots/__init__.py b/tests/teams/scenarios/file-upload/bots/__init__.py
deleted file mode 100644
index ba9df627e..000000000
--- a/tests/teams/scenarios/file-upload/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .teams_file_bot import TeamsFileBot
-
-__all__ = ["TeamsFileBot"]
diff --git a/tests/teams/scenarios/file-upload/bots/teams_file_bot.py b/tests/teams/scenarios/file-upload/bots/teams_file_bot.py
deleted file mode 100644
index 39fb047a7..000000000
--- a/tests/teams/scenarios/file-upload/bots/teams_file_bot.py
+++ /dev/null
@@ -1,185 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from datetime import datetime
-import os
-
-import requests
-from botbuilder.core import TurnContext
-from botbuilder.core.teams import TeamsActivityHandler
-from botbuilder.schema import (
- Activity,
- ChannelAccount,
- ActivityTypes,
- ConversationAccount,
- Attachment,
-)
-from botbuilder.schema.teams import (
- FileDownloadInfo,
- FileConsentCard,
- FileConsentCardResponse,
- FileInfoCard,
-)
-from botbuilder.schema.teams.additional_properties import ContentType
-
-
-class TeamsFileBot(TeamsActivityHandler):
- async def on_message_activity(self, turn_context: TurnContext):
- message_with_file_download = (
- False
- if not turn_context.activity.attachments
- else turn_context.activity.attachments[0].content_type == ContentType.FILE_DOWNLOAD_INFO
- )
-
- if message_with_file_download:
- # Save an uploaded file locally
- file = turn_context.activity.attachments[0]
- file_download = FileDownloadInfo.deserialize(file.content)
- file_path = "files/" + file.name
-
- response = requests.get(file_download.download_url, allow_redirects=True)
- open(file_path, "wb").write(response.content)
-
- reply = self._create_reply(
- turn_context.activity, f"Complete downloading {file.name}", "xml"
- )
- await turn_context.send_activity(reply)
- else:
- # Attempt to upload a file to Teams. This will display a confirmation to
- # the user (Accept/Decline card). If they accept, on_teams_file_consent_accept
- # will be called, otherwise on_teams_file_consent_decline.
- filename = "teams-logo.png"
- file_path = "files/" + filename
- file_size = os.path.getsize(file_path)
- await self._send_file_card(turn_context, filename, file_size)
-
- async def _send_file_card(
- self, turn_context: TurnContext, filename: str, file_size: int
- ):
- """
- Send a FileConsentCard to get permission from the user to upload a file.
- """
-
- consent_context = {"filename": filename}
-
- file_card = FileConsentCard(
- description="This is the file I want to send you",
- size_in_bytes=file_size,
- accept_context=consent_context,
- decline_context=consent_context
- )
-
- as_attachment = Attachment(
- content=file_card.serialize(), content_type=ContentType.FILE_CONSENT_CARD, name=filename
- )
-
- reply_activity = self._create_reply(turn_context.activity)
- reply_activity.attachments = [as_attachment]
- await turn_context.send_activity(reply_activity)
-
- async def on_teams_file_consent_accept(
- self,
- turn_context: TurnContext,
- file_consent_card_response: FileConsentCardResponse
- ):
- """
- The user accepted the file upload request. Do the actual upload now.
- """
-
- file_path = "files/" + file_consent_card_response.context["filename"]
- file_size = os.path.getsize(file_path)
-
- headers = {
- "Content-Length": f"\"{file_size}\"",
- "Content-Range": f"bytes 0-{file_size-1}/{file_size}"
- }
- response = requests.put(
- file_consent_card_response.upload_info.upload_url, open(file_path, "rb"), headers=headers
- )
-
- if response.status_code != 200:
- await self._file_upload_failed(turn_context, "Unable to upload file.")
- else:
- await self._file_upload_complete(turn_context, file_consent_card_response)
-
- async def on_teams_file_consent_decline(
- self,
- turn_context: TurnContext,
- file_consent_card_response: FileConsentCardResponse
- ):
- """
- The user declined the file upload.
- """
-
- context = file_consent_card_response.context
-
- reply = self._create_reply(
- turn_context.activity,
- f"Declined. We won't upload file {context['filename']}.",
- "xml"
- )
- await turn_context.send_activity(reply)
-
- async def _file_upload_complete(
- self,
- turn_context: TurnContext,
- file_consent_card_response: FileConsentCardResponse
- ):
- """
- The file was uploaded, so display a FileInfoCard so the user can view the
- file in Teams.
- """
-
- name = file_consent_card_response.upload_info.name
-
- download_card = FileInfoCard(
- unique_id=file_consent_card_response.upload_info.unique_id,
- file_type=file_consent_card_response.upload_info.file_type
- )
-
- as_attachment = Attachment(
- content=download_card.serialize(),
- content_type=ContentType.FILE_INFO_CARD,
- name=name,
- content_url=file_consent_card_response.upload_info.content_url
- )
-
- reply = self._create_reply(
- turn_context.activity,
- f"File uploaded. Your file {name} is ready to download",
- "xml"
- )
- reply.attachments = [as_attachment]
-
- await turn_context.send_activity(reply)
-
- async def _file_upload_failed(self, turn_context: TurnContext, error: str):
- reply = self._create_reply(
- turn_context.activity,
- f"File upload failed. Error: {error}",
- "xml"
- )
- await turn_context.send_activity(reply)
-
- def _create_reply(self, activity, text=None, text_format=None):
- return Activity(
- type=ActivityTypes.message,
- timestamp=datetime.utcnow(),
- from_property=ChannelAccount(
- id=activity.recipient.id, name=activity.recipient.name
- ),
- recipient=ChannelAccount(
- id=activity.from_property.id, name=activity.from_property.name
- ),
- reply_to_id=activity.id,
- service_url=activity.service_url,
- channel_id=activity.channel_id,
- conversation=ConversationAccount(
- is_group=activity.conversation.is_group,
- id=activity.conversation.id,
- name=activity.conversation.name,
- ),
- text=text or "",
- text_format=text_format or None,
- locale=activity.locale,
- )
diff --git a/tests/teams/scenarios/file-upload/config.py b/tests/teams/scenarios/file-upload/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/file-upload/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/file-upload/files/teams-logo.png b/tests/teams/scenarios/file-upload/files/teams-logo.png
deleted file mode 100644
index 78b0a0c30..000000000
Binary files a/tests/teams/scenarios/file-upload/files/teams-logo.png and /dev/null differ
diff --git a/tests/teams/scenarios/file-upload/requirements.txt b/tests/teams/scenarios/file-upload/requirements.txt
deleted file mode 100644
index 8ee86105f..000000000
--- a/tests/teams/scenarios/file-upload/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-requests
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/file-upload/teams_app_manifest/color.png b/tests/teams/scenarios/file-upload/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/file-upload/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/file-upload/teams_app_manifest/manifest.json b/tests/teams/scenarios/file-upload/teams_app_manifest/manifest.json
deleted file mode 100644
index f6941c176..000000000
--- a/tests/teams/scenarios/file-upload/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,38 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "<>",
- "packageName": "com.microsoft.teams.samples.fileUpload",
- "developer": {
- "name": "Microsoft Corp",
- "websiteUrl": "https://example.azurewebsites.net",
- "privacyUrl": "https://example.azurewebsites.net/privacy",
- "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
- },
- "name": {
- "short": "V4 File Sample",
- "full": "Microsoft Teams V4 File Sample Bot"
- },
- "description": {
- "short": "Sample bot using V4 SDK to demo bot file features",
- "full": "Sample bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK to demo bot file features"
- },
- "icons": {
- "outline": "outline.png",
- "color": "color.png"
- },
- "accentColor": "#abcdef",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "personal"
- ],
- "supportsFiles": true
- }
- ],
- "validDomains": [
- "*.azurewebsites.net"
- ]
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/file-upload/teams_app_manifest/outline.png b/tests/teams/scenarios/file-upload/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/file-upload/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/link-unfurling/README.md b/tests/teams/scenarios/link-unfurling/README.md
deleted file mode 100644
index eecb8fccb..000000000
--- a/tests/teams/scenarios/link-unfurling/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# RosterBot
-
-Bot Framework v4 teams roster bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\roster` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/link-unfurling/bots/__init__.py b/tests/teams/scenarios/link-unfurling/bots/__init__.py
deleted file mode 100644
index 40e14fad9..000000000
--- a/tests/teams/scenarios/link-unfurling/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .link_unfurling_bot import LinkUnfurlingBot
-
-__all__ = ["LinkUnfurlingBot"]
diff --git a/tests/teams/scenarios/link-unfurling/bots/link_unfurling_bot.py b/tests/teams/scenarios/link-unfurling/bots/link_unfurling_bot.py
deleted file mode 100644
index 5dec7e21b..000000000
--- a/tests/teams/scenarios/link-unfurling/bots/link_unfurling_bot.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import CardFactory, MessageFactory, TurnContext
-from botbuilder.schema import ChannelAccount, ThumbnailCard, CardImage, HeroCard, Attachment
-from botbuilder.schema.teams import AppBasedLinkQuery, MessagingExtensionAttachment, MessagingExtensionQuery, MessagingExtensionResult, MessagingExtensionResponse
-from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
-
-class LinkUnfurlingBot(TeamsActivityHandler):
- async def on_teams_app_based_link_query(self, turn_context: TurnContext, query: AppBasedLinkQuery):
- hero_card = ThumbnailCard(
- title="Thumnnail card",
- text=query.url,
- images=[
- CardImage(
- url="https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png"
- )
- ]
- )
- attachments = MessagingExtensionAttachment(
- content_type=CardFactory.content_types.hero_card,
- content=hero_card)
- result = MessagingExtensionResult(
- attachment_layout="list",
- type="result",
- attachments=[attachments]
- )
- return MessagingExtensionResponse(compose_extension=result)
-
- async def on_teams_messaging_extension_query(self, turn_context: TurnContext, query: MessagingExtensionQuery):
- if query.command_id == "searchQuery":
- card = HeroCard(
- title="This is a Link Unfurling Sample",
- subtitle="It will unfurl links from *.botframework.com",
- text="This sample demonstrates how to handle link unfurling in Teams. Please review the readme for more information."
- )
- attachment = Attachment(
- content_type=CardFactory.content_types.hero_card,
- content=card
- )
- msg_ext_atc = MessagingExtensionAttachment(
- content=card,
- content_type=CardFactory.content_types.hero_card,
- preview=attachment
- )
- msg_ext_res = MessagingExtensionResult(
- attachment_layout="list",
- type="result",
- attachments=[msg_ext_atc]
- )
- response = MessagingExtensionResponse(
- compose_extension=msg_ext_res
- )
-
- return response
-
- raise NotImplementedError(f"Invalid command: {query.command_id}")
\ No newline at end of file
diff --git a/tests/teams/scenarios/link-unfurling/config.py b/tests/teams/scenarios/link-unfurling/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/link-unfurling/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/link-unfurling/requirements.txt b/tests/teams/scenarios/link-unfurling/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/link-unfurling/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/link-unfurling/teams_app_manifest/color.png b/tests/teams/scenarios/link-unfurling/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/link-unfurling/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.json b/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.json
deleted file mode 100644
index 712b303b1..000000000
--- a/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,67 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "<>",
- "packageName": "com.teams.sample.linkunfurling",
- "developer": {
- "name": "Link Unfurling",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "Link Unfurling",
- "full": "Link Unfurling"
- },
- "description": {
- "short": "Link Unfurling",
- "full": "Link Unfurling"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [ "personal", "team" ]
- }
- ],
- "composeExtensions": [
- {
- "botId": "<>",
- "commands": [
- {
- "id": "searchQuery",
- "context": [ "compose", "commandBox" ],
- "description": "Test command to run query",
- "title": "Search",
- "type": "query",
- "parameters": [
- {
- "name": "searchQuery",
- "title": "Search Query",
- "description": "Your search query",
- "inputType": "text"
- }
- ]
- }
- ],
- "messageHandlers": [
- {
- "type": "link",
- "value": {
- "domains": [
- "microsoft.com",
- "github.com",
- "linkedin.com",
- "bing.com"
- ]
- }
- }
- ]
- }
- ]
-}
diff --git a/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.zip b/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.zip
deleted file mode 100644
index aaedf42c4..000000000
Binary files a/tests/teams/scenarios/link-unfurling/teams_app_manifest/manifest.zip and /dev/null differ
diff --git a/tests/teams/scenarios/link-unfurling/teams_app_manifest/outline.png b/tests/teams/scenarios/link-unfurling/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/link-unfurling/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/mentions/README.md b/tests/teams/scenarios/mentions/README.md
deleted file mode 100644
index f1a48af72..000000000
--- a/tests/teams/scenarios/mentions/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# EchoBot
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/mentions/app.py b/tests/teams/scenarios/mentions/app.py
deleted file mode 100644
index b7230468e..000000000
--- a/tests/teams/scenarios/mentions/app.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import MentionBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-
-# Create the Bot
-BOT = MentionBot()
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/mentions/bots/__init__.py b/tests/teams/scenarios/mentions/bots/__init__.py
deleted file mode 100644
index 7acf9b841..000000000
--- a/tests/teams/scenarios/mentions/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .mention_bot import MentionBot
-
-__all__ = ["MentionBot"]
diff --git a/tests/teams/scenarios/mentions/bots/mention_bot.py b/tests/teams/scenarios/mentions/bots/mention_bot.py
deleted file mode 100644
index 218fb735a..000000000
--- a/tests/teams/scenarios/mentions/bots/mention_bot.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import MessageFactory, TurnContext
-from botbuilder.core.teams import TeamsActivityHandler
-from botbuilder.schema import Mention
-
-
-class MentionBot(TeamsActivityHandler):
- async def on_message_activity(self, turn_context: TurnContext):
- mention_data = {
- "mentioned": turn_context.activity.from_property,
- "text": f"{turn_context.activity.from_property.name}",
- "type": "mention",
- }
-
- mention_object = Mention(**mention_data)
-
- reply_activity = MessageFactory.text(f"Hello {mention_object.text}")
- reply_activity.entities = [mention_object]
- await turn_context.send_activity(reply_activity)
diff --git a/tests/teams/scenarios/mentions/config.py b/tests/teams/scenarios/mentions/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/mentions/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/mentions/requirements.txt b/tests/teams/scenarios/mentions/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/mentions/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/mentions/teams_app_manifest/color.png b/tests/teams/scenarios/mentions/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/mentions/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/mentions/teams_app_manifest/manifest.json b/tests/teams/scenarios/mentions/teams_app_manifest/manifest.json
deleted file mode 100644
index 035808898..000000000
--- a/tests/teams/scenarios/mentions/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "<>",
- "packageName": "com.teams.sample.conversationUpdate",
- "developer": {
- "name": "MentionBot",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "MentionBot",
- "full": "MentionBot"
- },
- "description": {
- "short": "MentionBot",
- "full": "MentionBot"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "groupchat",
- "team",
- "personal"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/mentions/teams_app_manifest/outline.png b/tests/teams/scenarios/mentions/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/mentions/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/message-reactions/README.md b/tests/teams/scenarios/message-reactions/README.md
deleted file mode 100644
index f1a48af72..000000000
--- a/tests/teams/scenarios/message-reactions/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# EchoBot
-
-Bot Framework v4 echo bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/message-reactions/activity_log.py b/tests/teams/scenarios/message-reactions/activity_log.py
deleted file mode 100644
index c12276bb0..000000000
--- a/tests/teams/scenarios/message-reactions/activity_log.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import MemoryStorage
-from botbuilder.schema import Activity
-
-
-class ActivityLog:
- def __init__(self, storage: MemoryStorage):
- self._storage = storage
-
- async def append(self, activity_id: str, activity: Activity):
- if not activity_id:
- raise TypeError("activity_id is required for ActivityLog.append")
-
- if not activity:
- raise TypeError("activity is required for ActivityLog.append")
-
- obj = {}
- obj[activity_id] = activity
-
- await self._storage.write(obj)
- return
-
- async def find(self, activity_id: str) -> Activity:
- if not activity_id:
- raise TypeError("activity_id is required for ActivityLog.find")
-
- items = await self._storage.read([activity_id])
- return items[activity_id] if len(items) >= 1 else None
diff --git a/tests/teams/scenarios/message-reactions/app.py b/tests/teams/scenarios/message-reactions/app.py
deleted file mode 100644
index 93b78e957..000000000
--- a/tests/teams/scenarios/message-reactions/app.py
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
- MemoryStorage,
-)
-from botbuilder.schema import Activity, ActivityTypes
-from activity_log import ActivityLog
-from bots import MessageReactionBot
-from threading_helper import run_coroutine
-
-# Create the Flask app
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-
-MEMORY = MemoryStorage()
-ACTIVITY_LOG = ActivityLog(MEMORY)
-# Create the Bot
-BOT = MessageReactionBot(ACTIVITY_LOG)
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- print("about to create task")
- print("about to run until complete")
- run_coroutine(ADAPTER.process_activity(activity, auth_header, BOT.on_turn))
- print("is now complete")
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/message-reactions/bots/__init__.py b/tests/teams/scenarios/message-reactions/bots/__init__.py
deleted file mode 100644
index 39b49a20c..000000000
--- a/tests/teams/scenarios/message-reactions/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .message_reaction_bot import MessageReactionBot
-
-__all__ = ["MessageReactionBot"]
diff --git a/tests/teams/scenarios/message-reactions/bots/message_reaction_bot.py b/tests/teams/scenarios/message-reactions/bots/message_reaction_bot.py
deleted file mode 100644
index 5b585e270..000000000
--- a/tests/teams/scenarios/message-reactions/bots/message_reaction_bot.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from typing import List
-from botbuilder.core import MessageFactory, TurnContext, ActivityHandler
-from botbuilder.schema import MessageReaction
-from activity_log import ActivityLog
-
-
-class MessageReactionBot(ActivityHandler):
- def __init__(self, activity_log: ActivityLog):
- self._log = activity_log
-
- async def on_reactions_added(
- self, message_reactions: List[MessageReaction], turn_context: TurnContext
- ):
- for reaction in message_reactions:
- activity = await self._log.find(turn_context.activity.reply_to_id)
- if not activity:
- await self._send_message_and_log_activity_id(
- turn_context,
- f"Activity {turn_context.activity.reply_to_id} not found in log",
- )
- else:
- await self._send_message_and_log_activity_id(
- turn_context,
- f"You added '{reaction.type}' regarding '{activity.text}'",
- )
- return
-
- async def on_reactions_removed(
- self, message_reactions: List[MessageReaction], turn_context: TurnContext
- ):
- for reaction in message_reactions:
- activity = await self._log.find(turn_context.activity.reply_to_id)
- if not activity:
- await self._send_message_and_log_activity_id(
- turn_context,
- f"Activity {turn_context.activity.reply_to_id} not found in log",
- )
- else:
- await self._send_message_and_log_activity_id(
- turn_context,
- f"You removed '{reaction.type}' regarding '{activity.text}'",
- )
- return
-
- async def on_message_activity(self, turn_context: TurnContext):
- await self._send_message_and_log_activity_id(
- turn_context, f"echo: {turn_context.activity.text}"
- )
-
- async def _send_message_and_log_activity_id(
- self, turn_context: TurnContext, text: str
- ):
- reply_activity = MessageFactory.text(text)
- resource_response = await turn_context.send_activity(reply_activity)
-
- await self._log.append(resource_response.id, reply_activity)
- return
diff --git a/tests/teams/scenarios/message-reactions/config.py b/tests/teams/scenarios/message-reactions/config.py
deleted file mode 100644
index aec900d57..000000000
--- a/tests/teams/scenarios/message-reactions/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "e4c570ca-189d-4fee-a81b-5466be24a557")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "bghqYKJV3709;creKFP8$@@")
diff --git a/tests/teams/scenarios/message-reactions/requirements.txt b/tests/teams/scenarios/message-reactions/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/message-reactions/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/message-reactions/teams_app_manifest/color.png b/tests/teams/scenarios/message-reactions/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/message-reactions/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/message-reactions/teams_app_manifest/manifest.json b/tests/teams/scenarios/message-reactions/teams_app_manifest/manifest.json
deleted file mode 100644
index 2b53de7e0..000000000
--- a/tests/teams/scenarios/message-reactions/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "<>",
- "packageName": "com.teams.sample.conversationUpdate",
- "developer": {
- "name": "MessageReactions",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "MessageReactions",
- "full": "MessageReactions"
- },
- "description": {
- "short": "MessageReactions",
- "full": "MessageReactions"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "groupchat",
- "team",
- "personal"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/message-reactions/teams_app_manifest/outline.png b/tests/teams/scenarios/message-reactions/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/message-reactions/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/message-reactions/threading_helper.py b/tests/teams/scenarios/message-reactions/threading_helper.py
deleted file mode 100644
index 04dd20ee7..000000000
--- a/tests/teams/scenarios/message-reactions/threading_helper.py
+++ /dev/null
@@ -1,169 +0,0 @@
-import asyncio
-import itertools
-import logging
-import threading
-
-# pylint: disable=invalid-name
-# pylint: disable=global-statement
-try:
- # Python 3.8 or newer has a suitable process watcher
- asyncio.ThreadedChildWatcher
-except AttributeError:
- # backport the Python 3.8 threaded child watcher
- import os
- import warnings
-
- # Python 3.7 preferred API
- _get_running_loop = getattr(asyncio, "get_running_loop", asyncio.get_event_loop)
-
- class _Py38ThreadedChildWatcher(asyncio.AbstractChildWatcher):
- def __init__(self):
- self._pid_counter = itertools.count(0)
- self._threads = {}
-
- def is_active(self):
- return True
-
- def close(self):
- pass
-
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- pass
-
- def __del__(self, _warn=warnings.warn):
- threads = [t for t in list(self._threads.values()) if t.is_alive()]
- if threads:
- _warn(
- f"{self.__class__} has registered but not finished child processes",
- ResourceWarning,
- source=self,
- )
-
- def add_child_handler(self, pid, callback, *args):
- loop = _get_running_loop()
- thread = threading.Thread(
- target=self._do_waitpid,
- name=f"waitpid-{next(self._pid_counter)}",
- args=(loop, pid, callback, args),
- daemon=True,
- )
- self._threads[pid] = thread
- thread.start()
-
- def remove_child_handler(self, pid):
- # asyncio never calls remove_child_handler() !!!
- # The method is no-op but is implemented because
- # abstract base class requires it
- return True
-
- def attach_loop(self, loop):
- pass
-
- def _do_waitpid(self, loop, expected_pid, callback, args):
- assert expected_pid > 0
-
- try:
- pid, status = os.waitpid(expected_pid, 0)
- except ChildProcessError:
- # The child process is already reaped
- # (may happen if waitpid() is called elsewhere).
- pid = expected_pid
- returncode = 255
- logger.warning(
- "Unknown child process pid %d, will report returncode 255", pid
- )
- else:
- if os.WIFSIGNALED(status):
- returncode = -os.WTERMSIG(status)
- elif os.WIFEXITED(status):
- returncode = os.WEXITSTATUS(status)
- else:
- returncode = status
-
- if loop.get_debug():
- logger.debug(
- "process %s exited with returncode %s", expected_pid, returncode
- )
-
- if loop.is_closed():
- logger.warning("Loop %r that handles pid %r is closed", loop, pid)
- else:
- loop.call_soon_threadsafe(callback, pid, returncode, *args)
-
- self._threads.pop(expected_pid)
-
- # add the watcher to the loop policy
- asyncio.get_event_loop_policy().set_child_watcher(_Py38ThreadedChildWatcher())
-
-__all__ = ["EventLoopThread", "get_event_loop", "stop_event_loop", "run_coroutine"]
-
-logger = logging.getLogger(__name__)
-
-
-class EventLoopThread(threading.Thread):
- loop = None
- _count = itertools.count(0)
-
- def __init__(self):
- name = f"{type(self).__name__}-{next(self._count)}"
- super().__init__(name=name, daemon=True)
-
- def __repr__(self):
- loop, r, c, d = self.loop, False, True, False
- if loop is not None:
- r, c, d = loop.is_running(), loop.is_closed(), loop.get_debug()
- return (
- f"<{type(self).__name__} {self.name} id={self.ident} "
- f"running={r} closed={c} debug={d}>"
- )
-
- def run(self):
- self.loop = loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
-
- try:
- loop.run_forever()
- finally:
- try:
- shutdown_asyncgens = loop.shutdown_asyncgens()
- except AttributeError:
- pass
- else:
- loop.run_until_complete(shutdown_asyncgens)
- loop.close()
- asyncio.set_event_loop(None)
-
- def stop(self):
- loop, self.loop = self.loop, None
- if loop is None:
- return
- loop.call_soon_threadsafe(loop.stop)
- self.join()
-
-
-_lock = threading.Lock()
-_loop_thread = None
-
-
-def get_event_loop():
- global _loop_thread
- with _lock:
- if _loop_thread is None:
- _loop_thread = EventLoopThread()
- _loop_thread.start()
- return _loop_thread.loop
-
-
-def stop_event_loop():
- global _loop_thread
- with _lock:
- if _loop_thread is not None:
- _loop_thread.stop()
- _loop_thread = None
-
-
-def run_coroutine(coro):
- return asyncio.run_coroutine_threadsafe(coro, get_event_loop())
diff --git a/tests/teams/scenarios/roster/README.md b/tests/teams/scenarios/roster/README.md
deleted file mode 100644
index eecb8fccb..000000000
--- a/tests/teams/scenarios/roster/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# RosterBot
-
-Bot Framework v4 teams roster bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\roster` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/roster/app.py b/tests/teams/scenarios/roster/app.py
deleted file mode 100644
index ba575e0bf..000000000
--- a/tests/teams/scenarios/roster/app.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import asyncio
-import sys
-from datetime import datetime
-from types import MethodType
-
-from flask import Flask, request, Response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-
-from bots import RosterBot
-
-# Create the loop and Flask app
-LOOP = asyncio.get_event_loop()
-APP = Flask(__name__, instance_relative_config=True)
-APP.config.from_object("config.DefaultConfig")
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error( # pylint: disable=unused-argument
- self, context: TurnContext, error: Exception
-):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
-
-# Create the Bot
-BOT = RosterBot()
-
-# Listen for incoming requests on /api/messages.s
-@APP.route("/api/messages", methods=["POST"])
-def messages():
- # Main bot message handler.
- 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 ""
- )
-
- try:
- task = LOOP.create_task(
- ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- )
- LOOP.run_until_complete(task)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-
-if __name__ == "__main__":
- try:
- APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
- except Exception as exception:
- raise exception
diff --git a/tests/teams/scenarios/roster/bots/__init__.py b/tests/teams/scenarios/roster/bots/__init__.py
deleted file mode 100644
index 44ab91a4b..000000000
--- a/tests/teams/scenarios/roster/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .roster_bot import RosterBot
-
-__all__ = ["RosterBot"]
diff --git a/tests/teams/scenarios/roster/bots/roster_bot.py b/tests/teams/scenarios/roster/bots/roster_bot.py
deleted file mode 100644
index 31cf75608..000000000
--- a/tests/teams/scenarios/roster/bots/roster_bot.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from typing import List
-from botbuilder.core import MessageFactory, TurnContext
-from botbuilder.schema import ChannelAccount
-from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
-
-class RosterBot(TeamsActivityHandler):
- async def on_members_added_activity(
- self, members_added: [ChannelAccount], turn_context: TurnContext
- ):
- for member in members_added:
- if member.id != turn_context.activity.recipient.id:
- await turn_context.send_activity(
- "Hello and welcome!"
- )
-
- async def on_message_activity(
- self, turn_context: TurnContext
- ):
- await turn_context.send_activity(MessageFactory.text(f"Echo: {turn_context.activity.text}"))
-
- text = turn_context.activity.text.strip()
- if "members" in text:
- await self._show_members(turn_context)
- elif "channels" in text:
- await self._show_channels(turn_context)
- elif "details" in text:
- await self._show_details(turn_context)
- else:
- await turn_context.send_activity(MessageFactory.text(f"Invalid command. Type \"Show channels\" to see a channel list. Type \"Show members\" to see a list of members in a team. Type \"Show details\" to see team information."))
-
- async def _show_members(
- self, turn_context: TurnContext
- ):
- members = await TeamsInfo.get_team_members(turn_context)
- reply = MessageFactory.text(f"Total of {len(members)} members are currently in team")
- await turn_context.send_activity(reply)
- messages = list(map(lambda m: (f'{m.aad_object_id} --> {m.name} --> {m.user_principal_name}'), members))
- await self._send_in_batches(turn_context, messages)
-
- async def _show_channels(
- self, turn_context: TurnContext
- ):
- channels = await TeamsInfo.get_team_channels(turn_context)
- reply = MessageFactory.text(f"Total of {len(channels)} channels are currently in team")
- await turn_context.send_activity(reply)
- messages = list(map(lambda c: (f'{c.id} --> {c.name}'), channels))
- await self._send_in_batches(turn_context, messages)
-
- async def _show_details(self, turn_context: TurnContext):
- team_details = await TeamsInfo.get_team_details(turn_context)
- reply = MessageFactory.text(f"The team name is {team_details.name}. The team ID is {team_details.id}. The AADGroupID is {team_details.aad_group_id}.")
- await turn_context.send_activity(reply)
-
- async def _send_in_batches(self, turn_context: TurnContext, messages: List[str]):
- batch = []
- for msg in messages:
- batch.append(msg)
- if len(batch) == 10:
- await turn_context.send_activity(MessageFactory.text("
".join(batch)))
- batch = []
-
- if len(batch) > 0:
- await turn_context.send_activity(MessageFactory.text("
".join(batch)))
\ No newline at end of file
diff --git a/tests/teams/scenarios/roster/config.py b/tests/teams/scenarios/roster/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/roster/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/roster/requirements.txt b/tests/teams/scenarios/roster/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/roster/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/roster/teams_app_manifest/color.png b/tests/teams/scenarios/roster/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/roster/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/roster/teams_app_manifest/manifest.json b/tests/teams/scenarios/roster/teams_app_manifest/manifest.json
deleted file mode 100644
index c6b6582b0..000000000
--- a/tests/teams/scenarios/roster/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "00000000-0000-0000-0000-000000000000",
- "packageName": "com.teams.sample.roster",
- "developer": {
- "name": "TeamsRosterBot",
- "websiteUrl": "https://www.microsoft.com",
- "privacyUrl": "https://www.teams.com/privacy",
- "termsOfUseUrl": "https://www.teams.com/termsofuser"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "TeamsRosterBot",
- "full": "TeamsRosterBot"
- },
- "description": {
- "short": "TeamsRosterBot",
- "full": "TeamsRosterBot"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "00000000-0000-0000-0000-000000000000",
- "scopes": [
- "groupchat",
- "team"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ],
- "validDomains": []
-}
\ No newline at end of file
diff --git a/tests/teams/scenarios/roster/teams_app_manifest/outline.png b/tests/teams/scenarios/roster/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/roster/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/search-based-messaging-extension/README.md b/tests/teams/scenarios/search-based-messaging-extension/README.md
deleted file mode 100644
index eecb8fccb..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# RosterBot
-
-Bot Framework v4 teams roster bot sample.
-
-This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
-
-## Running the sample
-- Clone the repository
-```bash
-git clone https://github.com/Microsoft/botbuilder-python.git
-```
-- Activate your desired virtual environment
-- Bring up a terminal, navigate to `botbuilder-python\samples\roster` folder
-- In the terminal, type `pip install -r requirements.txt`
-- In the terminal, type `python app.py`
-
-## Testing the bot using Bot Framework Emulator
-[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
-
-- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
-
-### Connect to bot using Bot Framework Emulator
-- Launch Bot Framework Emulator
-- Paste this URL in the emulator window - http://localhost:3978/api/messages
-
-## Further reading
-
-- [Bot Framework Documentation](https://docs.botframework.com)
-- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
-- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
diff --git a/tests/teams/scenarios/search-based-messaging-extension/app.py b/tests/teams/scenarios/search-based-messaging-extension/app.py
deleted file mode 100644
index 62c00ce20..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/app.py
+++ /dev/null
@@ -1,83 +0,0 @@
-import json
-import sys
-from datetime import datetime
-
-from aiohttp import web
-from aiohttp.web import Request, Response, json_response
-
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-
-from botbuilder.schema import Activity, ActivityTypes
-from bots import SearchBasedMessagingExtension
-from config import DefaultConfig
-
-CONFIG = DefaultConfig()
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-# Catch-all for errors.
-async def on_error(context: TurnContext, error: Exception):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
-
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-ADAPTER.on_turn_error = on_error
-
-# Create the Bot
-BOT = SearchBasedMessagingExtension()
-
-# Listen for incoming requests on /api/messages
-async def messages(req: Request) -> Response:
- # Main bot message handler.
- if "application/json" in req.headers["Content-Type"]:
- body = await req.json()
- else:
- return Response(status=415)
-
- activity = Activity().deserialize(body)
- auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
-
- try:
- response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
- if response:
- return json_response(data=response.body, status=response.status)
- return Response(status=201)
- except Exception as exception:
- raise exception
-
-APP = web.Application()
-APP.router.add_post("/api/messages", messages)
-
-if __name__ == "__main__":
- try:
- web.run_app(APP, host="localhost", port=CONFIG.PORT)
- except Exception as error:
- raise error
diff --git a/tests/teams/scenarios/search-based-messaging-extension/bots/__init__.py b/tests/teams/scenarios/search-based-messaging-extension/bots/__init__.py
deleted file mode 100644
index 9311de37a..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .search_based_messaging_extension import SearchBasedMessagingExtension
-
-__all__ = ["SearchBasedMessagingExtension"]
diff --git a/tests/teams/scenarios/search-based-messaging-extension/bots/search_based_messaging_extension.py b/tests/teams/scenarios/search-based-messaging-extension/bots/search_based_messaging_extension.py
deleted file mode 100644
index 27db99646..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/bots/search_based_messaging_extension.py
+++ /dev/null
@@ -1,175 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from botbuilder.core import CardFactory, MessageFactory, TurnContext
-from botbuilder.schema import ChannelAccount, ThumbnailCard, CardImage, HeroCard, Attachment, CardAction
-from botbuilder.schema.teams import AppBasedLinkQuery, MessagingExtensionAttachment, MessagingExtensionQuery, MessagingExtensionResult, MessagingExtensionResponse
-from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
-
-from typing import List
-import requests
-
-class SearchBasedMessagingExtension(TeamsActivityHandler):
- async def on_message_activity(self, turn_context: TurnContext):
- await turn_context.send_activities(MessageFactory.text(f"Echo: {turn_context.activity.text}"))
-
- async def on_teams_messaging_extension_query(self, turn_context: TurnContext, query: MessagingExtensionQuery):
- search_query = str(query.parameters[0].value)
- response = requests.get(f"http://registry.npmjs.com/-/v1/search",params={"text":search_query})
- data = response.json()
-
- attachments = []
-
- for obj in data["objects"]:
- hero_card = HeroCard(
- title=obj["package"]["name"],
- tap=CardAction(
- type="invoke",
- value=obj["package"]
- ),
- preview=[CardImage(url=obj["package"]["links"]["npm"])]
- )
-
- attachment = MessagingExtensionAttachment(
- content_type=CardFactory.content_types.hero_card,
- content=HeroCard(title=obj["package"]["name"]),
- preview=CardFactory.hero_card(hero_card)
- )
- attachments.append(attachment)
- return MessagingExtensionResponse(
- compose_extension=MessagingExtensionResult(
- type="result",
- attachment_layout="list",
- attachments=attachments
- )
- )
-
-
-
- async def on_teams_messaging_extension_select_item(self, turn_context: TurnContext, query) -> MessagingExtensionResponse:
- hero_card = HeroCard(
- title=query["name"],
- subtitle=query["description"],
- buttons=[
- CardAction(
- type="openUrl",
- value=query["links"]["npm"]
- )
- ]
- )
- attachment = MessagingExtensionAttachment(
- content_type=CardFactory.content_types.hero_card,
- content=hero_card
- )
-
- return MessagingExtensionResponse(
- compose_extension=MessagingExtensionResult(
- type="result",
- attachment_layout="list",
- attachments=[attachment]
- )
- )
-
- def _create_messaging_extension_result(self, attachments: List[MessagingExtensionAttachment]) -> MessagingExtensionResult:
- return MessagingExtensionResult(
- type="result",
- attachment_layout="list",
- attachments=attachments
- )
-
- def _create_search_result_attachment(self, search_query: str) -> MessagingExtensionAttachment:
- card_text = f"You said {search_query}"
- bf_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"
-
- button = CardAction(
- type="openUrl",
- title="Click for more Information",
- value="https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
- )
-
- images = [CardImage(url=bf_logo)]
- buttons = [button]
-
- hero_card = HeroCard(
- title="You searched for:",
- text=card_text,
- images=images,
- buttons=buttons
- )
-
- return MessagingExtensionAttachment(
- content_type=CardFactory.content_types.hero_card,
- content=hero_card,
- preview=CardFactory.hero_card(hero_card)
- )
-
- def _create_dummy_search_result_attachment(self) -> MessagingExtensionAttachment:
- card_text = "https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
- bf_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"
-
- button = CardAction(
- type = "openUrl",
- title = "Click for more Information",
- value = "https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
- )
-
- images = [CardImage(url=bf_logo)]
-
- buttons = [button]
-
-
- hero_card = HeroCard(
- title="Learn more about Teams:",
- text=card_text, images=images,
- buttons=buttons
- )
-
- preview = HeroCard(
- title="Learn more about Teams:",
- text=card_text,
- images=images
- )
-
- return MessagingExtensionAttachment(
- content_type = CardFactory.content_types.hero_card,
- content = hero_card,
- preview = CardFactory.hero_card(preview)
- )
-
- def _create_select_items_result_attachment(self, search_query: str) -> MessagingExtensionAttachment:
- card_text = f"You said {search_query}"
- bf_logo = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU"
-
- buttons = CardAction(
- type="openUrl",
- title="Click for more Information",
- value="https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-overview"
- )
-
- images = [CardImage(url=bf_logo)]
- buttons = [buttons]
-
- select_item_tap = CardAction(
- type="invoke",
- value={"query": search_query}
- )
-
- hero_card = HeroCard(
- title="You searched for:",
- text=card_text,
- images=images,
- buttons=buttons
- )
-
- preview = HeroCard(
- title=card_text,
- text=card_text,
- images=images,
- tap=select_item_tap
- )
-
- return MessagingExtensionAttachment(
- content_type=CardFactory.content_types.hero_card,
- content=hero_card,
- preview=CardFactory.hero_card(preview)
- )
\ No newline at end of file
diff --git a/tests/teams/scenarios/search-based-messaging-extension/config.py b/tests/teams/scenarios/search-based-messaging-extension/config.py
deleted file mode 100644
index d66581d4c..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/config.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
diff --git a/tests/teams/scenarios/search-based-messaging-extension/requirements.txt b/tests/teams/scenarios/search-based-messaging-extension/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/color.png b/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/color.png and /dev/null differ
diff --git a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/manifest.json b/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/manifest.json
deleted file mode 100644
index 98bb01282..000000000
--- a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,49 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "<>",
- "packageName": "com.microsoft.teams.samples.searchExtension",
- "developer": {
- "name": "Microsoft Corp",
- "websiteUrl": "https://example.azurewebsites.net",
- "privacyUrl": "https://example.azurewebsites.net/privacy",
- "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
- },
- "name": {
- "short": "search-extension-settings",
- "full": "Microsoft Teams V4 Search Messaging Extension Bot and settings"
- },
- "description": {
- "short": "Microsoft Teams V4 Search Messaging Extension Bot and settings",
- "full": "Sample Search Messaging Extension Bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK"
- },
- "icons": {
- "outline": "icon-outline.png",
- "color": "icon-color.png"
- },
- "accentColor": "#abcdef",
- "composeExtensions": [
- {
- "botId": "<>",
- "canUpdateConfiguration": true,
- "commands": [
- {
- "id": "searchQuery",
- "context": [ "compose", "commandBox" ],
- "description": "Test command to run query",
- "title": "Search",
- "type": "query",
- "parameters": [
- {
- "name": "searchQuery",
- "title": "Search Query",
- "description": "Your search query",
- "inputType": "text"
- }
- ]
- }
- ]
- }
- ]
- }
\ No newline at end of file
diff --git a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/outline.png b/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/search-based-messaging-extension/teams_app_manifest/outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/task-module/app.py b/tests/teams/scenarios/task-module/app.py
deleted file mode 100644
index b5abfad28..000000000
--- a/tests/teams/scenarios/task-module/app.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import json
-import sys
-from datetime import datetime
-
-from aiohttp import web
-from aiohttp.web import Request, Response, json_response
-from botbuilder.core import (
- BotFrameworkAdapterSettings,
- TurnContext,
- BotFrameworkAdapter,
-)
-from botbuilder.schema import Activity, ActivityTypes
-from bots import TaskModuleBot
-from config import DefaultConfig
-
-CONFIG = DefaultConfig()
-
-# Create adapter.
-# See https://aka.ms/about-bot-adapter to learn more about how bots work.
-SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
-ADAPTER = BotFrameworkAdapter(SETTINGS)
-
-
-# Catch-all for errors.
-async def on_error(context: TurnContext, error: Exception):
- # This check writes out errors to console log .vs. app insights.
- # NOTE: In production environment, you should consider logging this to Azure
- # application insights.
- print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
-
- # Send a message to the user
- await context.send_activity("The bot encountered an error or bug.")
- await context.send_activity(
- "To continue to run this bot, please fix the bot source code."
- )
- # Send a trace activity if we're talking to the Bot Framework Emulator
- if context.activity.channel_id == "emulator":
- # Create a trace activity that contains the error object
- trace_activity = Activity(
- label="TurnError",
- name="on_turn_error Trace",
- timestamp=datetime.utcnow(),
- type=ActivityTypes.trace,
- value=f"{error}",
- value_type="https://www.botframework.com/schemas/error",
- )
- # Send a trace activity, which will be displayed in Bot Framework Emulator
- await context.send_activity(trace_activity)
-
-
-ADAPTER.on_turn_error = on_error
-
-# Create the Bot
-BOT = TaskModuleBot()
-
-
-# Listen for incoming requests on /api/messages
-async def messages(req: Request) -> Response:
- # Main bot message handler.
- if "application/json" in req.headers["Content-Type"]:
- body = await req.json()
- else:
- return Response(status=415)
-
- activity = Activity().deserialize(body)
- auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
-
- try:
- invoke_response = await ADAPTER.process_activity(
- activity, auth_header, BOT.on_turn
- )
- if invoke_response:
- return json_response(
- data=invoke_response.body, status=invoke_response.status
- )
- return Response(status=201)
- except PermissionError:
- return Response(status=401)
- except Exception:
- return Response(status=500)
-
-
-APP = web.Application()
-APP.router.add_post("/api/messages", messages)
-
-if __name__ == "__main__":
- try:
- web.run_app(APP, host="localhost", port=CONFIG.PORT)
- except Exception as error:
- raise error
diff --git a/tests/teams/scenarios/task-module/bots/__init__.py b/tests/teams/scenarios/task-module/bots/__init__.py
deleted file mode 100644
index 550d3aaf8..000000000
--- a/tests/teams/scenarios/task-module/bots/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-from .teams_task_module_bot import TaskModuleBot
-
-__all__ = ["TaskModuleBot"]
diff --git a/tests/teams/scenarios/task-module/bots/teams_task_module_bot.py b/tests/teams/scenarios/task-module/bots/teams_task_module_bot.py
deleted file mode 100644
index 3c4cbde5d..000000000
--- a/tests/teams/scenarios/task-module/bots/teams_task_module_bot.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright (c) Microsoft Corp. All rights reserved.
-# Licensed under the MIT License.
-
-import json
-from typing import List
-import random
-from botbuilder.core import CardFactory, MessageFactory, TurnContext
-from botbuilder.schema import (
- ChannelAccount,
- HeroCard,
- CardAction,
- CardImage,
- Attachment,
-)
-from botbuilder.schema.teams import (
- MessagingExtensionAction,
- MessagingExtensionActionResponse,
- MessagingExtensionAttachment,
- MessagingExtensionResult,
- TaskModuleResponse,
- TaskModuleResponseBase,
- TaskModuleContinueResponse,
- TaskModuleMessageResponse,
- TaskModuleTaskInfo,
- TaskModuleRequest,
-)
-from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo
-from botbuilder.azure import CosmosDbPartitionedStorage
-from botbuilder.core.teams.teams_helper import deserializer_helper
-
-class TaskModuleBot(TeamsActivityHandler):
- async def on_message_activity(self, turn_context: TurnContext):
- reply = MessageFactory.attachment(self._get_task_module_hero_card())
- await turn_context.send_activity(reply)
-
- def _get_task_module_hero_card(self) -> Attachment:
- task_module_action = CardAction(
- type="invoke",
- title="Adaptive Card",
- value={"type": "task/fetch", "data": "adaptivecard"},
- )
- card = HeroCard(
- title="Task Module Invocation from Hero Card",
- subtitle="This is a hero card with a Task Module Action button. Click the button to show an Adaptive Card within a Task Module.",
- buttons=[task_module_action],
- )
- return CardFactory.hero_card(card)
-
- async def on_teams_task_module_fetch(
- self, turn_context: TurnContext, task_module_request: TaskModuleRequest
- ) -> TaskModuleResponse:
- reply = MessageFactory.text(
- f"OnTeamsTaskModuleFetchAsync TaskModuleRequest: {json.dumps(task_module_request.data)}"
- )
- await turn_context.send_activity(reply)
-
- # base_response = TaskModuleResponseBase(type='continue')
- card = CardFactory.adaptive_card(
- {
- "version": "1.0.0",
- "type": "AdaptiveCard",
- "body": [
- {"type": "TextBlock", "text": "Enter Text Here",},
- {
- "type": "Input.Text",
- "id": "usertext",
- "placeholder": "add some text and submit",
- "IsMultiline": "true",
- },
- ],
- "actions": [{"type": "Action.Submit", "title": "Submit",}],
- }
- )
-
- task_info = TaskModuleTaskInfo(
- card=card, title="Adaptive Card: Inputs", height=200, width=400
- )
- continue_response = TaskModuleContinueResponse(type="continue", value=task_info)
- return TaskModuleResponse(task=continue_response)
-
- async def on_teams_task_module_submit(
- self, turn_context: TurnContext, task_module_request: TaskModuleRequest
- ) -> TaskModuleResponse:
- reply = MessageFactory.text(
- f"on_teams_messaging_extension_submit_action_activity MessagingExtensionAction: {json.dumps(task_module_request.data)}"
- )
- await turn_context.send_activity(reply)
-
- message_response = TaskModuleMessageResponse(type="message", value="Thanks!")
- return TaskModuleResponse(task=message_response)
diff --git a/tests/teams/scenarios/task-module/config.py b/tests/teams/scenarios/task-module/config.py
deleted file mode 100644
index 42a571bcf..000000000
--- a/tests/teams/scenarios/task-module/config.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/env python3
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License.
-
-import os
-
-
-class DefaultConfig:
- """ Bot Configuration """
-
- PORT = 3978
- APP_ID = os.environ.get("MicrosoftAppId", "")
- APP_PASSWORD = os.environ.get(
- "MicrosoftAppPassword", ""
- )
diff --git a/tests/teams/scenarios/task-module/requirements.txt b/tests/teams/scenarios/task-module/requirements.txt
deleted file mode 100644
index 87eba6848..000000000
--- a/tests/teams/scenarios/task-module/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-botbuilder-core>=4.7.1
-flask>=1.0.3
diff --git a/tests/teams/scenarios/task-module/teams_app_manifest/icon-color.png b/tests/teams/scenarios/task-module/teams_app_manifest/icon-color.png
deleted file mode 100644
index 48a2de133..000000000
Binary files a/tests/teams/scenarios/task-module/teams_app_manifest/icon-color.png and /dev/null differ
diff --git a/tests/teams/scenarios/task-module/teams_app_manifest/icon-outline.png b/tests/teams/scenarios/task-module/teams_app_manifest/icon-outline.png
deleted file mode 100644
index dbfa92772..000000000
Binary files a/tests/teams/scenarios/task-module/teams_app_manifest/icon-outline.png and /dev/null differ
diff --git a/tests/teams/scenarios/task-module/teams_app_manifest/manifest.json b/tests/teams/scenarios/task-module/teams_app_manifest/manifest.json
deleted file mode 100644
index 21600fcd6..000000000
--- a/tests/teams/scenarios/task-module/teams_app_manifest/manifest.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0.0",
- "id": "<>",
- "packageName": "com.microsoft.teams.samples",
- "developer": {
- "name": "Microsoft",
- "websiteUrl": "https://example.azurewebsites.net",
- "privacyUrl": "https://example.azurewebsites.net/privacy",
- "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
- },
- "icons": {
- "color": "color.png",
- "outline": "outline.png"
- },
- "name": {
- "short": "Task Module",
- "full": "Simple Task Module"
- },
- "description": {
- "short": "Test Task Module Scenario",
- "full": "Simple Task Module Scenario Test"
- },
- "accentColor": "#FFFFFF",
- "bots": [
- {
- "botId": "<>",
- "scopes": [
- "personal",
- "team",
- "groupchat"
- ],
- "supportsFiles": false,
- "isNotificationOnly": false
- }
- ],
- "permissions": [
- "identity",
- "messageTeamMembers"
- ]
-}
\ No newline at end of file