-
Notifications
You must be signed in to change notification settings - Fork 813
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1492 from OfficeDev/v-mfurquan/bot-conv-quickstar…
…t-python Added Sample Bot Conversation QuickStart Python
- Loading branch information
Showing
28 changed files
with
799 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# TeamsFx files | ||
env/.env.*.user | ||
env/.env.local | ||
appManifest/build/ | ||
|
||
# python virtual environment | ||
.venv/ | ||
|
||
# misc | ||
.env | ||
.deployment/ | ||
|
||
# tmp files | ||
__pycache__/ |
6 changes: 6 additions & 0 deletions
6
samples/bot-conversation-quickstart/python/.vscode/extensions.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"recommendations": [ | ||
"TeamsDevApp.ms-teams-vscode-extension", | ||
"ms-python.python", | ||
] | ||
} |
69 changes: 69 additions & 0 deletions
69
samples/bot-conversation-quickstart/python/.vscode/launch.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
{ | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"name": "Launch App (Edge)", | ||
"type": "msedge", | ||
"request": "launch", | ||
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}", | ||
"cascadeTerminateToConfigurations": [ | ||
"Python: Run App Locally" | ||
], | ||
"presentation": { | ||
"group": "all", | ||
"hidden": true | ||
}, | ||
"internalConsoleOptions": "neverOpen" | ||
}, | ||
{ | ||
"name": "Launch App (Chrome)", | ||
"type": "chrome", | ||
"request": "launch", | ||
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}", | ||
"cascadeTerminateToConfigurations": [ | ||
"Python: Run App Locally" | ||
], | ||
"presentation": { | ||
"group": "all", | ||
"hidden": true | ||
}, | ||
"internalConsoleOptions": "neverOpen" | ||
}, | ||
{ | ||
"name": "Python: Run App Locally", | ||
"type": "debugpy", | ||
"request": "launch", | ||
"program": "${workspaceFolder}/app.py", | ||
"cwd": "${workspaceFolder}", | ||
"console": "integratedTerminal" | ||
} | ||
], | ||
"compounds": [ | ||
{ | ||
"name": "Debug (Edge)", | ||
"configurations": [ | ||
"Launch App (Edge)", | ||
"Python: Run App Locally" | ||
], | ||
"preLaunchTask": "Prepare Teams App Resources", | ||
"presentation": { | ||
"group": "all", | ||
"order": 1 | ||
}, | ||
"stopAll": true | ||
}, | ||
{ | ||
"name": "Debug (Chrome)", | ||
"configurations": [ | ||
"Launch App (Chrome)", | ||
"Python: Run App Locally" | ||
], | ||
"preLaunchTask": "Prepare Teams App Resources", | ||
"presentation": { | ||
"group": "all", | ||
"order": 2 | ||
}, | ||
"stopAll": true | ||
} | ||
] | ||
} |
3 changes: 3 additions & 0 deletions
3
samples/bot-conversation-quickstart/python/.vscode/settings.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"debug.onTaskErrors": "abort" | ||
} |
78 changes: 78 additions & 0 deletions
78
samples/bot-conversation-quickstart/python/.vscode/tasks.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
// This file is automatically generated by Teams Toolkit. | ||
// The teamsfx tasks defined in this file require Teams Toolkit version >= 5.0.0. | ||
// See https://aka.ms/teamsfx-tasks for details on how to customize each task. | ||
{ | ||
"version": "2.0.0", | ||
"tasks": [ | ||
{ | ||
"label": "Prepare Teams App Resources", | ||
"dependsOn": [ | ||
"Validate prerequisites", | ||
"Start local tunnel", | ||
"Provision", | ||
"Deploy" | ||
], | ||
"dependsOrder": "sequence" | ||
}, | ||
{ | ||
// Check all required prerequisites. | ||
// See https://aka.ms/teamsfx-tasks/check-prerequisites to know the details and how to customize the args. | ||
"label": "Validate prerequisites", | ||
"type": "teamsfx", | ||
"command": "debug-check-prerequisites", | ||
"args": { | ||
"prerequisites": [ | ||
"m365Account", // Sign-in prompt for Microsoft 365 account, then validate if the account enables the sideloading permission. | ||
"portOccupancy" // Validate available ports to ensure those debug ones are not occupied. | ||
], | ||
"portOccupancy": [ | ||
3978, // app service port | ||
] | ||
} | ||
}, | ||
{ | ||
// Start the local tunnel service to forward public URL to local port and inspect traffic. | ||
// See https://aka.ms/teamsfx-tasks/local-tunnel for the detailed args definitions. | ||
"label": "Start local tunnel", | ||
"type": "teamsfx", | ||
"command": "debug-start-local-tunnel", | ||
"args": { | ||
"type": "dev-tunnel", | ||
"ports": [ | ||
{ | ||
"portNumber": 3978, | ||
"protocol": "http", | ||
"access": "public", | ||
"writeToEnvironmentFile": { | ||
"endpoint": "BOT_ENDPOINT", // output tunnel endpoint as BOT_ENDPOINT | ||
"domain": "BOT_DOMAIN" // output tunnel domain as BOT_DOMAIN | ||
} | ||
} | ||
], | ||
"env": "local" | ||
}, | ||
"isBackground": true, | ||
"problemMatcher": "$teamsfx-local-tunnel-watch" | ||
}, | ||
{ | ||
// Create the debug resources. | ||
// See https://aka.ms/teamsfx-tasks/provision to know the details and how to customize the args. | ||
"label": "Provision", | ||
"type": "teamsfx", | ||
"command": "provision", | ||
"args": { | ||
"env": "local" | ||
} | ||
}, | ||
{ | ||
// Build project. | ||
// See https://aka.ms/teamsfx-tasks/deploy to know the details and how to customize the args. | ||
"label": "Deploy", | ||
"type": "teamsfx", | ||
"command": "deploy", | ||
"args": { | ||
"env": "local" | ||
} | ||
} | ||
] | ||
} |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+99.6 KB
samples/bot-conversation-quickstart/python/Images/3.Bot_Mentioned.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+97.2 KB
samples/bot-conversation-quickstart/python/Images/4.Hello_Mentioned.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+174 KB
samples/bot-conversation-quickstart/python/Images/7.Teams_HeroCard.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+623 KB
samples/bot-conversation-quickstart/python/Images/bot-conversation-quickstart.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
--- | ||
page_type: sample | ||
description: This sample demonstrates how to build a bot for Microsoft Teams using the Bot Framework in Python. It highlights key features such as sending Hero Cards and handling user messages. | ||
products: | ||
- office-teams | ||
- office | ||
- office-365 | ||
languages: | ||
- python | ||
extensions: | ||
contentType: samples | ||
createdDate: "19/12/2024 01:38:26 PM" | ||
urlFragment: officedev-microsoft-teams-samples-bot-conversation-quickstart-python | ||
--- | ||
|
||
# Bot Conversation QuickStart (Python) | ||
|
||
This sample demonstrates how to build a bot for Microsoft Teams using the Bot Framework in Python. It highlights key features such as sending Hero Cards, handling user messages, and participating in Teams conversations. | ||
|
||
Hero Card Integration: Teaches how to create and send Hero Cards with actionable buttons, allowing users to interact with predefined commands. | ||
|
||
## Included Features | ||
* Bots | ||
* Hero Cards | ||
* Teams Conversation Events | ||
|
||
## Interaction with app | ||
|
||
![BotConversationQuickStart](Images/bot-conversation-quickstart.gif) | ||
|
||
## Prerequisites | ||
|
||
- Microsoft Teams is installed and you have an account | ||
- [Python SDK](https://www.python.org/downloads/) min version 3.6 | ||
- [dev tunnel](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/get-started?tabs=windows) or [ngrok](https://ngrok.com/) latest version or equivalent tunnelling solution | ||
- [Teams Toolkit for VS Code](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) or [TeamsFx CLI](https://learn.microsoft.com/microsoftteams/platform/toolkit/teamsfx-cli?pivots=version-one) | ||
|
||
## Run the app (Using Teams Toolkit for Visual Studio Code) | ||
|
||
The simplest way to run this sample in Teams is to use Teams Toolkit for Visual Studio Code. | ||
|
||
1. Ensure you have downloaded and installed [Visual Studio Code](https://code.visualstudio.com/docs/setup/setup-overview) | ||
1. Install the [Teams Toolkit extension](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) and [Python Extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) | ||
1. Select **File > Open Folder** in VS Code and choose this samples directory from the repo | ||
1. Press **CTRL+Shift+P** to open the command box and enter **Python: Create Environment** to create and activate your desired virtual environment. Remember to select `requirements.txt` as dependencies to install when creating the virtual environment. | ||
1. Using the extension, sign in with your Microsoft 365 account where you have permissions to upload custom apps | ||
1. Select **Debug > Start Debugging** or **F5** to run the app in a Teams web client. | ||
1. In the browser that launches, select the **Add** button to install the app to Teams. | ||
|
||
> If you do not have permission to upload custom apps (sideloading), Teams Toolkit will recommend creating and using a Microsoft 365 Developer Program account - a free program to get your own dev environment sandbox that includes Teams. | ||
## Run the app (Manually Uploading to Teams) | ||
|
||
1. Register a new application in the [Microsoft Entra ID – App Registrations](https://go.microsoft.com/fwlink/?linkid=2083908) portal. | ||
|
||
2. Setup for Bot | ||
In Azure portal, create a [Bot Framework registration resource](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0&tabs=csharp%2Caadv2). | ||
- Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/en-us/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0) | ||
- For the Messaging endpoint URL, use the current `https` URL you were given by running the tunneling application and append it with the path `/api/messages`. It should look something like `https://{subdomain}.ngrok-free.app/api/messages`. | ||
|
||
**NOTE:** When you create your bot you will create an App ID and App password - make sure you keep these for later. | ||
|
||
- Click on the `Bots` menu item from the toolkit and select the bot you are using for this project. Update the messaging endpoint and press enter to save the value in the Bot Framework. | ||
|
||
- Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/en-us/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0) | ||
|
||
3. Setup NGROK | ||
- Run ngrok - point to port 3978 | ||
|
||
```bash | ||
ngrok http 3978 --host-header="localhost:3978" | ||
``` | ||
|
||
Alternatively, you can also use the `dev tunnels`. Please follow [Create and host a dev tunnel](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/get-started?tabs=windows) and host the tunnel with anonymous user access command as shown below: | ||
|
||
```bash | ||
devtunnel host -p 3978 --allow-anonymous | ||
``` | ||
|
||
4. Setup for code | ||
|
||
- Clone the repository | ||
|
||
```bash | ||
git clone https://github.com/OfficeDev/Microsoft-Teams-Samples.git | ||
|
||
- In a terminal, navigate to `samples/bot-conversation-quickstart/python` | ||
|
||
- Activate your desired virtual environment | ||
|
||
- Install dependencies by running ```pip install -r requirements.txt``` in the project folder. | ||
|
||
5) Update the `config.py` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.) | ||
|
||
6) __*This step is specific to Teams.*__ | ||
- **Edit** the `manifest.json` contained in the `appManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `${{AAD_APP_CLIENT_ID}}` and `${{TEAMS_APP_ID}}` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`) | ||
- **Zip** up the contents of the `appManifest` folder to create a `manifest.zip` | ||
- **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app") | ||
|
||
7) Run your bot with `python app.py` | ||
|
||
## Running the sample | ||
|
||
![Install](Images/1.App_Install.png) | ||
|
||
**Personal Scope** | ||
![Hero Card](Images/2.Hero_Card.png) | ||
|
||
![hello response team](Images/3.Bot_Mentioned.png) | ||
|
||
![hello response team](Images/4.Hello_Mentioned.png) | ||
|
||
**Group Chat Scope** | ||
![hello response team](Images/5.GroupChat_Bot.png) | ||
|
||
**Teams Scope** | ||
![hello response team](Images/6.Teams_Bot.png) | ||
|
||
![hello response team](Images/7.Teams_HeroCard.png) | ||
|
||
|
||
<img src="https://pnptelemetry.azurewebsites.net/microsoft-teams-samples/samples/bot-conversation-quickstart-python" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
import sys | ||
import traceback | ||
import uuid | ||
from datetime import datetime | ||
from http import HTTPStatus | ||
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 BotActivityHandler | ||
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. Please check the logs for more details.") | ||
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 | ||
|
||
# If the channel is the Emulator, and authentication is not in use, the AppId will be null. | ||
# We generate a random AppId for this case only. This is not required for production, since | ||
# the AppId will have a value. | ||
APP_ID = SETTINGS.app_id if SETTINGS.app_id else uuid.uuid4() | ||
|
||
# Create the Bot | ||
BOT = BotActivityHandler() | ||
|
||
# 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=HTTPStatus.UNSUPPORTED_MEDIA_TYPE) | ||
|
||
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=HTTPStatus.OK) | ||
|
||
# Listen for incoming requests on /api/messages. | ||
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 |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.