Skip to content

Commit fd892b8

Browse files
authored
Merge pull request #1521 from OfficeDev/v-jegadeesh/python-migration
Updating Python samples PR -2
2 parents d897cc0 + ecfe635 commit fd892b8

29 files changed

+781
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# TeamsFx files
2+
env/.env.*.user
3+
env/.env.local
4+
appManifest/build/
5+
6+
# python virtual environment
7+
.venv/
8+
9+
# misc
10+
.env
11+
.deployment/
12+
13+
# tmp files
14+
__pycache__/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"recommendations": [
3+
"TeamsDevApp.ms-teams-vscode-extension",
4+
"ms-python.python",
5+
]
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
"name": "Launch App (Edge)",
6+
"type": "msedge",
7+
"request": "launch",
8+
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
9+
"cascadeTerminateToConfigurations": [
10+
"Python: Run App Locally"
11+
],
12+
"presentation": {
13+
"group": "all",
14+
"hidden": true
15+
},
16+
"internalConsoleOptions": "neverOpen"
17+
},
18+
{
19+
"name": "Launch App (Chrome)",
20+
"type": "chrome",
21+
"request": "launch",
22+
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
23+
"cascadeTerminateToConfigurations": [
24+
"Python: Run App Locally"
25+
],
26+
"presentation": {
27+
"group": "all",
28+
"hidden": true
29+
},
30+
"internalConsoleOptions": "neverOpen"
31+
},
32+
{
33+
"name": "Python: Run App Locally",
34+
"type": "debugpy",
35+
"request": "launch",
36+
"program": "${workspaceFolder}/app.py",
37+
"cwd": "${workspaceFolder}",
38+
"console": "integratedTerminal"
39+
}
40+
],
41+
"compounds": [
42+
{
43+
"name": "Debug (Edge)",
44+
"configurations": [
45+
"Launch App (Edge)",
46+
"Python: Run App Locally"
47+
],
48+
"preLaunchTask": "Prepare Teams App Resources",
49+
"presentation": {
50+
"group": "all",
51+
"order": 1
52+
},
53+
"stopAll": true
54+
},
55+
{
56+
"name": "Debug (Chrome)",
57+
"configurations": [
58+
"Launch App (Chrome)",
59+
"Python: Run App Locally"
60+
],
61+
"preLaunchTask": "Prepare Teams App Resources",
62+
"presentation": {
63+
"group": "all",
64+
"order": 2
65+
},
66+
"stopAll": true
67+
}
68+
]
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"debug.onTaskErrors": "abort"
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// This file is automatically generated by Teams Toolkit.
2+
// The teamsfx tasks defined in this file require Teams Toolkit version >= 5.0.0.
3+
// See https://aka.ms/teamsfx-tasks for details on how to customize each task.
4+
{
5+
"version": "2.0.0",
6+
"tasks": [
7+
{
8+
"label": "Prepare Teams App Resources",
9+
"dependsOn": [
10+
"Validate prerequisites",
11+
"Start local tunnel",
12+
"Provision",
13+
"Deploy"
14+
],
15+
"dependsOrder": "sequence"
16+
},
17+
{
18+
// Check all required prerequisites.
19+
// See https://aka.ms/teamsfx-tasks/check-prerequisites to know the details and how to customize the args.
20+
"label": "Validate prerequisites",
21+
"type": "teamsfx",
22+
"command": "debug-check-prerequisites",
23+
"args": {
24+
"prerequisites": [
25+
"m365Account", // Sign-in prompt for Microsoft 365 account, then validate if the account enables the sideloading permission.
26+
"portOccupancy" // Validate available ports to ensure those debug ones are not occupied.
27+
],
28+
"portOccupancy": [
29+
3978, // app service port
30+
]
31+
}
32+
},
33+
{
34+
// Start the local tunnel service to forward public URL to local port and inspect traffic.
35+
// See https://aka.ms/teamsfx-tasks/local-tunnel for the detailed args definitions.
36+
"label": "Start local tunnel",
37+
"type": "teamsfx",
38+
"command": "debug-start-local-tunnel",
39+
"args": {
40+
"type": "dev-tunnel",
41+
"ports": [
42+
{
43+
"portNumber": 3978,
44+
"protocol": "http",
45+
"access": "public",
46+
"writeToEnvironmentFile": {
47+
"endpoint": "BOT_ENDPOINT", // output tunnel endpoint as BOT_ENDPOINT
48+
"domain": "BOT_DOMAIN" // output tunnel domain as BOT_DOMAIN
49+
}
50+
}
51+
],
52+
"env": "local"
53+
},
54+
"isBackground": true,
55+
"problemMatcher": "$teamsfx-local-tunnel-watch"
56+
},
57+
{
58+
// Create the debug resources.
59+
// See https://aka.ms/teamsfx-tasks/provision to know the details and how to customize the args.
60+
"label": "Provision",
61+
"type": "teamsfx",
62+
"command": "provision",
63+
"args": {
64+
"env": "local"
65+
}
66+
},
67+
{
68+
// Build project.
69+
// See https://aka.ms/teamsfx-tasks/deploy to know the details and how to customize the args.
70+
"label": "Deploy",
71+
"type": "teamsfx",
72+
"command": "deploy",
73+
"args": {
74+
"env": "local"
75+
}
76+
}
77+
]
78+
}
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
page_type: sample
3+
description: This Teams bot enables configuration and reconfiguration with dynamic search capabilities on Adaptive Cards.
4+
products:
5+
- office-teams
6+
- office
7+
- office-365
8+
languages:
9+
- python
10+
extensions:
11+
contentType: samples
12+
createdDate: "31-12-2024 13:38:25"
13+
urlFragment: officedev-microsoft-teams-samples-bot-configuration-app-auth-nodejs
14+
---
15+
16+
# Create a commands menu
17+
This sample illustrates bot configuration and reconfiguration in Teams and group chats, showcasing a type-ahead search feature on Adaptive Cards. It supports both static and dynamic search options, enabling a customizable and interactive bot experience for users.
18+
19+
## Included Features
20+
* Bots
21+
22+
## Interaction with app
23+
24+
![Configuration Bot](Images/ConfigurationBot.gif)
25+
26+
## Prerequisites
27+
28+
- Microsoft Teams is installed and you have an account
29+
- [Python SDK](https://www.python.org/downloads/) min version 3.6
30+
- [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
31+
32+
33+
## Run the app (Using Teams Toolkit for Visual Studio Code)
34+
35+
The simplest way to run this sample in Teams is to use Teams Toolkit for Visual Studio Code.
36+
37+
1. Ensure you have downloaded and installed [Visual Studio Code](https://code.visualstudio.com/docs/setup/setup-overview)
38+
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)
39+
1. Select **File > Open Folder** in VS Code and choose this samples directory from the repo
40+
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.
41+
1. Using the extension, sign in with your Microsoft 365 account where you have permissions to upload custom apps
42+
1. Select **Debug > Start Debugging** or **F5** to run the app in a Teams web client.
43+
1. In the browser that launches, select the **Add** button to install the app to Teams.
44+
45+
> 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.
46+
47+
## Run the app (Manually Uploading to Teams)
48+
49+
> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
50+
the Teams service needs to call into the bot.
51+
52+
1) Clone the repository
53+
54+
```bash
55+
git clone https://github.com/OfficeDev/Microsoft-Teams-Samples.git
56+
```
57+
58+
2) Run ngrok - point to port 3978
59+
60+
```bash
61+
ngrok http 3978 --host-header="localhost:3978"
62+
```
63+
64+
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:
65+
66+
```bash
67+
devtunnel host -p 3978 --allow-anonymous
68+
```
69+
70+
3) Create [Azure Bot resource resource](https://docs.microsoft.com/azure/bot-service/bot-service-quickstart-registration) in Azure
71+
- Use the current `https` URL you were given by running the tunneling application. Append with the path `/api/messages` used by this sample
72+
- Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
73+
- __*If you don't have an Azure account*__ you can use this [Azure free account here](https://azure.microsoft.com/free/)
74+
75+
4) In a terminal, go to `samples\bot-configuration-app-auth`
76+
77+
5) Activate your desired virtual environment
78+
79+
6) Install dependencies by running ```pip install -r requirements.txt``` in the project folder.
80+
81+
7) 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.)
82+
83+
8) __*This step is specific to Teams.*__
84+
- **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`)
85+
- **Zip** up the contents of the `appManifest` folder to create a `manifest.zip`
86+
- **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")
87+
88+
9) Run your bot with `python app.py`
89+
90+
# Running the sample
91+
You can interact with this bot in Teams by sending it a message, or selecting a command from the command list. The bot will respond to the following strings.
92+
93+
**Configurable Card**
94+
A configurable card is used to modify data even after the bot has been installed. When the bot is added to a Teams or group chat scope, it utilizes 'config/fetch' and 'config/submit' invoke requests.
95+
96+
- **Result:** The bot will send the configurable adaptive card
97+
- **Valid Scopes:** group chat, team chat
98+
99+
- **Bot Interactions:**
100+
101+
**Adding bot UI:**
102+
![groupChat-AddBot ](Images/groupChat-AddBot.png)
103+
104+
**Added bot UI:**
105+
![groupChat-AddedBot ](Images/groupChat-AddedBot.png)
106+
107+
**Option 1 : Auth card Interactions:**
108+
- Note: The `Sign-in` page displayed is currently using a dummy URL. Please update it with your authentication URL.
109+
110+
![Bot-description-card](Images/Bot-description-card.png)
111+
112+
## Further reading
113+
114+
- [Bot configuration](https://learn.microsoft.com/microsoftteams/platform/bots/how-to/bot-configuration-experience)
115+
- [Bot Framework Documentation](https://docs.botframework.com)
116+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
117+
- [Send Notification to User in Chat](https://docs.microsoft.com/graph/api/chat-sendactivitynotification?view=graph-rest-beta)
118+
- [Send Notification to User in Team](https://docs.microsoft.com/graph/api/team-sendactivitynotification?view=graph-rest-beta&tabs=http)
119+
- [Send Notification to User](https://docs.microsoft.com/graph/api/userteamwork-sendactivitynotification?view=graph-rest-beta&tabs=http)
120+
121+
<img src="https://pnptelemetry.azurewebsites.net/microsoft-teams-samples/samples/bot-configuration-app-auth-python" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
import sys
5+
import traceback
6+
import uuid
7+
from datetime import datetime
8+
from http import HTTPStatus
9+
10+
from aiohttp import web
11+
from aiohttp.web import Request, Response, json_response
12+
from botbuilder.core import (
13+
BotFrameworkAdapterSettings,
14+
TurnContext,
15+
BotFrameworkAdapter,
16+
)
17+
from botbuilder.core.integration import aiohttp_error_middleware
18+
from botbuilder.schema import Activity, ActivityTypes
19+
20+
from bots import TeamsBot
21+
from config import DefaultConfig
22+
23+
CONFIG = DefaultConfig()
24+
25+
# Create adapter.
26+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
27+
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
28+
ADAPTER = BotFrameworkAdapter(SETTINGS)
29+
30+
31+
# Catch-all for errors.
32+
async def on_error(context: TurnContext, error: Exception):
33+
# This check writes out errors to console log .vs. app insights.
34+
# NOTE: In production environment, you should consider logging this to Azure
35+
# application insights.
36+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
37+
traceback.print_exc()
38+
39+
# Send a message to the user
40+
await context.send_activity("The bot encountered an error or bug.")
41+
await context.send_activity(
42+
"To continue to run this bot, please fix the bot source code."
43+
)
44+
# Send a trace activity if we're talking to the Bot Framework Emulator
45+
if context.activity.channel_id == "emulator":
46+
# Create a trace activity that contains the error object
47+
trace_activity = Activity(
48+
label="TurnError",
49+
name="on_turn_error Trace",
50+
timestamp=datetime.utcnow(),
51+
type=ActivityTypes.trace,
52+
value=f"{error}",
53+
value_type="https://www.botframework.com/schemas/error",
54+
)
55+
# Send a trace activity, which will be displayed in Bot Framework Emulator
56+
await context.send_activity(trace_activity)
57+
58+
59+
ADAPTER.on_turn_error = on_error
60+
61+
# If the channel is the Emulator, and authentication is not in use, the AppId will be null.
62+
# We generate a random AppId for this case only. This is not required for production, since
63+
# the AppId will have a value.
64+
APP_ID = SETTINGS.app_id if SETTINGS.app_id else uuid.uuid4()
65+
BASE_URL = CONFIG.BOT_ENDPOINT
66+
# Create the Bot
67+
BOT = TeamsBot()
68+
69+
70+
# Listen for incoming requests on /api/messages.
71+
async def messages(req: Request) -> Response:
72+
# Main bot message handler.
73+
if "application/json" in req.headers["Content-Type"]:
74+
body = await req.json()
75+
else:
76+
return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
77+
78+
activity = Activity().deserialize(body)
79+
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
80+
81+
response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
82+
if response:
83+
return json_response(data=response.body, status=response.status)
84+
return Response(status=HTTPStatus.OK)
85+
86+
87+
APP = web.Application(middlewares=[aiohttp_error_middleware])
88+
APP.router.add_post("/api/messages", messages)
89+
90+
if __name__ == "__main__":
91+
try:
92+
web.run_app(APP, host="localhost", port=CONFIG.PORT)
93+
except Exception as error:
94+
raise error
Loading

0 commit comments

Comments
 (0)