diff --git a/samples/bot-configuration-app-auth/python/.gitignore b/samples/bot-configuration-app-auth/python/.gitignore new file mode 100644 index 0000000000..e8442994dd --- /dev/null +++ b/samples/bot-configuration-app-auth/python/.gitignore @@ -0,0 +1,14 @@ +# TeamsFx files +env/.env.*.user +env/.env.local +appManifest/build/ + +# python virtual environment +.venv/ + +# misc +.env +.deployment/ + +# tmp files +__pycache__/ \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/.vscode/extensions.json b/samples/bot-configuration-app-auth/python/.vscode/extensions.json new file mode 100644 index 0000000000..bf8c33db9c --- /dev/null +++ b/samples/bot-configuration-app-auth/python/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "TeamsDevApp.ms-teams-vscode-extension", + "ms-python.python", + ] +} \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/.vscode/launch.json b/samples/bot-configuration-app-auth/python/.vscode/launch.json new file mode 100644 index 0000000000..6d66d8beb8 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/.vscode/launch.json @@ -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 + } + ] +} \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/.vscode/settings.json b/samples/bot-configuration-app-auth/python/.vscode/settings.json new file mode 100644 index 0000000000..3014fd9cf0 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} diff --git a/samples/bot-configuration-app-auth/python/.vscode/tasks.json b/samples/bot-configuration-app-auth/python/.vscode/tasks.json new file mode 100644 index 0000000000..2161094dcc --- /dev/null +++ b/samples/bot-configuration-app-auth/python/.vscode/tasks.json @@ -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" + } + } + ] +} \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/Images/Bot-description-card.png b/samples/bot-configuration-app-auth/python/Images/Bot-description-card.png new file mode 100644 index 0000000000..6536083613 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/Bot-description-card.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/ConfigurationBot.gif b/samples/bot-configuration-app-auth/python/Images/ConfigurationBot.gif new file mode 100644 index 0000000000..20e7d6a669 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/ConfigurationBot.gif differ diff --git a/samples/bot-configuration-app-auth/python/Images/configbutton.png b/samples/bot-configuration-app-auth/python/Images/configbutton.png new file mode 100644 index 0000000000..bb87cf8169 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/configbutton.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction1.png b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction1.png new file mode 100644 index 0000000000..d32888341d Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction1.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction2.png b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction2.png new file mode 100644 index 0000000000..4e92d5c1b4 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction2.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction3.png b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction3.png new file mode 100644 index 0000000000..7e0e0b60a6 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction3.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction4.png b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction4.png new file mode 100644 index 0000000000..82af12175e Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/configurable-card-Interaction4.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/groupChat-AddBot.png b/samples/bot-configuration-app-auth/python/Images/groupChat-AddBot.png new file mode 100644 index 0000000000..ccc0d2e19f Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/groupChat-AddBot.png differ diff --git a/samples/bot-configuration-app-auth/python/Images/groupChat-AddedBot.png b/samples/bot-configuration-app-auth/python/Images/groupChat-AddedBot.png new file mode 100644 index 0000000000..01a08cc111 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/Images/groupChat-AddedBot.png differ diff --git a/samples/bot-configuration-app-auth/python/README.md b/samples/bot-configuration-app-auth/python/README.md new file mode 100644 index 0000000000..e57b40f736 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/README.md @@ -0,0 +1,121 @@ +--- +page_type: sample +description: This Teams bot enables configuration and reconfiguration with dynamic search capabilities on Adaptive Cards. +products: +- office-teams +- office +- office-365 +languages: +- python +extensions: + contentType: samples + createdDate: "31-12-2024 13:38:25" +urlFragment: officedev-microsoft-teams-samples-bot-configuration-app-auth-nodejs +--- + +# Create a commands menu +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. + +## Included Features +* Bots + +## Interaction with app + +![Configuration Bot](Images/ConfigurationBot.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 + + +## 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) + +> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because +the Teams service needs to call into the bot. + +1) Clone the repository + + ```bash + git clone https://github.com/OfficeDev/Microsoft-Teams-Samples.git + ``` + +2) 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 + ``` + +3) Create [Azure Bot resource resource](https://docs.microsoft.com/azure/bot-service/bot-service-quickstart-registration) in Azure + - Use the current `https` URL you were given by running the tunneling application. Append with the path `/api/messages` used by this sample + - Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0) + - __*If you don't have an Azure account*__ you can use this [Azure free account here](https://azure.microsoft.com/free/) + +4) In a terminal, go to `samples\bot-configuration-app-auth` + +5) Activate your desired virtual environment + +6) Install dependencies by running ```pip install -r requirements.txt``` in the project folder. + +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.) + +8) __*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") + +9) Run your bot with `python app.py` + +# Running the sample +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. + + **Configurable Card** + 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. + + - **Result:** The bot will send the configurable adaptive card + - **Valid Scopes:** group chat, team chat + + - **Bot Interactions:** + + **Adding bot UI:** + ![groupChat-AddBot ](Images/groupChat-AddBot.png) + + **Added bot UI:** + ![groupChat-AddedBot ](Images/groupChat-AddedBot.png) + + **Option 1 : Auth card Interactions:** + - Note: The `Sign-in` page displayed is currently using a dummy URL. Please update it with your authentication URL. + + ![Bot-description-card](Images/Bot-description-card.png) + +## Further reading + +- [Bot configuration](https://learn.microsoft.com/microsoftteams/platform/bots/how-to/bot-configuration-experience) +- [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) +- [Send Notification to User in Chat](https://docs.microsoft.com/graph/api/chat-sendactivitynotification?view=graph-rest-beta) +- [Send Notification to User in Team](https://docs.microsoft.com/graph/api/team-sendactivitynotification?view=graph-rest-beta&tabs=http) +- [Send Notification to User](https://docs.microsoft.com/graph/api/userteamwork-sendactivitynotification?view=graph-rest-beta&tabs=http) + + \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/app.py b/samples/bot-configuration-app-auth/python/app.py new file mode 100644 index 0000000000..aae5fb82d0 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/app.py @@ -0,0 +1,94 @@ +# 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 TeamsBot +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 + +# 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() +BASE_URL = CONFIG.BOT_ENDPOINT +# Create the Bot +BOT = TeamsBot() + + +# 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) + + +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/samples/bot-configuration-app-auth/python/appManifest/color.png b/samples/bot-configuration-app-auth/python/appManifest/color.png new file mode 100644 index 0000000000..b8cf81afbe Binary files /dev/null and b/samples/bot-configuration-app-auth/python/appManifest/color.png differ diff --git a/samples/bot-configuration-app-auth/python/appManifest/manifest.json b/samples/bot-configuration-app-auth/python/appManifest/manifest.json new file mode 100644 index 0000000000..b803dcbdf1 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/appManifest/manifest.json @@ -0,0 +1,50 @@ +{ + "$schema": "https://raw.githubusercontent.com/OfficeDev/microsoft-teams-app-schema/preview/DevPreview/MicrosoftTeams.schema.json", + "manifestVersion": "devPreview", + "version": "1.0.0", + "id": "${{TEAMS_APP_ID}}", + "packageName": "com.microsoft.teams.botconfigurationauth", + "developer": { + "name": "Microsoft", + "websiteUrl": "https://www.microsoft.com", + "privacyUrl": "https://www.microsoft.com/privacy", + "termsOfUseUrl": "https://www.microsoft.com/termsofuse" + }, + "name": { + "short": "Bot Configuration auth Sample", + "full": "Bot Configuration auth Sample App" + }, +"description": { + "short": "Configurable Teams bot with dynamic type-ahead search and Adaptive Cards.", + "full": "This Teams bot enables configuration and reconfiguration with dynamic search capabilities on Adaptive Cards." +}, + "icons": { + "outline": "outline.png", + "color": "color.png" + }, + "accentColor": "#60A18E", + "bots": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "needsChannelSelector": false, + "scopes": [ + "personal", + "team", + "groupChat" + ], + "configuration":{ + "groupChat":{ + "fetchTask": true + }, + "team":{ + "fetchTask": true + } + }, + "isNotificationOnly": false + } + ], + "permissions": [ "identity", "messageTeamMembers" ], + "validDomains": [ + "${{BOT_DOMAIN}}" + ] +} \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/appManifest/outline.png b/samples/bot-configuration-app-auth/python/appManifest/outline.png new file mode 100644 index 0000000000..2c3bf6fa65 Binary files /dev/null and b/samples/bot-configuration-app-auth/python/appManifest/outline.png differ diff --git a/samples/bot-configuration-app-auth/python/assets/sample.json b/samples/bot-configuration-app-auth/python/assets/sample.json new file mode 100644 index 0000000000..63410faf00 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-bot-configuration-app-auth-python", + "source": "officeDev", + "title": "Bot configuration app with auth", + "shortDescription": "This Teams bot enables configuration and reconfiguration with dynamic search capabilities on Adaptive Cards.", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/bot-configuration-app-auth/python", + "longDescription": [ + "This sample demonstrates a configurable Teams bot that supports both static and dynamic type-ahead search controls on Adaptive Cards. It offers flexible bot configuration and reconfiguration for team and group chats." + ], + "creationDateTime": "2024-12-31", + "updateDateTime": "2024-12-31", + "products": [ + "Teams" + ], + "metadata": [ + { + "key": "TEAMS-SAMPLE-SOURCE", + "value": "OfficeDev" + }, + { + "key": "TEAMS-SERVER-LANGUAGE", + "value": "python" + }, + { + "key": "TEAMS-SERVER-PLATFORM", + "value": "python" + }, + { + "key": "TEAMS-FEATURES", + "value": "bot" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/bot-configuration-app-auth/nodejs/Images/ConfigurationBot.gif", + "alt": "Solution UX showing the feature of bot configuration and reconfiguration for bots in team and group chat" + } + ], + "authors": [ + { + "gitHubAccount": "OfficeDev", + "pictureUrl": "https://avatars.githubusercontent.com/u/6789362?s=200&v=4", + "name": "OfficeDev" + } + ], + "references": [ + { + "name": "Teams developer documentation", + "url": "https://aka.ms/TeamsPlatformDocs" + }, + { + "name": "Teams developer questions", + "url": "https://aka.ms/TeamsPlatformFeedback" + }, + { + "name": "Teams development videos from Microsoft", + "url": "https://aka.ms/sample-ref-teams-vids-from-microsoft" + }, + { + "name": "Teams development videos from the community", + "url": "https://aka.ms/community/videos/m365powerplatform" + } + ] + } +] \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/bots/__init__.py b/samples/bot-configuration-app-auth/python/bots/__init__.py new file mode 100644 index 0000000000..f692c91551 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/bots/__init__.py @@ -0,0 +1,3 @@ +from .bot_configuration_auth import TeamsBot + +__all__ = ["TeamsBot"] \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/bots/bot_configuration_auth.py b/samples/bot-configuration-app-auth/python/bots/bot_configuration_auth.py new file mode 100644 index 0000000000..cb6a7f20fc --- /dev/null +++ b/samples/bot-configuration-app-auth/python/bots/bot_configuration_auth.py @@ -0,0 +1,89 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from botbuilder.core import ActivityHandler, MessageFactory, InvokeResponse +from botbuilder.schema import Activity, Attachment +from http import HTTPStatus +import base64 + +class TeamsBot(ActivityHandler): + def __init__(self): + super().__init__() + + async def on_members_added_activity(self, members_added, turn_context): + image_path = 'Images/configbutton.png' + with open(image_path, 'rb') as image_file: + image_base64 = base64.b64encode(image_file.read()).decode('utf-8') + + adaptive_card = { + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "type": "AdaptiveCard", + "version": "1.0", + "body": [ + { + "type": "TextBlock", + "text": "Hello and welcome! With this sample, you can experience the functionality of bot configuration. To access Bot configuration, click on the settings button in the bot description card.", + "wrap": True, + "size": "large", + "weight": "bolder" + }, + { + "type": "Image", + "url": f"data:image/jpeg;base64,{image_base64}", + "size": "auto" + } + ], + "fallbackText": "This card requires Adaptive Card support." + } + + card_attachment = Attachment( + content_type="application/vnd.microsoft.card.adaptive", + content=adaptive_card + ) + + activity = Activity( + attachments=[card_attachment], + text="" + ) + + await turn_context.send_activity(activity) + + async def on_message_activity(self, turn_context): + # Placeholder for further message handling logic + await super().on_message_activity(turn_context) + + async def on_invoke_activity(self, turn_context): + if turn_context.activity.name == "config/fetch": + return await self.handle_teams_config_fetch(turn_context) + elif turn_context.activity.name == "config/submit": + return await self.handle_teams_config_submit(turn_context) + else: + return InvokeResponse(status=HTTPStatus.NOT_IMPLEMENTED) + + async def handle_teams_config_fetch(self, turn_context): + # Configuration fetch logic + response = { + "config": { + "type": "auth", + "suggestedActions": { + "actions": [ + { + "type": "openUrl", + "value": "https://example.com/auth", + "title": "Sign in to this app" + } + ] + }, + }, + } + return InvokeResponse(status=HTTPStatus.OK, body=response) + + async def handle_teams_config_submit(self, turn_context): + # Configuration submit logic + response = { + "config": { + "type": "message", + "value": "You have chosen to finish setting up bot", + }, + } + return InvokeResponse(status=HTTPStatus.OK, body=response) \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/config.py b/samples/bot-configuration-app-auth/python/config.py new file mode 100644 index 0000000000..7815d9e28d --- /dev/null +++ b/samples/bot-configuration-app-auth/python/config.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import os + +""" Bot Configuration """ + + +class DefaultConfig: + """ Bot Configuration """ + + PORT = 3978 + APP_ID = os.environ.get("MicrosoftAppId", "<>") + APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "<>") + BOT_ENDPOINT = os.environ.get("BaseUrl", "<>") \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/env/.env.local b/samples/bot-configuration-app-auth/python/env/.env.local new file mode 100644 index 0000000000..553698b86a --- /dev/null +++ b/samples/bot-configuration-app-auth/python/env/.env.local @@ -0,0 +1,21 @@ +# This file includes environment variables that can be committed to git. It's gitignored by default because it represents your local development environment. + +# Built-in environment variables +TEAMSFX_ENV=local + +# Generated during provision, you can also add your own variables. If you're adding a secret value, add SECRET_ prefix to the name so Teams Toolkit can handle them properly +BOT_ENDPOINT= +BOT_DOMAIN= +AAD_APP_CLIENT_ID= +AAD_APP_OBJECT_ID= +AAD_APP_TENANT_ID= +AAD_APP_OAUTH_AUTHORITY= +AAD_APP_OAUTH_AUTHORITY_HOST= +TEAMS_APP_ID= +TEAMS_APP_TENANT_ID= +MICROSOFT_APP_TYPE= +MICROSOFT_APP_TENANT_ID= +RESOURCE_SUFFIX= +AZURE_SUBSCRIPTION_ID= +AZURE_RESOURCE_GROUP_NAME= +APP_NAME_SUFFIX=local \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/infra/azure.bicep b/samples/bot-configuration-app-auth/python/infra/azure.bicep new file mode 100644 index 0000000000..8734cb547b --- /dev/null +++ b/samples/bot-configuration-app-auth/python/infra/azure.bicep @@ -0,0 +1,42 @@ +@maxLength(20) +@minLength(4) +@description('Used to generate names for all resources in this file') +param resourceBaseName string + +@description('Required when create Azure Bot service') +param botAadAppClientId string + +param botAppDomain string + +@maxLength(42) +param botDisplayName string + +param botServiceName string = resourceBaseName +param botServiceSku string = 'F0' + +// Register your web service as a bot with the Bot Framework +resource botService 'Microsoft.BotService/botServices@2021-03-01' = { + kind: 'azurebot' + location: 'global' + name: botServiceName + properties: { + displayName: botDisplayName + endpoint: 'https://${botAppDomain}/api/messages' + msaAppId: botAadAppClientId + msaAppType: 'MultiTenant' + msaAppTenantId: '' + } + sku: { + name: botServiceSku + } +} + +// Connect the bot service to Microsoft Teams +resource botServiceMsTeamsChannel 'Microsoft.BotService/botServices/channels@2021-03-01' = { + parent: botService + location: 'global' + name: 'MsTeamsChannel' + properties: { + channelName: 'MsTeamsChannel' + } +} diff --git a/samples/bot-configuration-app-auth/python/infra/azure.parameters.json b/samples/bot-configuration-app-auth/python/infra/azure.parameters.json new file mode 100644 index 0000000000..7474499bdb --- /dev/null +++ b/samples/bot-configuration-app-auth/python/infra/azure.parameters.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "resourceBaseName": { + "value": "bot${{RESOURCE_SUFFIX}}" + }, + "botAadAppClientId": { + "value": "${{AAD_APP_CLIENT_ID}}" + }, + "botAppDomain": { + "value": "${{BOT_DOMAIN}}" + }, + "botDisplayName": { + "value": "TeamsConversationBot" + } + } + } \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/requirements.txt b/samples/bot-configuration-app-auth/python/requirements.txt new file mode 100644 index 0000000000..c6424216e6 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/requirements.txt @@ -0,0 +1,2 @@ +requests==2.31.0 +botbuilder-integration-aiohttp>=4.14.5 diff --git a/samples/bot-configuration-app-auth/python/teamsapp.local.yml b/samples/bot-configuration-app-auth/python/teamsapp.local.yml new file mode 100644 index 0000000000..33c56a6d83 --- /dev/null +++ b/samples/bot-configuration-app-auth/python/teamsapp.local.yml @@ -0,0 +1,78 @@ +# yaml-language-server: $schema=https://aka.ms/teams-toolkit/v1.2/yaml.schema.json +# Visit https://aka.ms/teamsfx-v5.0-guide for details on this file +# Visit https://aka.ms/teamsfx-actions for details on actions +version: v1.2 + +additionalMetadata: + sampleTag: Microsoft-Teams-Samples:bot-configuration-app-auth-python + +provision: + # Creates a new Azure Active Directory (AAD) app to authenticate users if the environment variable that stores clientId is empty + - uses: aadApp/create + with: + name: teamsConversationBot-aad # Note: when you run aadApp/update, the AAD app name will be updated based on the definition in manifest. If you don't want to change the name, make sure the name in AAD manifest is the same with the name defined here. + generateClientSecret: true # If the value is false, the action will not generate client secret for you + signInAudience: "AzureADMultipleOrgs" # Multitenant + writeToEnvironmentFile: # Write the information of created resources into environment file for the specified environment variable(s). + clientId: AAD_APP_CLIENT_ID + clientSecret: SECRET_AAD_APP_CLIENT_SECRET # Environment variable that starts with `SECRET_` will be stored to the .env.{envName}.user environment file + objectId: AAD_APP_OBJECT_ID + tenantId: AAD_APP_TENANT_ID + authority: AAD_APP_OAUTH_AUTHORITY + authorityHost: AAD_APP_OAUTH_AUTHORITY_HOST + + # Creates a Teams app + - uses: teamsApp/create + with: + # Teams app name + name: teamsConversationBot${{APP_NAME_SUFFIX}} + # Write the information of created resources into environment file for + # the specified environment variable(s). + writeToEnvironmentFile: + teamsAppId: TEAMS_APP_ID + + - uses: arm/deploy # Deploy given ARM templates parallelly. + with: + subscriptionId: ${{AZURE_SUBSCRIPTION_ID}} # The AZURE_SUBSCRIPTION_ID is a built-in environment variable. TeamsFx will ask you select one subscription if its value is empty. You're free to reference other environment varialbe here, but TeamsFx will not ask you to select subscription if it's empty in this case. + resourceGroupName: ${{AZURE_RESOURCE_GROUP_NAME}} # The AZURE_RESOURCE_GROUP_NAME is a built-in environment variable. TeamsFx will ask you to select or create one resource group if its value is empty. You're free to reference other environment varialbe here, but TeamsFx will not ask you to select or create resource grouop if it's empty in this case. + templates: + - path: ./infra/azure.bicep + parameters: ./infra/azure.parameters.json + deploymentName: Create-resources-for-bot + bicepCliVersion: v0.9.1 # Teams Toolkit will download this bicep CLI version from github for you, will use bicep CLI in PATH if you remove this config. + + # Validate using manifest schema + - uses: teamsApp/validateManifest + with: + # Path to manifest template + manifestPath: ./appManifest/manifest.json + + # Build Teams app package with latest env value + - uses: teamsApp/zipAppPackage + with: + # Path to manifest template + manifestPath: ./appManifest/manifest.json + outputZipPath: ./appManifest/build/appManifest.${{TEAMSFX_ENV}}.zip + outputJsonPath: ./appManifest/build/manifest.${{TEAMSFX_ENV}}.json + # Validate app package using validation rules + - uses: teamsApp/validateAppPackage + with: + # Relative path to this file. This is the path for built zip file. + appPackagePath: ./appManifest/build/appManifest.${{TEAMSFX_ENV}}.zip + + # Apply the Teams app manifest to an existing Teams app in + # Teams Developer Portal. + # Will use the app id in manifest file to determine which Teams app to update. + - uses: teamsApp/update + with: + # Relative path to this file. This is the path for built zip file. + appPackagePath: ./appManifest/build/appManifest.${{TEAMSFX_ENV}}.zip + +deploy: + # Generate runtime environment variables + - uses: file/createOrUpdateEnvironmentFile + with: + target: ./.env + envs: + MicrosoftAppId: ${{AAD_APP_CLIENT_ID}} + MicrosoftAppPassword: ${{SECRET_AAD_APP_CLIENT_SECRET}} \ No newline at end of file diff --git a/samples/bot-configuration-app-auth/python/teamsapp.yml b/samples/bot-configuration-app-auth/python/teamsapp.yml new file mode 100644 index 0000000000..444271b3fe --- /dev/null +++ b/samples/bot-configuration-app-auth/python/teamsapp.yml @@ -0,0 +1,9 @@ +# yaml-language-server: $schema=https://aka.ms/teams-toolkit/v1.2/yaml.schema.json +# Visit https://aka.ms/teamsfx-v5.0-guide for details on this file +# Visit https://aka.ms/teamsfx-actions for details on actions +version: v1.2 + +additionalMetadata: + sampleTag: Microsoft-Teams-Samples:bot-configuration-app-auth-python + +environmentFolderPath: ./env