diff --git a/samples/app-hello-world/python/.gitignore b/samples/app-hello-world/python/.gitignore new file mode 100644 index 0000000000..e8442994dd --- /dev/null +++ b/samples/app-hello-world/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/app-hello-world/python/.vscode/extensions.json b/samples/app-hello-world/python/.vscode/extensions.json new file mode 100644 index 0000000000..bf8c33db9c --- /dev/null +++ b/samples/app-hello-world/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/app-hello-world/python/.vscode/launch.json b/samples/app-hello-world/python/.vscode/launch.json new file mode 100644 index 0000000000..6d66d8beb8 --- /dev/null +++ b/samples/app-hello-world/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/app-hello-world/python/.vscode/settings.json b/samples/app-hello-world/python/.vscode/settings.json new file mode 100644 index 0000000000..3014fd9cf0 --- /dev/null +++ b/samples/app-hello-world/python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} diff --git a/samples/app-hello-world/python/.vscode/tasks.json b/samples/app-hello-world/python/.vscode/tasks.json new file mode 100644 index 0000000000..2161094dcc --- /dev/null +++ b/samples/app-hello-world/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/app-hello-world/python/Images/1.PersonalScope_Bot.png b/samples/app-hello-world/python/Images/1.PersonalScope_Bot.png new file mode 100644 index 0000000000..e282f18042 Binary files /dev/null and b/samples/app-hello-world/python/Images/1.PersonalScope_Bot.png differ diff --git a/samples/app-hello-world/python/Images/2.PersonalScope_StaticTab.png b/samples/app-hello-world/python/Images/2.PersonalScope_StaticTab.png new file mode 100644 index 0000000000..a5c2722b4e Binary files /dev/null and b/samples/app-hello-world/python/Images/2.PersonalScope_StaticTab.png differ diff --git a/samples/app-hello-world/python/Images/3.PersonalScope_MsgExtSearchQuery.png b/samples/app-hello-world/python/Images/3.PersonalScope_MsgExtSearchQuery.png new file mode 100644 index 0000000000..d698a8a204 Binary files /dev/null and b/samples/app-hello-world/python/Images/3.PersonalScope_MsgExtSearchQuery.png differ diff --git a/samples/app-hello-world/python/Images/4.PersonalScope_MsgExtQuery2.png b/samples/app-hello-world/python/Images/4.PersonalScope_MsgExtQuery2.png new file mode 100644 index 0000000000..e07132ddf2 Binary files /dev/null and b/samples/app-hello-world/python/Images/4.PersonalScope_MsgExtQuery2.png differ diff --git a/samples/app-hello-world/python/Images/AppHelloWorldGif.gif b/samples/app-hello-world/python/Images/AppHelloWorldGif.gif new file mode 100644 index 0000000000..ea2dcb886c Binary files /dev/null and b/samples/app-hello-world/python/Images/AppHelloWorldGif.gif differ diff --git a/samples/app-hello-world/python/Images/Office_M365.png b/samples/app-hello-world/python/Images/Office_M365.png new file mode 100644 index 0000000000..5b74d68a35 Binary files /dev/null and b/samples/app-hello-world/python/Images/Office_M365.png differ diff --git a/samples/app-hello-world/python/Images/Office_M365_App.png b/samples/app-hello-world/python/Images/Office_M365_App.png new file mode 100644 index 0000000000..73e1178b2a Binary files /dev/null and b/samples/app-hello-world/python/Images/Office_M365_App.png differ diff --git a/samples/app-hello-world/python/Images/Outlook_SelectApp.png b/samples/app-hello-world/python/Images/Outlook_SelectApp.png new file mode 100644 index 0000000000..fd4df0f7bc Binary files /dev/null and b/samples/app-hello-world/python/Images/Outlook_SelectApp.png differ diff --git a/samples/app-hello-world/python/Images/Outlook_StaticTab.png b/samples/app-hello-world/python/Images/Outlook_StaticTab.png new file mode 100644 index 0000000000..85febba6fd Binary files /dev/null and b/samples/app-hello-world/python/Images/Outlook_StaticTab.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_Bot.png b/samples/app-hello-world/python/Images/TeamsScope_Bot.png new file mode 100644 index 0000000000..c73b50719a Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_Bot.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_1.png b/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_1.png new file mode 100644 index 0000000000..4df709d90b Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_1.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_2.png b/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_2.png new file mode 100644 index 0000000000..040530a364 Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_ComposeExt_2.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_ConfigTab.png b/samples/app-hello-world/python/Images/TeamsScope_ConfigTab.png new file mode 100644 index 0000000000..eb9a9447a1 Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_ConfigTab.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_FirstTab.png b/samples/app-hello-world/python/Images/TeamsScope_FirstTab.png new file mode 100644 index 0000000000..114513d258 Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_FirstTab.png differ diff --git a/samples/app-hello-world/python/Images/TeamsScope_SecondTab.png b/samples/app-hello-world/python/Images/TeamsScope_SecondTab.png new file mode 100644 index 0000000000..d6cd8bb40a Binary files /dev/null and b/samples/app-hello-world/python/Images/TeamsScope_SecondTab.png differ diff --git a/samples/app-hello-world/python/README.md b/samples/app-hello-world/python/README.md new file mode 100644 index 0000000000..6ea80d1e75 --- /dev/null +++ b/samples/app-hello-world/python/README.md @@ -0,0 +1,227 @@ +--- +page_type: sample +products: +- office-365 +languages: +- python +title: Microsoft Teams Python Hello World Sample +description: The Microsoft Teams Python "Hello World" Sample app demonstrates key features of Teams, including tabs, bots, and messaging extensions, built with Python. It’s a great starting point for developing and deploying custom Teams apps. +extensions: + contentType: samples + createdDate: 10/19/2022 10:02:21 PM +urlFragment: officedev-microsoft-teams-samples-app-hello-world-python +--- + +# Microsoft Teams hello world sample app. + +The Microsoft Teams Python "Hello World" Sample app is a comprehensive demonstration of essential Microsoft Teams features built using Python. This sample highlights the core functionalities of Teams, such as tabs, bots, and messaging extensions, making it an excellent starting point for developers interested in creating robust Teams apps. + +With this sample, users can: +- Experience a personal scope bot interaction. +- Explore static and configurable tabs for rich in-app content. +- Utilize messaging extensions for seamless content sharing within Teams. + +## Included Features +* Tabs +* Bots +* Messaging Extensions + +## Interaction with app + +![HelloWorldGif](Images/AppHelloWorldGif.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. (Sideloading 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)). + +**Microsoft Teams hello world sample app:** [Manifest](/samples/app-hello-world/csharp/demo-manifest/app-hello-world.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 +- [M365 developer account](https://docs.microsoft.com/microsoftteams/platform/concepts/build-and-test/prepare-your-o365-tenant) or access to a Teams account with the appropriate permissions to install an app. +- [Teams Toolkit for VS Code](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) or [TeamsFx CLI](https://learn.microsoft.com/microsoftteams/platform/toolkit/teamsfx-cli?pivots=version-one) + +## Run the app (Using Teams Toolkit for Visual Studio Code) + +The simplest way to run this sample in Teams is to use Teams Toolkit for Visual Studio Code. + +1. Ensure you have downloaded and installed [Visual Studio Code](https://code.visualstudio.com/docs/setup/setup-overview) +1. Install the [Teams Toolkit extension](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) and [Python Extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) +1. Select **File > Open Folder** in VS Code and choose this samples directory from the repo +1. Press **CTRL+Shift+P** to open the command box and enter **Python: Create Environment** to create and activate your desired virtual environment. Remember to select `requirements.txt` as dependencies to install when creating the virtual environment. +1. Using the extension, sign in with your Microsoft 365 account where you have permissions to upload custom apps +1. Select **Debug > Start Debugging** or **F5** to run the app in a Teams web client. +1. In the browser that launches, select the **Add** button to install the app to Teams. + +> If you do not have permission to upload custom apps (sideloading), Teams Toolkit will recommend creating and using a Microsoft 365 Developer Program account - a free program to get your own dev environment sandbox that includes Teams. + +## Run the app (Manually Uploading to Teams) + +> 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\app-hello-world` + +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) Run your app with `python app.py` + +### 4. Setup Manifest for Teams + + - **This step is specific to Teams.** + + - **Edit** the `manifest.json` contained in the `app-hello-world/python/appManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `<>` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`) + - **Edit** the `manifest.json` for `configurationUrl` inside `configurableTabs` and `validDomains`. Replace `{{domain-name}}` with base Url domain. E.g. if you are using ngrok it would be `https://1234.ngrok-free.app` then your domain-name will be `1234.ngrok-free.app` and if you are using dev tunnels then your domain will be like: `12345.devtunnels.ms`. + + **Note:** If you want to test your app across multi hub like: Outlook/Office.com, please update the `manifest.json` in the `app-hello-world/python/appManifest_Hub` folder with the required values. + + - **Zip** up the contents of the `app-hello-world/python/appManifest` folder to create a `manifest.zip`(Make sure that zip file does not contains any subfolder otherwise you will get error while uploading your .zip package) + - **Upload** the `manifest.zip` to Teams (In Teams Apps/Manage your apps click "Upload an app". Browse to and Open the .zip file. At the next dialog, click the Add button.) + - Add the app to personal/team/groupChat scope (Supported scopes) + +This app has a default landing capability that determines whether the opening scope is set to the Bot or a static tab. Without configuring this, Microsoft Teams defaults to landing on the bot in desktop clients and tab in mobile clients. + +To set the **Bot as the default landing capability**, configure the 'staticTabs' section in the manifest as follows: +```bash +"staticTabs": [ + { + "entityId": "conversations", + "scopes": [ + "personal" + ] + }, + { + "entityId": "com.contoso.helloworld.hellotab", + "name": "Hello Tab", + "contentUrl": "https://${{BOT_DOMAIN}}/hello", + "scopes": [ + "personal" + ] + } +], +``` + +To set the **Tab as the default landing capability**, configure the 'staticTabs' section in the manifest as follows: +```bash +"staticTabs": [ + { + "entityId": "com.contoso.helloworld.hellotab", + "name": "Hello Tab", + "contentUrl": "https://${{BOT_DOMAIN}}/hello", + "scopes": [ + "personal" + ] + }, + { + "entityId": "conversations", + "scopes": [ + "personal" + ] + } +], +``` + +## Running the sample + +**Install App:** + +![Personal Scope Bot](Images/1.PersonalScope_Bot.png) + +**Hello World Tab:** + +![HelloWorld](Images/2.PersonalScope_StaticTab.png) + +**ME:** + +![Hello World App](Images/3.PersonalScope_MsgExtSearchQuery.png) + +![Hello World App](Images/4.PersonalScope_MsgExtQuery2.png) + +**Teams Scope** + +![Hello World App](Images/TeamsScope_Bot.png) + +![Hello World App](Images/TeamsScope_ComposeExt_1.png) + +![Hello World App](Images/TeamsScope_ComposeExt_2.png) + +![Hello World App](Images/TeamsScope_ConfigTab.png) + +![Hello World App](Images/TeamsScope_FirstTab.png) + +![Hello World App](Images/TeamsScope_SecondTab.png) + +## Outlook on the web + +- To view your app in Outlook on the web. + +- Go to [Outlook on the web](https://outlook.office.com/mail/)and sign in using your dev tenant account. + +**On the side bar, select More Apps. Your sideloaded app title appears among your installed apps** + +![InstallOutlook](Images/Outlook_SelectApp.png) + +**Select your app icon to launch and preview your app running in Outlook on the web** + +![AppOutlook](Images/Outlook_StaticTab.png) + +**Note:** Similarly, you can test your application in the Outlook desktop app as well. + +## Office on the web + +- To preview your app running in Office on the web. + +- Log into office.com with test tenant credentials + +**Select the Apps icon on the side bar. Your sideloaded app title appears among your installed apps** + +![InstallOffice](Images/Office_M365.png) + +**Select your app icon to launch your app in Office on the web** + +![AppOffice](Images/Office_M365_App.png) + +**Note:** Similarly, you can test your application in the Office 365 desktop app as well. + +## Deploy the bot to Azure + +To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions. + +## Further reading + +- [Bot Framework Documentation](https://docs.botframework.com) +- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0) +- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0) +- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0) +- [Extend Teams apps across Microsoft 365](https://learn.microsoft.com/en-us/microsoftteams/platform/m365-apps/overview) + + \ No newline at end of file diff --git a/samples/app-hello-world/python/app.py b/samples/app-hello-world/python/app.py new file mode 100644 index 0000000000..4e1d8114f1 --- /dev/null +++ b/samples/app-hello-world/python/app.py @@ -0,0 +1,121 @@ +# 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 HelloWorldBot +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. + +# aiohttp route for home page +async def home(request): + return web.FileResponse('src/views/hello.html') + +# aiohttp route for /hello +async def hello(request): + return web.FileResponse('src/views/hello.html') + +# aiohttp route for /first +async def first(request): + return web.FileResponse('src/views/first.html') + +# aiohttp route for /second +async def second(request): + return web.FileResponse('src/views/second.html') + +# aiohttp route for /configure +async def configure(request): + return web.FileResponse('src/views/configure.html') + +# Assign APP_ID from SETTINGS.app_id if it exists; otherwise, generate a new unique UUID. +APP_ID = SETTINGS.app_id if SETTINGS.app_id else uuid.uuid4() + +# Create the Bot +BOT = HelloWorldBot(CONFIG.APP_ID, CONFIG.APP_PASSWORD) + +# 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]) + +# Register routes +APP.router.add_get("/", home) +APP.router.add_get("/hello", hello) +APP.router.add_get("/first", first) +APP.router.add_get("/second", second) +APP.router.add_get("/configure", configure) +APP.router.add_get("/msteams-16", msteams) +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/app-hello-world/python/appManifest/color.png b/samples/app-hello-world/python/appManifest/color.png new file mode 100644 index 0000000000..b8cf81afbe Binary files /dev/null and b/samples/app-hello-world/python/appManifest/color.png differ diff --git a/samples/app-hello-world/python/appManifest/manifest.json b/samples/app-hello-world/python/appManifest/manifest.json new file mode 100644 index 0000000000..d213e04f72 --- /dev/null +++ b/samples/app-hello-world/python/appManifest/manifest.json @@ -0,0 +1,85 @@ +{ + "$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": "Contoso", + "websiteUrl": "https://www.microsoft.com", + "privacyUrl": "https://www.microsoft.com/privacy", + "termsOfUseUrl": "https://www.microsoft.com/termsofuse" + }, + "name": { + "short": "Hello World Python", + "full": "Hello World App for Microsoft Teams" + }, + "description": { + "short": "Microsoft Teams Hello World sample showcasing tabs, bots, and messaging Ext.", + "full": "The Microsoft Teams Python Hello World Sample app demonstrates key features of Teams, including tabs, bots, and messaging extensions, built with Python. It’s a great starting point for developing and deploying custom Teams apps." + }, + "icons": { + "outline": "outline.png", + "color": "color.png" + }, + "accentColor": "#60A18E", + "staticTabs": [ + { + "entityId": "conversations", + "scopes": [ + "personal" + ] + }, + { + "entityId": "com.contoso.helloworld.hellotab", + "name": "Hello Tab", + "contentUrl": "https://${{BOT_DOMAIN}}/hello", + "scopes": [ + "personal" + ] + } + ], + "configurableTabs": [ + { + "configurationUrl": "https://${{BOT_DOMAIN}}/configure", + "canUpdateConfiguration": true, + "scopes": [ + "team" + ] + } + ], + "bots": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "needsChannelSelector": false, + "isNotificationOnly": false, + "scopes": [ + "team", + "personal" + ] + } + ], + "composeExtensions": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "commands": [ + { + "id": "getRandomText", + "description": "Gets some random text and images that you can insert in messages for fun.", + "title": "Get some random text for fun", + "initialRun": true, + "parameters": [ + { + "name": "cardTitle", + "description": "Card title to use", + "title": "Card title" + } + ] + } + ] + } + ], + "permissions": [], + "validDomains": [ + "${{BOT_DOMAIN}}" + ] +} \ No newline at end of file diff --git a/samples/app-hello-world/python/appManifest/outline.png b/samples/app-hello-world/python/appManifest/outline.png new file mode 100644 index 0000000000..2c3bf6fa65 Binary files /dev/null and b/samples/app-hello-world/python/appManifest/outline.png differ diff --git a/samples/app-hello-world/python/assets/sample.json b/samples/app-hello-world/python/assets/sample.json new file mode 100644 index 0000000000..fe9b33e32b --- /dev/null +++ b/samples/app-hello-world/python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-app-hello-world-python", + "source": "officeDev", + "title": "Microsoft Teams Python Hello World Sample", + "shortDescription": "The Microsoft Teams Python Hello World Sample app demonstrates key features of Teams, including tabs, bots, and messaging extensions, built with Python. It’s a great starting point for developing and deploying custom Teams apps.", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/app-hello-world/python", + "longDescription": [ + "The Microsoft Teams Python Hello World Sample app demonstrates key features of Teams, including tabs, bots, and messaging extensions, built with Python. It’s a great starting point for developing and deploying custom Teams apps." + ], + "creationDateTime": "2024-12-12", + "updateDateTime": "2024-12-12", + "products": [ + "Teams" + ], + "metadata": [ + { + "key": "TEAMS-SAMPLE-SOURCE", + "value": "OfficeDev" + }, + { + "key": "TEAMS-SERVER-LANGUAGE", + "value": "python" + }, + { + "key": "TEAMS-SERVER-PLATFORM", + "value": "express" + }, + { + "key": "TEAMS-FEATURES", + "value": "tab,bot,msgext" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/app-hello-world/python/Images/AppHelloWorldGif.gif", + "alt": "Solution UX showing microsoft teams python helloworld sample" + } + ], + "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/app-hello-world/python/bots/__init__.py b/samples/app-hello-world/python/bots/__init__.py new file mode 100644 index 0000000000..7721f3c1e3 --- /dev/null +++ b/samples/app-hello-world/python/bots/__init__.py @@ -0,0 +1,3 @@ +from .bot import HelloWorldBot + +__all__ = ["HelloWorldBot"] \ No newline at end of file diff --git a/samples/app-hello-world/python/bots/bot.py b/samples/app-hello-world/python/bots/bot.py new file mode 100644 index 0000000000..c6df031d0c --- /dev/null +++ b/samples/app-hello-world/python/bots/bot.py @@ -0,0 +1,129 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from botbuilder.core import TurnContext, CardFactory +from botbuilder.core.teams import TeamsActivityHandler +from botbuilder.schema.teams import TeamInfo, TeamsChannelAccount +from faker import Faker +from botbuilder.schema.teams import ( + MessagingExtensionResponse, + MessagingExtensionAttachment, + MessagingExtensionResult, +) +from botbuilder.schema import ( + ThumbnailCard, + CardImage, + CardAction, +) + +class HelloWorldBot(TeamsActivityHandler): + def __init__(self, app_id: str, app_password: str): + self._app_id = app_id + self._app_password = app_password + + async def on_teams_members_added( # pylint: disable=unused-argument + self, + teams_members_added: [TeamsChannelAccount], + team_info: TeamInfo, + turn_context: TurnContext, + ): + for member in teams_members_added: + if member.id != turn_context.activity.recipient.id: + await turn_context.send_activity( + f"Welcome to the App hello world sample { member.given_name } { member.surname }. " + ) + + async def on_message_activity(self, turn_context: TurnContext): + # Remove recipient mention from the activity + TurnContext.remove_recipient_mention(turn_context.activity) + + # Check if the activity contains a text message + text = turn_context.activity.text.strip() if turn_context.activity.text else None + + if text: + # Send a response if text is present + await turn_context.send_activity(f"You said: {text}") + else: + # Return None if no text message is provided + return None + + async def on_teams_messaging_extension_query(self, context, query): + faker = Faker() + + title = query.command_id + random_image_url = "https://loremflickr.com/200/200" + + if query.command_id == "getRandomText": + attachments = [] + + # Generate 5 results with fake text and fake images + for i in range(5): + text = faker.paragraph() + images = [f"{random_image_url}?random={i}"] + + # Create a thumbnail card using ThumbnailCard + thumbnail_card = ThumbnailCard( + title=title, + text=text, + images=[CardImage(url=image) for image in images], + ) + + # Use CardFactory to create the card attachment + card_attachment = CardFactory.thumbnail_card(thumbnail_card) + + # Create a CardAction for the 'tap' attribute + tap_action = CardAction( + type="invoke", + value={"title": title, "text": text, "images": images}, + ) + + # Create a preview card and add the tap action + preview_card = ThumbnailCard( + title=title, + text=text, + images=[CardImage(url=image) for image in images], + ) + preview_attachment = CardFactory.thumbnail_card(preview_card) + preview_attachment.content.tap = tap_action + + # Combine the thumbnail card and the preview + attachment = MessagingExtensionAttachment( + content=thumbnail_card, + content_type=CardFactory.content_types.thumbnail_card, + preview=preview_attachment, + ) + attachments.append(attachment) + + return MessagingExtensionResponse( + compose_extension=MessagingExtensionResult( + type="result", + attachment_layout="list", + attachments=attachments, + ) + ) + + + async def on_teams_messaging_extension_select_item( + self, turn_context: TurnContext, query + ) -> MessagingExtensionResponse: + title = query.get("title") + text = query.get("text") + images = query.get("images", []) + + thumbnail_card = ThumbnailCard( + title=title, + text=text, + images=[CardImage(url=image) for image in images], + ) + + # Create a MessagingExtensionAttachment + attachment = MessagingExtensionAttachment( + content_type=CardFactory.content_types.thumbnail_card, + content=thumbnail_card, + ) + + return MessagingExtensionResponse( + compose_extension=MessagingExtensionResult( + type="result", attachment_layout="list", attachments=[attachment] + ) + ) diff --git a/samples/app-hello-world/python/config.py b/samples/app-hello-world/python/config.py new file mode 100644 index 0000000000..c682ef8547 --- /dev/null +++ b/samples/app-hello-world/python/config.py @@ -0,0 +1,15 @@ +#!/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", "<>") diff --git a/samples/app-hello-world/python/env/.env.local b/samples/app-hello-world/python/env/.env.local new file mode 100644 index 0000000000..22987ef6bb --- /dev/null +++ b/samples/app-hello-world/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= \ No newline at end of file diff --git a/samples/app-hello-world/python/infra/azure.bicep b/samples/app-hello-world/python/infra/azure.bicep new file mode 100644 index 0000000000..8734cb547b --- /dev/null +++ b/samples/app-hello-world/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/app-hello-world/python/infra/azure.parameters.json b/samples/app-hello-world/python/infra/azure.parameters.json new file mode 100644 index 0000000000..0ccfdab3f2 --- /dev/null +++ b/samples/app-hello-world/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": "AppHelloWorld" + } + } + } \ No newline at end of file diff --git a/samples/app-hello-world/python/requirements.txt b/samples/app-hello-world/python/requirements.txt new file mode 100644 index 0000000000..c6424216e6 --- /dev/null +++ b/samples/app-hello-world/python/requirements.txt @@ -0,0 +1,2 @@ +requests==2.31.0 +botbuilder-integration-aiohttp>=4.14.5 diff --git a/samples/app-hello-world/python/src/views/configure.html b/samples/app-hello-world/python/src/views/configure.html new file mode 100644 index 0000000000..d1350c521a --- /dev/null +++ b/samples/app-hello-world/python/src/views/configure.html @@ -0,0 +1,104 @@ + + + + + + Microsoft Teams Hello World Sample App + + + + + +
+
+
+ Configure your app here +

+

+ + +
+

+
+

+ Selected Tab: (none) +

+
+
+ + + + + \ No newline at end of file diff --git a/samples/app-hello-world/python/src/views/first.html b/samples/app-hello-world/python/src/views/first.html new file mode 100644 index 0000000000..bbbe514ad1 --- /dev/null +++ b/samples/app-hello-world/python/src/views/first.html @@ -0,0 +1,24 @@ + + + + + + + Microsoft Teams Hello World Sample App + + + + +
+
+
+ This is our first tab +

+ Welcome to Microsoft Teams Hello World sample app (Python) +

+
+
+
+ + + diff --git a/samples/app-hello-world/python/src/views/hello.html b/samples/app-hello-world/python/src/views/hello.html new file mode 100644 index 0000000000..92f5dbf291 --- /dev/null +++ b/samples/app-hello-world/python/src/views/hello.html @@ -0,0 +1,21 @@ + + + + + Microsoft Teams Hello World Sample App + + + +
+
+
+ Hello, World +

+ Welcome to Microsoft Teams Hello World sample app (python) +

+
+
+
+ + + diff --git a/samples/app-hello-world/python/src/views/second.html b/samples/app-hello-world/python/src/views/second.html new file mode 100644 index 0000000000..e6bc86dbda --- /dev/null +++ b/samples/app-hello-world/python/src/views/second.html @@ -0,0 +1,24 @@ + + + + + + Microsoft Teams Hello World Sample App + + + + +
+
+
+ This is our Second tab +

+ Welcome to Microsoft Teams Hello World sample app (Python) +

+
+
+
+ + + \ No newline at end of file diff --git a/samples/app-hello-world/python/teamsapp.local.yml b/samples/app-hello-world/python/teamsapp.local.yml new file mode 100644 index 0000000000..d1ac849743 --- /dev/null +++ b/samples/app-hello-world/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:app-hello-world-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: app-hello-world-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: app-hello-world${{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/app-hello-world/python/teamsapp.yml b/samples/app-hello-world/python/teamsapp.yml new file mode 100644 index 0000000000..dbd38d710b --- /dev/null +++ b/samples/app-hello-world/python/teamsapp.yml @@ -0,0 +1,8 @@ +# 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:app-hello-world-python +environmentFolderPath: ./env