diff --git a/samples/bot-all-cards/python/.env b/samples/bot-all-cards/python/.env new file mode 100644 index 0000000000..ecba2484b2 --- /dev/null +++ b/samples/bot-all-cards/python/.env @@ -0,0 +1,4 @@ +MicrosoftAppId= +MicrosoftAppPassword= +connectionName= +MicrosoftAppTenantId= \ No newline at end of file diff --git a/samples/bot-all-cards/python/.gitignore b/samples/bot-all-cards/python/.gitignore new file mode 100644 index 0000000000..e8442994dd --- /dev/null +++ b/samples/bot-all-cards/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-all-cards/python/.vscode/extensions.json b/samples/bot-all-cards/python/.vscode/extensions.json new file mode 100644 index 0000000000..e81b1beb93 --- /dev/null +++ b/samples/bot-all-cards/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-all-cards/python/.vscode/launch.json b/samples/bot-all-cards/python/.vscode/launch.json new file mode 100644 index 0000000000..9c7356e267 --- /dev/null +++ b/samples/bot-all-cards/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": "python", + "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 + } + ] +} diff --git a/samples/bot-all-cards/python/.vscode/settings.json b/samples/bot-all-cards/python/.vscode/settings.json new file mode 100644 index 0000000000..3014fd9cf0 --- /dev/null +++ b/samples/bot-all-cards/python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} diff --git a/samples/bot-all-cards/python/.vscode/tasks.json b/samples/bot-all-cards/python/.vscode/tasks.json new file mode 100644 index 0000000000..a11f46be58 --- /dev/null +++ b/samples/bot-all-cards/python/.vscode/tasks.json @@ -0,0 +1,78 @@ +// This file is automatically generated by Microsoft 365 Agents Toolkit. +// The teamsfx tasks defined in this file require Microsoft 365 Agents 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 uploading 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-all-cards/python/README.md b/samples/bot-all-cards/python/README.md new file mode 100644 index 0000000000..3392063bdf --- /dev/null +++ b/samples/bot-all-cards/python/README.md @@ -0,0 +1,160 @@ +--- +page_type: sample +description: This sample demonstrates using a bot to send multiple card types in Microsoft Teams, including Adaptive, Hero, Thumbnail, and OAuth cards. It covers setup, deployment, and app installation instructions. +products: +- office-teams +- office +- office-365 +languages: +- Python +extensions: + contentType: samples + createdDate: "2025-19-08" +urlFragment: officedev-microsoft-teams-samples-bot-all-cards-python +--- + +# Types of Cards + +This Microsoft Teams bot sample demonstrates sending various card types, such as Adaptive, Hero, List, and Thumbnail cards. It includes detailed steps for setup, app deployment, and using Microsoft 365 Agents Toolkit for Visual Studio to run the app. Experience this versatile bot directly within your Teams client, complete with a manifest for easy uploading. + +## Included Features +* Bots +* Adaptive Cards +* Hero Cards +* List Cards +* O365 Connector Cards +* List Cards +* Thumbnail Cards +* Collections Cards + +## Interaction with app + +![Types Of Cards](Images/TypesOfCards.gif) + +## Try it yourself - experience the App in your Microsoft Teams client +Please find below demo manifest which is deployed on Microsoft Azure and you can try it yourself by uploading the app package (.zip file link below) to your teams and/or as a personal app. (Uploading must be enabled for your tenant, [see steps here](https://docs.microsoft.com/microsoftteams/platform/concepts/build-and-test/prepare-your-o365-tenant#enable-custom-teams-apps-and-turn-on-custom-app-uploading)). + +**Different types of cards:** [Manifest](/samples/bot-all-cards/csharp/demo-manifest/bot-all-cards.zip) +## Prerequisites + +- Microsoft Teams is installed and you have an account +- [Python SDK](https://www.python.org/downloads/) min version 3.8 +- [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 +- [Microsoft 365 Agents 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 Microsoft 365 Agents Toolkit for Visual Studio Code) + +The simplest way to run this sample in Teams is to use Microsoft 365 Agents 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 [Microsoft 365 Agents 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 (uploading), Microsoft 365 Agents 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. + +## Setup for bot + +In Azure portal, create a [Azure Bot resource](https://docs.microsoft.com/azure/bot-service/bot-service-quickstart-registration). + - For bot handle, make up a name. + - Select "Use existing app registration" (Create the app registration in Microsoft Entra ID beforehand.) + - __*If you don't have an Azure account*__ create an [Azure free account here](https://azure.microsoft.com/free/) + + In the new Azure Bot resource in the Portal, + - Ensure that you've [enabled the Teams Channel](https://learn.microsoft.com/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0) + - In Settings/Configuration/Messaging endpoint, enter the current `https` URL you were given by running the tunneling application. Append it with the path `/api/messages` + +## Run the app (Manually Uploading to Teams) +## Setup for code +> 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) In a terminal, navigate to `samples/bot-all-cards/python` + +4) Activate your desired virtual environment + +5) Install dependencies by running ```pip install -r requirements.txt``` in the project folder. + +6) 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.) + +7) __*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") + +8) Run your bot with `python app.py` + + - If you are using the Microsoft 365 Agents Toolkit for Visual Studio Code, this step is done for you when you select **Debug > Start Debugging** or **F5**. + +## Running the sample + +**Install App:** + +![InstallApp](Images/1.Install.png) + +**Welcome Message:** + +![Initial message](Images/2.Welcome.png) + +**Adaptive Card:** + +![Adaptive Card](Images/3.AdaptiveCard.png) + +**Hero Card:** + +![Hero Card](Images/4.HeroCard.png) + +**List Card:** + +![List Card](Images/5.ListCard.png) + +**Office365 Card:** + +![Office365 Connector Card](Images/6.Office365Card.png) + +**SignIn Card:** + +![SignIn Card](Images/8.SignInCard.png) + +**Thumbnail Card:** + +![Thumbnail Card](Images/9.ThumbnailCard.png) + +**Collection Card:** + +![Collection Card](Images/7.CollectionCard.png) + +**Oauth Card:** + +![Oauth Card](Images/8.SignInCard.png) + +## 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 +- [Types Of Cards](https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#thumbnail-card) +- [Send a hero card](https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-add-media-attachments?view=azure-bot-service-4.0&tabs=javascript#send-a-hero-card&preserve-view=true) + + \ No newline at end of file diff --git a/samples/bot-all-cards/python/aad.manifest.json b/samples/bot-all-cards/python/aad.manifest.json new file mode 100644 index 0000000000..4d798d01cb --- /dev/null +++ b/samples/bot-all-cards/python/aad.manifest.json @@ -0,0 +1,107 @@ +{ + "id": "${{AAD_APP_OBJECT_ID}}", + "appId": "${{AAD_APP_CLIENT_ID}}", + "name": "bot-all-cards-aad", + "accessTokenAcceptedVersion": 2, + "signInAudience": "AzureADandPersonalMicrosoftAccount", + "oauth2AllowIdTokenImplicitFlow": true, + "oauth2AllowImplicitFlow": true, + "optionalClaims": { + "idToken": [], + "accessToken": [ + { + "name": "idtyp", + "source": null, + "essential": false, + "additionalProperties": [] + } + ], + "saml2Token": [] + }, + "requiredResourceAccess": [ + { + "resourceAppId": "Microsoft Graph", + "resourceAccess": [ + { + "id": "User.Read", + "type": "Scope" + } + ] + } + ], + "oauth2Permissions": [ + { + "adminConsentDescription": "Allows Teams to call the app's web APIs as the current user.", + "adminConsentDisplayName": "Teams can access app's web APIs", + "id": "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}", + "isEnabled": true, + "type": "User", + "userConsentDescription": "Enable Teams to call this app's web APIs with the same rights that you have", + "userConsentDisplayName": "Teams can access app's web APIs and make requests on your behalf", + "value": "access_as_user" + } + ], + "preAuthorizedApplications": [ + { + "appId": "1fec8e78-bce4-4aaf-ab1b-5451cc387264", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "5e3ce6c0-2b1f-4285-8d4b-75ee78787346", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "d3590ed6-52b3-4102-aeff-aad2292ab01c", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "00000002-0000-0ff1-ce00-000000000000", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "bc59ab01-8403-45c6-8796-ac3ef710b3e3", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "0ec893e0-5785-4de6-99da-4ed124e5296c", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "4765445b-32c6-49b0-83e6-1d93765276ca", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + }, + { + "appId": "4345a7b9-9a63-4910-a426-35363201d503", + "permissionIds": [ + "${{AAD_APP_ACCESS_AS_USER_PERMISSION_ID}}" + ] + } + ], + "identifierUris":[ + "api://botid-${{AAD_APP_CLIENT_ID}}" + ], + "replyUrlsWithType":[ + { + "url": "https://${{BOT_DOMAIN}}/auth-end.html", + "type": "Web" + }, + { + "url": "https://token.botframework.com/.auth/web/redirect", + "type": "Web" + } + ] +} diff --git a/samples/bot-all-cards/python/app.py b/samples/bot-all-cards/python/app.py new file mode 100644 index 0000000000..07c48fb018 --- /dev/null +++ b/samples/bot-all-cards/python/app.py @@ -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 BotAllCards +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() + +# Create the Bot +BOT = BotAllCards() + +# 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 diff --git a/samples/bot-all-cards/python/appManifest/color.png b/samples/bot-all-cards/python/appManifest/color.png new file mode 100644 index 0000000000..b8cf81afbe Binary files /dev/null and b/samples/bot-all-cards/python/appManifest/color.png differ diff --git a/samples/bot-all-cards/python/appManifest/manifest.json b/samples/bot-all-cards/python/appManifest/manifest.json new file mode 100644 index 0000000000..12a71f37bd --- /dev/null +++ b/samples/bot-all-cards/python/appManifest/manifest.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.19/MicrosoftTeams.schema.json", + "manifestVersion": "1.19", + "version": "1.0.0", + "id": "${{TEAMS_APP_ID}}", + "developer": { + "name": "Microsoft", + "websiteUrl": "https://www.microsoft.com", + "privacyUrl": "https://www.microsoft.com/privacy", + "termsOfUseUrl": "https://www.microsoft.com/termsofuse" + }, + "name": { + "short": "Types Of Cards", + "full": "Types Of Cards" + }, + "description": { + "short": "Bot demo sending various card types in Teams: Adaptive, Hero, Thumbnail, etc.", + "full": "This sample showcases how to send various types of cards using a bot in Microsoft Teams." + }, + "icons": { + "outline": "outline.png", + "color": "color.png" + }, + "accentColor": "#60A18E", + "bots": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "scopes": [ + "personal" + ], + "isNotificationOnly": false + } + ], + "validDomains": [ + "${{BOT_DOMAIN}}", + "*.botframework.com" + ], + "webApplicationInfo": { + "id": "${{AAD_APP_CLIENT_ID}}", + "resource": "api://botid-${{AAD_APP_CLIENT_ID}}" + } +} \ No newline at end of file diff --git a/samples/bot-all-cards/python/appManifest/outline.png b/samples/bot-all-cards/python/appManifest/outline.png new file mode 100644 index 0000000000..2c3bf6fa65 Binary files /dev/null and b/samples/bot-all-cards/python/appManifest/outline.png differ diff --git a/samples/bot-all-cards/python/assets/sample.json b/samples/bot-all-cards/python/assets/sample.json new file mode 100644 index 0000000000..2dc8a0cc28 --- /dev/null +++ b/samples/bot-all-cards/python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-bot-all-cards-python", + "source": "officeDev", + "title": "People picker control in Adaptive Cards", + "shortDescription": " This sample demonstrates using a bot to send multiple card types in Microsoft Teams, including Adaptive, Hero, Thumbnail, and OAuth cards. It covers setup, deployment, and app installation instructions.", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/bot-all-cards/python", + "longDescription": [ + "This Microsoft Teams bot sample demonstrates sending various card types, such as Adaptive, Hero, List, and Thumbnail cards. It includes detailed steps for setup, app deployment, and using Microsoft 365 Agents Toolkit for Visual Studio to run the app. Experience this versatile bot directly within your Teams client, complete with a manifest for easy uploading." + ], + "creationDateTime": "2025-08-19", + "updateDateTime": "2025-08-19", + "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-all-cards/python/Images/TypesOfCards.gif", + "alt": "Solution UX showing different types of cards using bot." + } + ], + "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-all-cards/python/bots/__init__.py b/samples/bot-all-cards/python/bots/__init__.py new file mode 100644 index 0000000000..0db16cbe2f --- /dev/null +++ b/samples/bot-all-cards/python/bots/__init__.py @@ -0,0 +1,3 @@ +from .botAllCards import BotAllCards + +__all__ = ["BotAllCards"] \ No newline at end of file diff --git a/samples/bot-all-cards/python/bots/botAllCards.py b/samples/bot-all-cards/python/bots/botAllCards.py new file mode 100644 index 0000000000..38879d9f6a --- /dev/null +++ b/samples/bot-all-cards/python/bots/botAllCards.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from botbuilder.core.teams import TeamsActivityHandler +from botbuilder.schema import Activity +from botbuilder.schema.teams import TeamInfo, TeamsChannelAccount +from botbuilder.core import TurnContext, MessageFactory +from cards import cards +from botbuilder.schema import HeroCard, CardAction, ActionTypes, Attachment +from config import DefaultConfig +CONFIG = DefaultConfig() + +class BotAllCards(TeamsActivityHandler): + def __init__(self): + # Constructor for the TeamsBot class. Initializes the parent class (TeamsActivityHandler) + super(BotAllCards, self).__init__() + + async def on_teams_members_added( + self, + teams_members_added: list[TeamsChannelAccount], + team_info: TeamInfo, + turn_context: TurnContext, + ): + """ + Handles the event when new members are added to a team. + """ + for member in teams_members_added: + # Check if the added member is not the bot itself + if member.id != turn_context.activity.recipient.id: + await turn_context.send_activity( + " Welcome to Cards Bot!\n\n" + "This bot will introduce you to different types of cards.\n\n" + "Please select one from the options below." + ) + + # Send card options (HeroCard with buttons instead of SuggestedActions) + await self.send_card_options(turn_context) + + async def on_message_activity(self, turn_context: TurnContext): + # Normalize text input + text = (turn_context.activity.text or "").strip() + + # Create a list with valid card options + valid_cards = [ + "AdaptiveCard", "HeroCard", "ListCard", "Office365", "CollectionCard", + "SignIn", "OAuth", "ThumbnailCard" + ] + + # If text is in the list, send the corresponding card + if text in valid_cards: + attachment = None + + if text == "AdaptiveCard": + attachment = cards.adaptive_Card() + elif text == "HeroCard": + attachment = cards.hero_Card() + elif text == "Office365": + attachment = cards.o365_Connector_Card() + elif text == "ThumbnailCard": + attachment = cards.thumbnail_Card() + elif text == "SignIn": + attachment = cards.signin_Card() + elif text == "OAuth": + attachment = cards.oauth_Card(CONFIG.CONNECTION_NAME) + elif text == "ListCard": + attachment = cards.list_Card() + elif text == "CollectionCard": + attachment = cards.collection_Card() + + if attachment: + await turn_context.send_activity(Activity(attachments=[attachment])) + + await turn_context.send_activity(f"You have selected **{text}**") + + else: + # If the input was not recognized, send a friendly message + await turn_context.send_activity("Please choose one of the card types below.") + + # Always send card options again (outside the IF block) + await self.send_card_options(turn_context) + + + async def send_card_options(self, turn_context: TurnContext): + """ + Sends a HeroCard with buttons instead of SuggestedActions (Teams limit is 3 for suggested actions). + """ + card = HeroCard( + title="Select a card type", + text="Click a button below to view a card sample.", + buttons=[ + CardAction(type=ActionTypes.im_back, title="AdaptiveCard", value="AdaptiveCard"), + CardAction(type=ActionTypes.im_back, title="ListCard", value="ListCard"), + CardAction(type=ActionTypes.im_back, title="HeroCard", value="HeroCard"), + CardAction(type=ActionTypes.im_back, title="Office365", value="Office365"), + CardAction(type=ActionTypes.im_back, title="CollectionCard", value="CollectionCard"), + CardAction(type=ActionTypes.im_back, title="SignIn", value="SignIn"), + CardAction(type=ActionTypes.im_back, title="ThumbnailCard", value="ThumbnailCard"), + CardAction(type=ActionTypes.im_back, title="OAuth", value="OAuth"), + ] + ) + + # In Python, wrap HeroCard into Attachment manually + attachment = Attachment( + content_type="application/vnd.microsoft.card.hero", + content=card + ) + + reply = MessageFactory.attachment(attachment) + await turn_context.send_activity(reply) + \ No newline at end of file diff --git a/samples/bot-all-cards/python/cards/cards.py b/samples/bot-all-cards/python/cards/cards.py new file mode 100644 index 0000000000..46dcb5e35f --- /dev/null +++ b/samples/bot-all-cards/python/cards/cards.py @@ -0,0 +1,298 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from botbuilder.core import CardFactory +from botbuilder.schema import ( + Attachment, + HeroCard, + CardImage, + CardAction, + ActionTypes, + SigninCard, + OAuthCard +) +import os + + +def adaptive_Card() -> Attachment: + return CardFactory.adaptive_card( + { + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "type": "AdaptiveCard", + "version": "1.0", + "body": [ + { + "type": "Container", + "items": [ + { + "type": "TextBlock", + "text": "Publish Adaptive Card schema", + "weight": "bolder", + "size": "medium", + }, + { + "type": "ColumnSet", + "columns": [ + { + "type": "Column", + "width": "auto", + "items": [ + { + "type": "Image", + "url": "https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png", + "size": "small", + "style": "person", + } + ], + }, + { + "type": "Column", + "width": "stretch", + "items": [ + { + "type": "TextBlock", + "text": "Teams", + "weight": "bolder", + "wrap": True, + }, + { + "type": "TextBlock", + "spacing": "none", + "text": "Created {{DATE(2023-01-12T06:08:39Z, SHORT)}}", + "isSubtle": True, + "wrap": True, + }, + ], + }, + ], + }, + ], + }, + { + "type": "Container", + "items": [ + { + "type": "TextBlock", + "text": "Now that we have defined the main rules and features of the format, we need to produce a schema and publish it to GitHub. The schema will be the starting point of our reference documentation.", + "wrap": True, + }, + { + "type": "FactSet", + "facts": [ + {"title": "Board:", "value": "Adaptive Card"}, + {"title": "List:", "value": "Backlog"}, + {"title": "Assigned to:", "value": "Teams"}, + ], + }, + ], + }, + ], + } + ) + + +def collection_Card() -> Attachment: + return CardFactory.adaptive_card( + { + "type": "AdaptiveCard", + "version": "1.0", + "body": [ + { + "type": "Container", + "items": [ + { + "type": "TextBlock", + "size": "extraLarge", + "weight": "bolder", + "text": "Welcome to Employee Connect", + "height": "stretch", + }, + { + "type": "TextBlock", + "size": "medium", + "weight": "bolder", + "text": "Add events to your calendar", + "height": "stretch", + }, + { + "type": "TextBlock", + "weight": "bolder", + "text": "The bot can send \r\rnotification to remind \r\ryou about the latest \r\revents and trainings.", + "wrap": True, + "height": "stretch", + }, + { + "type": "ColumnSet", + "columns": [ + {"type": "Column", "items": [], "height": "stretch"} + ], + }, + { + "type": "ColumnSet", + "columns": [ + {"type": "Column", "items": [], "height": "stretch"} + ], + }, + ], + } + ], + "actions": [{"type": "Action.Submit", "title": "Let's get started"}], + } + ) + + +def list_Card() -> Attachment: + return Attachment( + content_type="application/vnd.microsoft.teams.card.list", + content={ + "title": "Card title", + "items": [ + { + "type": "file", + "id": "https://contoso.sharepoint.com/teams/new/Shared%20Documents/Report.xlsx", + "title": "Report", + "subtitle": "teams > new > design", + "tap": { + "type": "imBack", + "value": "editOnline https://contoso.sharepoint.com/teams/new/Shared%20Documents/Report.xlsx", + }, + }, + { + "type": "resultItem", + "icon": "https://cdn2.iconfinder.com/data/icons/social-icons-33/128/Trello-128.png", + "title": "Trello title", + "subtitle": "A Trello subtitle", + "tap": {"type": "openUrl", "value": "http://trello.com"}, + }, + {"type": "section", "title": "Manager"}, + { + "type": "person", + "id": "JohnDoe@contoso.com", + "title": "John Doe", + "subtitle": "Manager", + "tap": {"type": "imBack", "value": "whois JohnDoe@contoso.com"}, + }, + ], + "buttons": [{"type": "imBack", "title": "Select", "value": "whois"}], + }, + ) + + +def o365_Connector_Card() -> Attachment: + return Attachment( + content_type="application/vnd.microsoft.teams.card.o365connector", + content={ + "@type": "MessageCard", + "@context": "http://schema.org/extensions", + "summary": "Office 365 Connector Card", + "title": "Project Tango", + "sections": [ + { + "activityTitle": "Office 365 Connector Card", + "activitySubtitle": "On Project Tango", + "activityText": "Here are the designs", + "activityImage": "https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png", + }, + { + "title": "Details", + "facts": [ + {"name": "Labels", "value": "Designs, redlines"}, + {"name": "Due date", "value": "May 28, 2023"}, + { + "name": "Attachments", + "value": "[icon.png](https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png)", + }, + ], + }, + { + "title": "Images", + "images": [ + { + "image": "http://connectorsdemo.azurewebsites.net/images/MicrosoftSurface_024_Cafe_OH-06315_VS_R1c.jpg" + }, + { + "image": "http://connectorsdemo.azurewebsites.net/images/WIN12_Scene_01.jpg" + }, + { + "image": "http://connectorsdemo.azurewebsites.net/images/WIN12_Anthony_02.jpg" + }, + ], + }, + ], + "potentialAction": [ + { + "@type": "ViewAction", + "name": "View in Microsoft", + "target": ["https://learn.microsoft.com/"], + } + ], + }, + ) + + +def thumbnail_Card() -> Attachment: + return Attachment( + content_type="application/vnd.microsoft.card.thumbnail", + content={ + "title": "Thumbnail Card", + "subtitle": "Tale of a robot who dared to love", + "text": ( + "Bender Bending Rodríguez is a main character in the animated " + "television series Futurama. He was created by series creators " + "Matt Groening and David X. Cohen, and is voiced by John DiMaggio." + ), + "images": [ + { + "url": "https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png", + "alt": "Bender Rodríguez", + } + ], + "buttons": [ + { + "type": "openUrl", + "title": "Learn more", + "value": "https://en.wikipedia.org/wiki/Bender_(Futurama)", + } + ], + }, + ) + + +def hero_Card(): + return CardFactory.hero_card( + HeroCard( + title="BotFramework Hero Card", + images=[ + CardImage( + url="https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Seattle_monorail01_2008-02-25.jpg/1024px-Seattle_monorail01_2008-02-25.jpg" + ) + ], + buttons=[ + CardAction( + type=ActionTypes.open_url, + title="Get started", + value="https://docs.microsoft.com/en-us/azure/bot-service/", + ) + ], + ) + ) + + +def signin_Card(): + return CardFactory.signin_card( + SigninCard( + text="BotFramework SignIn Card", + buttons=[ + CardAction( + type=ActionTypes.signin, + title="Sign In", + value="https://login.microsoftonline.com", + ) + ], + ) + ) + +def oauth_Card(connection_name: str): + return CardFactory.oauth_card( + connection_name, "Sign In", "Please sign in to continue." + ) diff --git a/samples/bot-all-cards/python/config.py b/samples/bot-all-cards/python/config.py new file mode 100644 index 0000000000..a0f9d3eecc --- /dev/null +++ b/samples/bot-all-cards/python/config.py @@ -0,0 +1,17 @@ +#!/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", "") + MicrosoftAppTenantId = os.environ.get("MicrosoftAppTenantId", "") + CONNECTION_NAME = os.environ.get("ConnectionName", "") diff --git a/samples/bot-all-cards/python/env/.env.local b/samples/bot-all-cards/python/env/.env.local new file mode 100644 index 0000000000..91924dd21e --- /dev/null +++ b/samples/bot-all-cards/python/env/.env.local @@ -0,0 +1,23 @@ +# 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= +AAD_APP_ACCESS_AS_USER_PERMISSION_ID= +CONNECTION_NAME= +MICROSOFT_APP_TYPE= +MICROSOFT_APP_TENANT_ID= +RESOURCE_SUFFIX= +AZURE_SUBSCRIPTION_ID= +AZURE_RESOURCE_GROUP_NAME=-2 +APP_NAME_SUFFIX= \ No newline at end of file diff --git a/samples/bot-all-cards/python/infra/azure.bicep b/samples/bot-all-cards/python/infra/azure.bicep new file mode 100644 index 0000000000..145ce9cd4f --- /dev/null +++ b/samples/bot-all-cards/python/infra/azure.bicep @@ -0,0 +1,76 @@ +@maxLength(20) +@minLength(4) +@description('Used to generate names for all resources in this file') +param resourceBaseName string + +@maxLength(42) +param botDisplayName string + +param botServiceName string = resourceBaseName +param botServiceSku string = 'F0' +param botAadAppClientId string +param botAppDomain string + +param aadAppClientId string +@secure() +param aadAppClientSecret string +param microsoftAppType string +param microsoftAppTenantId string + +// 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: microsoftAppType + msaAppTenantId: microsoftAppType == 'SingleTenant' ? microsoftAppTenantId : '' + } + 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' + } +} + +resource botServiceConnection 'Microsoft.BotService/botServices/connections@2021-03-01' = { + parent: botService + name: 'oauthbotsetting' + location: 'global' + properties: { + serviceProviderDisplayName: 'Azure Active Directory v2' + serviceProviderId: '30dd229c-58e3-4a48-bdfd-91ec48eb906c' + scopes: 'User.Read' + parameters: [ + { + key: 'clientId' + value: aadAppClientId + } + { + key: 'clientSecret' + value: aadAppClientSecret + } + { + key: 'tenantID' + value: microsoftAppTenantId + } + { + key: 'tokenExchangeUrl' + value: 'api://botid-${aadAppClientId}' + } + ] + } +} + +output CONNECTION_NAME string = botServiceConnection.name diff --git a/samples/bot-all-cards/python/infra/azure.parameters.json b/samples/bot-all-cards/python/infra/azure.parameters.json new file mode 100644 index 0000000000..dab564237e --- /dev/null +++ b/samples/bot-all-cards/python/infra/azure.parameters.json @@ -0,0 +1,30 @@ +{ + "$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": "bot-all-cards" + }, + "aadAppClientId": { + "value": "${{AAD_APP_CLIENT_ID}}" + }, + "aadAppClientSecret": { + "value": "${{SECRET_AAD_APP_CLIENT_SECRET}}" + }, + "microsoftAppType": { + "value": "${{MICROSOFT_APP_TYPE}}" + }, + "microsoftAppTenantId": { + "value": "${{MICROSOFT_APP_TENANT_ID}}" + } + } +} \ No newline at end of file diff --git a/samples/bot-all-cards/python/m365agents.local.yml b/samples/bot-all-cards/python/m365agents.local.yml new file mode 100644 index 0000000000..55300f834a --- /dev/null +++ b/samples/bot-all-cards/python/m365agents.local.yml @@ -0,0 +1,92 @@ +# 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-all-cards-python + +provision: + - uses: aadApp/create # Creates a new Azure Active Directory (AAD) app to authenticate users if the environment variable that stores clientId is empty + with: + name: bot-all-cards-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: "AzureADMyOrg" # Authenticate users with a Microsoft work or school account in your organization's Azure AD tenant (for example, single tenant). + 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: bot-all-cards${{APP_NAME_SUFFIX}} + # Write the information of created resources into environment file for + # the specified environment variable(s). + writeToEnvironmentFile: + teamsAppId: TEAMS_APP_ID + + - uses: script + with: + run: + echo "::set-teamsfx-env MICROSOFT_APP_TYPE=SingleTenant"; + echo "::set-teamsfx-env MICROSOFT_APP_TENANT_ID=${{AAD_APP_TENANT_ID}}"; + # echo "::set-teamsfx-env MICROSOFT_APP_TYPE=MultiTenant"; + # echo "::set-teamsfx-env MICROSOFT_APP_TENANT_ID=common"; + + - 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 # Microsoft 365 Agents Toolkit will download this bicep CLI version from github for you, will use bicep CLI in PATH if you remove this config. + + - uses: aadApp/update # Apply the AAD manifest to an existing AAD app. Will use the object id in manifest file to determine which AAD app to update. + with: + manifestPath: ./aad.manifest.json # Relative path to teamsfx folder. Environment variables in manifest will be replaced before apply to AAD app + outputFilePath: ./build/aad.manifest.${{TEAMSFX_ENV}}.json + + # 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 + # Developer Portal. + # Will use the app id in manifest file to determine which Teams app to update. + - uses: teamsApp/update + with: + # Relative path to teamsfx folder. 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}} + MicrosoftAppTenantId: ${{MICROSOFT_APP_TENANT_ID}} + connectionName: ${{CONNECTION_NAME}} diff --git a/samples/bot-all-cards/python/m365agents.yml b/samples/bot-all-cards/python/m365agents.yml new file mode 100644 index 0000000000..dc2a7ce953 --- /dev/null +++ b/samples/bot-all-cards/python/m365agents.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-all-cards-python + +environmentFolderPath: ./env diff --git a/samples/bot-all-cards/python/requirements.txt b/samples/bot-all-cards/python/requirements.txt new file mode 100644 index 0000000000..d7f2ca5200 --- /dev/null +++ b/samples/bot-all-cards/python/requirements.txt @@ -0,0 +1,2 @@ +requests==2.32.3 +botbuilder-integration-aiohttp>=4.16.2 \ No newline at end of file