diff --git a/samples/bot-message-reaction/python/.gitignore b/samples/bot-message-reaction/python/.gitignore new file mode 100644 index 0000000000..e8442994dd --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction/python/.vscode/extensions.json b/samples/bot-message-reaction/python/.vscode/extensions.json new file mode 100644 index 0000000000..bf8c33db9c --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction/python/.vscode/launch.json b/samples/bot-message-reaction/python/.vscode/launch.json new file mode 100644 index 0000000000..6d66d8beb8 --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction/python/.vscode/settings.json b/samples/bot-message-reaction/python/.vscode/settings.json new file mode 100644 index 0000000000..3014fd9cf0 --- /dev/null +++ b/samples/bot-message-reaction/python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} diff --git a/samples/bot-message-reaction/python/.vscode/tasks.json b/samples/bot-message-reaction/python/.vscode/tasks.json new file mode 100644 index 0000000000..2161094dcc --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction/python/Images/1.InstallApp.png b/samples/bot-message-reaction/python/Images/1.InstallApp.png new file mode 100644 index 0000000000..e383f399ca Binary files /dev/null and b/samples/bot-message-reaction/python/Images/1.InstallApp.png differ diff --git a/samples/bot-message-reaction/python/Images/10.Teams_EchoBot.png b/samples/bot-message-reaction/python/Images/10.Teams_EchoBot.png new file mode 100644 index 0000000000..6e58d6fc1d Binary files /dev/null and b/samples/bot-message-reaction/python/Images/10.Teams_EchoBot.png differ diff --git a/samples/bot-message-reaction/python/Images/11.Teams_AddedHeartToMsg.png b/samples/bot-message-reaction/python/Images/11.Teams_AddedHeartToMsg.png new file mode 100644 index 0000000000..ea913cf26c Binary files /dev/null and b/samples/bot-message-reaction/python/Images/11.Teams_AddedHeartToMsg.png differ diff --git a/samples/bot-message-reaction/python/Images/2.PersonalScope_Echo_Bot.png b/samples/bot-message-reaction/python/Images/2.PersonalScope_Echo_Bot.png new file mode 100644 index 0000000000..fc4c185e97 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/2.PersonalScope_Echo_Bot.png differ diff --git a/samples/bot-message-reaction/python/Images/3.PersonalScope_AddedLikeToHelloMsg.png b/samples/bot-message-reaction/python/Images/3.PersonalScope_AddedLikeToHelloMsg.png new file mode 100644 index 0000000000..1bed7c7e1e Binary files /dev/null and b/samples/bot-message-reaction/python/Images/3.PersonalScope_AddedLikeToHelloMsg.png differ diff --git a/samples/bot-message-reaction/python/Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png b/samples/bot-message-reaction/python/Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png new file mode 100644 index 0000000000..ff0cbb9f72 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png differ diff --git a/samples/bot-message-reaction/python/Images/5.GroupChat-EchoBot.png b/samples/bot-message-reaction/python/Images/5.GroupChat-EchoBot.png new file mode 100644 index 0000000000..5d7d321d48 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/5.GroupChat-EchoBot.png differ diff --git a/samples/bot-message-reaction/python/Images/6.GroupChat_LikeReaction.png b/samples/bot-message-reaction/python/Images/6.GroupChat_LikeReaction.png new file mode 100644 index 0000000000..76bfbb062e Binary files /dev/null and b/samples/bot-message-reaction/python/Images/6.GroupChat_LikeReaction.png differ diff --git a/samples/bot-message-reaction/python/Images/7.GroupChat_Like_Angry_Reaction.png b/samples/bot-message-reaction/python/Images/7.GroupChat_Like_Angry_Reaction.png new file mode 100644 index 0000000000..83941ae3cf Binary files /dev/null and b/samples/bot-message-reaction/python/Images/7.GroupChat_Like_Angry_Reaction.png differ diff --git a/samples/bot-message-reaction/python/Images/8.Remove_Reaction_Notification.png b/samples/bot-message-reaction/python/Images/8.Remove_Reaction_Notification.png new file mode 100644 index 0000000000..e4bbb6d625 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/8.Remove_Reaction_Notification.png differ diff --git a/samples/bot-message-reaction/python/Images/9.Install_To_Teams.png b/samples/bot-message-reaction/python/Images/9.Install_To_Teams.png new file mode 100644 index 0000000000..24ec673651 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/9.Install_To_Teams.png differ diff --git a/samples/bot-message-reaction/python/Images/MessageReactions.gif b/samples/bot-message-reaction/python/Images/MessageReactions.gif new file mode 100644 index 0000000000..41a6e13f50 Binary files /dev/null and b/samples/bot-message-reaction/python/Images/MessageReactions.gif differ diff --git a/samples/bot-message-reaction/python/README.md b/samples/bot-message-reaction/python/README.md new file mode 100644 index 0000000000..beec867348 --- /dev/null +++ b/samples/bot-message-reaction/python/README.md @@ -0,0 +1,145 @@ +--- +page_type: sample +description: This sample app demonstrates how to use message reactions in Microsoft Teams with a bot built on the Bot Framework. +products: +- office-teams +- office +- office-365 +languages: +- Python +extensions: + contentType: samples + createdDate: "12-12-2024 17:00:25" +urlFragment: officedev-microsoft-teams-samples-bot-message-reaction-Python +--- + +# Teams Message Reactions Bot Python Sample + +This sample app demonstrates the implementation of message reactions in Microsoft Teams using the Bot Framework. The bot responds dynamically to reactions, supporting personal, group, and team scopes. + +## Included Features +* Bots +* Message Reactions + +## Interaction with bot + ![Message Reaction](Images/MessageReactions.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)). + +**Teams Message Reactions Bot:** [Manifest](/samples/bot-message-reaction/csharp/demo-manifest/bot-message-reaction.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 +- [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. + +## 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 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-message-reaction/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` + +## Running the sample + +Message the bot and it will respond with an 'Echo: [your message]'. Add a message reaction to the bots response, and the bot will reply accordingly. + +- **App Installation:** +![App Installation ](Images/1.InstallApp.png) + +- **Personal Scope Interactions:** +![personalScope-AddApp ](Images/2.PersonalScope_Echo_Bot.png) + +![personalScope-AddApp ](Images/3.PersonalScope_AddedLikeToHelloMsg.png) + +![personalScope-Interaction ](Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png) + +- **Group Chat Scope Interactions:** +![groupChat-Interaction ](Images/5.GroupChat-EchoBot.png) + +![groupChat-Interaction ](Images/6.GroupChat_LikeReaction.png) + +![groupChat-Interaction ](Images/7.GroupChat_Like_Angry_Reaction.png) + +![groupChat-Interaction ](Images/8.Remove_Reaction_Notification.png) + +- **Team Scope Interactions:** +![Team-Interaction ](Images/9.Install_To_Teams.png) + +![Team-Interaction ](Images/10.Teams_EchoBot.png) + +![Team-Interaction ](Images/11.Teams_AddedHeartToMsg.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 + +- [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) +- [Teams Message Reaction Events](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/subscribe-to-conversation-events?tabs=dotnet#message-reaction-events) + + + \ No newline at end of file diff --git a/samples/bot-message-reaction/python/activity_log.py b/samples/bot-message-reaction/python/activity_log.py new file mode 100644 index 0000000000..9fe4e6b9fe --- /dev/null +++ b/samples/bot-message-reaction/python/activity_log.py @@ -0,0 +1,37 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +class ActivityLog: + # Constructor to initialize the ActivityLog class with a storage object. + def __init__(self, storage): + self._storage = storage # The storage object is used for storing and retrieving activities. + + # Asynchronous method to append an activity to the log. + async def append(self, activity_id, activity): + # Check if activity_id is provided; raise an error if not. + if activity_id is None: + raise TypeError('activity_id is required for ActivityLog.append') + + # Check if activity is provided; raise an error if not. + if activity is None: + raise TypeError('activity is required for ActivityLog.append') + + # Create an object to store the activity with the activity_id as the key. + obj = {activity_id: {"activity": activity}} + + # Use the storage's write method to save the activity. + await self._storage.write(obj) + + # Asynchronous method to find and retrieve an activity from the log by its ID. + async def find(self, activity_id): + # Check if activity_id is provided; raise an error if not. + if activity_id is None: + raise TypeError('activity_id is required for ActivityLog.find') + + # Use the storage's read method to fetch the activity by its ID. + # The read method is expected to return a dictionary where keys are IDs and values are the stored objects. + items = await self._storage.read([activity_id]) + + # Retrieve the activity from the fetched data if it exists, otherwise return None. + return items.get(activity_id, {}).get("activity") if items else None + diff --git a/samples/bot-message-reaction/python/app.py b/samples/bot-message-reaction/python/app.py new file mode 100644 index 0000000000..6a26656db6 --- /dev/null +++ b/samples/bot-message-reaction/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, + MemoryStorage +) +from botbuilder.core.integration import aiohttp_error_middleware +from botbuilder.schema import Activity, ActivityTypes +from bots import MessageReactionBot +from config import DefaultConfig +from activity_log import ActivityLog + +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 storage and Activity Log +memory_storage = MemoryStorage() +activity_log = ActivityLog(memory_storage) # Initialize your activity log +# Create the Bot +BOT = MessageReactionBot(CONFIG.APP_ID, CONFIG.APP_PASSWORD,activity_log) + +# 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-message-reaction/python/appManifest/color.png b/samples/bot-message-reaction/python/appManifest/color.png new file mode 100644 index 0000000000..b8cf81afbe Binary files /dev/null and b/samples/bot-message-reaction/python/appManifest/color.png differ diff --git a/samples/bot-message-reaction/python/appManifest/manifest.json b/samples/bot-message-reaction/python/appManifest/manifest.json new file mode 100644 index 0000000000..53a4f42578 --- /dev/null +++ b/samples/bot-message-reaction/python/appManifest/manifest.json @@ -0,0 +1,47 @@ +{ + "$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": "MessageReactionBot", + "websiteUrl": "https://www.microsoft.com", + "privacyUrl": "https://www.teams.com/privacy", + "termsOfUseUrl": "https://www.teams.com/termsofuser" + }, + "icons": { + "color": "color.png", + "outline": "outline.png" + }, + "name": { + "short": "BotMessageReaction Python", + "full": "Bot Message Reaction In Python" + }, + "description": { + "short": "Sample app demonstrating bot reactions to Teams messages using Bot Framework.", + "full": "This sample app demonstrates how to use message reactions in Microsoft Teams with a bot built on the Bot Framework." + }, + "accentColor": "#FFFFFF", + "bots": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "scopes": [ + "groupChat", + "team", + "personal" + ], + "isNotificationOnly": false, + "supportsCalling": false, + "supportsVideo": false, + "supportsFiles": false + } + ], + "permissions": [ + "identity", + "messageTeamMembers" + ], + "validDomains": [ + "*.ngrok-free.app", + "${{BOT_DOMAIN}}" + ] +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/appManifest/outline.png b/samples/bot-message-reaction/python/appManifest/outline.png new file mode 100644 index 0000000000..2c3bf6fa65 Binary files /dev/null and b/samples/bot-message-reaction/python/appManifest/outline.png differ diff --git a/samples/bot-message-reaction/python/assets/sample.json b/samples/bot-message-reaction/python/assets/sample.json new file mode 100644 index 0000000000..96aab913d6 --- /dev/null +++ b/samples/bot-message-reaction/python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-bot-message-reaction-python", + "source": "officeDev", + "title": "Message Reactions Bot", + "shortDescription": "This sample app demonstrates how to use message reactions in Microsoft Teams with a bot built on the Bot Framework.", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/bot-message-reaction/python", + "longDescription": [ + "This sample bot, built on the Bot Framework, responds to message reactions in Microsoft Teams. It supports multiple scopes, including personal, group, and team interactions." + ], + "creationDateTime": "2024-12-13", + "updateDateTime": "2024-12-13", + "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": "bot" + } + ], + "thumbnails": [ + { + "type": "Image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/bot-message-reaction/python/Images/MessageReactions.gif", + "alt": "Solution UX showing message reactions" + } + ], + "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-message-reaction/python/bots/__init__.py b/samples/bot-message-reaction/python/bots/__init__.py new file mode 100644 index 0000000000..1c5675c15b --- /dev/null +++ b/samples/bot-message-reaction/python/bots/__init__.py @@ -0,0 +1,3 @@ +from .messageReactionBot import MessageReactionBot + +__all__ = ["MessageReactionBot"] \ No newline at end of file diff --git a/samples/bot-message-reaction/python/bots/messageReactionBot.py b/samples/bot-message-reaction/python/bots/messageReactionBot.py new file mode 100644 index 0000000000..9ba84350d1 --- /dev/null +++ b/samples/bot-message-reaction/python/bots/messageReactionBot.py @@ -0,0 +1,89 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from botbuilder.core import ActivityHandler, MessageFactory,TurnContext + +# This class represents a bot that handles message activities and reactions in Microsoft Teams. +class MessageReactionBot(ActivityHandler): + def __init__(self, app_id, app_password, activity_log): + """ + Initialize the bot with app credentials and an activity log for storing activity data. + :param app_id: The Microsoft app ID for the bot. + :param app_password: The Microsoft app password for the bot. + :param activity_log: An object to manage logging of activity IDs and their associated data. + """ + super().__init__() + self.app_id = app_id + self.app_password = app_password + self._log = activity_log # Reference to an activity log instance for storing and retrieving activities. + + async def on_message_activity(self, turn_context:TurnContext, next_handler=None): + # Remove recipient mention from the activity + TurnContext.remove_recipient_mention(turn_context.activity) + text = turn_context.activity.text + + """ + Handle incoming message activities. + :param turn_context: Provides information about the current turn of the conversation. + :param next_handler: Optional handler to call after the current method. + """ + # Respond to the user with an echo of their message and log the activity ID. + await self.send_message_and_log_activity_id(turn_context, f"echo: {text}") + + async def on_reactions_added(self, reactions_added, turn_context): + """ + Handle reactions added to messages. + :param reactions_added: A list of reactions that were added. + :param turn_context: Provides information about the current turn of the conversation. + """ + for reaction in reactions_added: + # Look up the activity in the log using the replyToId (ID of the message being reacted to). + activity = await self._log.find(turn_context.activity.reply_to_id) + + if not activity: + # If the activity was not found, notify the user and log the event. + await self.send_message_and_log_activity_id( + turn_context, + f"Activity {turn_context.activity.reply_to_id} not found in the log." + ) + else: + # If the activity is found, acknowledge the reaction and include the activity's text. + await self.send_message_and_log_activity_id( + turn_context, + f" added '{reaction.type}' regarding '{activity.text}'" + ) + + async def on_reactions_removed(self, reactions_removed, turn_context): + """ + Handle reactions removed from messages. + :param reactions_removed: A list of reactions that were removed. + :param turn_context: Provides information about the current turn of the conversation. + """ + for reaction in reactions_removed: + # Look up the activity in the log using the replyToId. + activity = await self._log.find(turn_context.activity.reply_to_id) + if not activity: + # If the activity was not found, notify the user. + await self.send_message_and_log_activity_id( + turn_context, + f"Activity {turn_context.activity.reply_to_id} not found in the log." + ) + else: + # If the activity is found, acknowledge the removal of the reaction. + await self.send_message_and_log_activity_id( + turn_context, + f"You removed '{reaction.type}' regarding '{activity.text}'" + ) + + async def send_message_and_log_activity_id(self, turn_context, text): + """ + Send a message to the user and log the activity ID. + :param turn_context: Provides information about the current turn of the conversation. + :param text: The message text to send to the user. + """ + # Create a text message activity. + reply_activity = MessageFactory.text(text) + # Send the activity to the user and capture the response containing the activity ID. + resource_response = await turn_context.send_activity(reply_activity) + # Log the activity ID and its associated text in the activity log. + await self._log.append(resource_response.id, reply_activity) diff --git a/samples/bot-message-reaction/python/config.py b/samples/bot-message-reaction/python/config.py new file mode 100644 index 0000000000..c682ef8547 --- /dev/null +++ b/samples/bot-message-reaction/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/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json new file mode 100644 index 0000000000..cc1800c0db --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "azureBotId": { + "value": "" + }, + "azureBotSku": { + "value": "S1" + }, + "azureBotRegion": { + "value": "global" + }, + "botEndpoint": { + "value": "" + }, + "appId": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json new file mode 100644 index 0000000000..54a7d62890 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appServiceName": { + "value": "" + }, + "existingAppServicePlanName": { + "value": "" + }, + "existingAppServicePlanLocation": { + "value": "" + }, + "newAppServicePlanName": { + "value": "" + }, + "newAppServicePlanLocation": { + "value": "West US" + }, + "newAppServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/readme.md b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/readme.md new file mode 100644 index 0000000000..c86cbf9db7 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/readme.md @@ -0,0 +1,26 @@ +# Usage +BotApp must be deployed prior to AzureBot. + +### Command line: +`az login`
+`az deployment group create --resource-group --template-file --parameters @` + +## Parameters for template-BotApp-with-rg.json: + +- **appServiceName**: (required) The Name of the Bot App Service. +- (Pick an existing App Service Plan or create a new App Service Plan.) + - **existingAppServicePlanName**: The name of the App Service Plan. + - **existingAppServicePlanLocation**: The location of the App Service Plan. + - **newAppServicePlanName**: The name of the App Service Plan. + - **newAppServicePlanLocation**: The location of the App Service Plan. + - **newAppServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values. +- **appId**: (required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings. +- **appSecret**: (required) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. + +## Parameters for template-AzureBot-with-rg.json: + +- **azureBotId**: (required) The globally unique and immutable bot ID. +- **azureBotSku**: The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default). +- **azureBotRegion**: Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope. +- **botEndpoint**: Use to handle client messages, Such as `https://.azurewebsites.net/api/messages`. +- **appId**: (required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings. \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json new file mode 100644 index 0000000000..60c9c1bb6c --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json @@ -0,0 +1,65 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "azureBotId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID." + } + }, + "azureBotSku": { + "type": "string", + "defaultValue": "S1", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default)." + } + }, + "azureBotRegion": { + "type": "string", + "defaultValue": "global", + "metadata": { + "description": "Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope." + } + }, + "botEndpoint": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + } + }, + "variables": { + "botEndpoint": "[if(empty(parameters('botEndpoint')), concat('https://', parameters('azureBotId'), '.azurewebsites.net/api/messages'), parameters('botEndpoint'))]" + }, + "resources": [ + { + "apiVersion": "2021-05-01-preview", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('azureBotId')]", + "location": "[parameters('azureBotRegion')]", + "kind": "azurebot", + "sku": { + "name": "[parameters('azureBotSku')]" + }, + "properties": { + "name": "[parameters('azureBotId')]", + "displayName": "[parameters('azureBotId')]", + "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "luisAppIds": [], + "schemaTransformationVersion": "1.3", + "isCmekEnabled": false, + "isIsolated": false + } + } + ] +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json new file mode 100644 index 0000000000..3a44abf249 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json @@ -0,0 +1,210 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "appServiceName": { + "type": "string", + "metadata": { + "description": "The globally unique name of the Web App." + } + }, + "existingAppServicePlanName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Name of the existing App Service Plan used to create the Web App for the bot." + } + }, + "existingAppServicePlanLocation": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The location of the App Service Plan." + } + }, + "newAppServicePlanName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The name of the new App Service Plan." + } + }, + "newAppServicePlanLocation": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The location of the App Service Plan." + } + }, + "newAppServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types. Defaults to \"\"." + } + } + }, + "variables": { + "useExistingServicePlan": "[not(empty(parameters('existingAppServicePlanName')))]", + "servicePlanName": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanName'), parameters('newAppServicePlanName'))]", + "servicePlanLocation": "[if(variables('useExistingServicePlan'), parameters('existingAppServicePlanLocation'), parameters('newAppServicePlanLocation'))]" + }, + "resources": [ + { + "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.", + "type": "Microsoft.Web/serverfarms", + "condition": "[not(variables('useExistingServicePlan'))]", + "name": "[variables('servicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[parameters('newAppServicePlanLocation')]", + "sku": "[parameters('newAppServicePlanSku')]", + "kind": "linux", + "properties": { + "name": "[variables('servicePlanName')]", + "perSiteScaling": false, + "reserved": true, + "targetWorkerCount": 0, + "targetWorkerSizeId": 0 + } + }, + { + "comments": "Create a Web App using an App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2015-08-01", + "name": "[parameters('appServiceName')]", + "location": "[variables('servicePlanLocation')]", + "kind": "app,linux", + "dependsOn": [ + "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]" + ], + "properties": { + "enabled": true, + "hostNameSslStates": [ + { + "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]", + "sslState": "Disabled", + "hostType": "Standard" + }, + { + "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]", + "sslState": "Disabled", + "hostType": "Repository" + } + ], + "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]", + "reserved": true, + "scmSiteAlsoStopped": false, + "clientAffinityEnabled": false, + "clientCertEnabled": false, + "hostNamesDisabled": false, + "containerSize": 0, + "dailyMemoryTimeQuota": 0, + "httpsOnly": false, + "siteConfig": { + "appSettings": [ + { + "name": "SCM_DO_BUILD_DURING_DEPLOYMENT", + "value": "true" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + } + } + } + }, + { + "type": "Microsoft.Web/sites/config", + "apiVersion": "2016-08-01", + "name": "[concat(parameters('appServiceName'), '/web')]", + "location": "[variables('servicePlanLocation')]", + "dependsOn": [ + "[resourceId('Microsoft.Web/sites', parameters('appServiceName'))]" + ], + "properties": { + "numberOfWorkers": 1, + "defaultDocuments": [ + "Default.htm", + "Default.html", + "Default.asp", + "index.htm", + "index.html", + "iisstart.htm", + "default.aspx", + "index.php", + "hostingstart.html" + ], + "netFrameworkVersion": "v4.0", + "phpVersion": "", + "pythonVersion": "", + "nodeVersion": "", + "linuxFxVersion": "PYTHON|3.7", + "requestTracingEnabled": false, + "remoteDebuggingEnabled": false, + "remoteDebuggingVersion": "VS2017", + "httpLoggingEnabled": true, + "logsDirectorySizeLimit": 35, + "detailedErrorLoggingEnabled": false, + "publishingUsername": "[concat('$', parameters('appServiceName'))]", + "scmType": "None", + "use32BitWorkerProcess": true, + "webSocketsEnabled": false, + "alwaysOn": false, + "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP", + "managedPipelineMode": "Integrated", + "virtualApplications": [ + { + "virtualPath": "/", + "physicalPath": "site\\wwwroot", + "preloadEnabled": false, + "virtualDirectories": null + } + ], + "winAuthAdminState": 0, + "winAuthTenantState": 0, + "customAppPoolIdentityAdminState": false, + "customAppPoolIdentityTenantState": false, + "loadBalancing": "LeastRequests", + "routingRules": [], + "experiments": { + "rampUpRules": [] + }, + "autoHealEnabled": false, + "vnetName": "", + "minTlsVersion": "1.2", + "ftpsState": "AllAllowed", + "reservedInstanceCount": 0 + } + } + ] +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json new file mode 100644 index 0000000000..f180618138 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupName": { + "value": "" + }, + "groupLocation": { + "value": "" + }, + "azureBotId": { + "value": "" + }, + "azureBotSku": { + "value": "S1" + }, + "azureBotRegion": { + "value": "global" + }, + "botEndpoint": { + "value": "" + }, + "appId": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json new file mode 100644 index 0000000000..f3f07b4972 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupName": { + "value": "" + }, + "groupLocation": { + "value": "" + }, + "appServiceName": { + "value": "" + }, + "appServicePlanName": { + "value": "" + }, + "appServicePlanLocation": { + "value": "" + }, + "appServicePlanSku": { + "value": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + } + }, + "appId": { + "value": "" + }, + "appSecret": { + "value": "" + } + } +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/readme.md b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/readme.md new file mode 100644 index 0000000000..dbdfabf9a9 --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/readme.md @@ -0,0 +1,27 @@ +# Usage +BotApp must be deployed prior to AzureBot. + +### Command line: +`az login`
+`az deployment sub create --template-file --location --parameters @` + +## Parameters for template-BotApp-new-rg.json: + +- **groupName**: (required) The name of the new Resource Group. +- **groupLocation**: (required) The location of the new Resource Group. +- **appServiceName**: (required) The location of the App Service Plan. +- **appServicePlanName**: (required) The name of the App Service Plan. +- **appServicePlanLocation**: The location of the App Service Plan. Defaults to use groupLocation. +- **appServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values. +- **appId**: (required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings. +- **appSecret**: (required for MultiTenant and SingleTenant) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. + +## Parameters for template-AzureBot-new-rg.json: + +- **groupName**: (required) The name of the new Resource Group. +- **groupLocation**: (required) The location of the new Resource Group. +- **azureBotId**: (required) The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable. +- **azureBotSku**: The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default). +- **azureBotRegion**: Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope. +- **botEndpoint**: Use to handle client messages, Such as `https://.azurewebsites.net/api/messages`. +- **appId**: (required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings. \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json new file mode 100644 index 0000000000..927307e0fc --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json @@ -0,0 +1,104 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupName": { + "type": "string", + "metadata": { + "description": "Specifies the name of the Resource Group." + } + }, + "groupLocation": { + "type": "string", + "metadata": { + "description": "Specifies the location of the Resource Group." + } + }, + "azureBotId": { + "type": "string", + "metadata": { + "description": "The globally unique and immutable bot ID." + } + }, + "azureBotSku": { + "type": "string", + "defaultValue": "S1", + "metadata": { + "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1." + } + }, + "azureBotRegion": { + "type": "string", + "defaultValue": "global", + "metadata": { + "description": "" + } + }, + "botEndpoint": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Use to handle client messages, Such as https://.azurewebsites.net/api/messages." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + } + }, + "variables": { + "botEndpoint": "[if(empty(parameters('botEndpoint')), concat('https://', parameters('azureBotId'), '.azurewebsites.net/api/messages'), parameters('botEndpoint'))]" + }, + "resources": [ + { + "name": "[parameters('groupName')]", + "type": "Microsoft.Resources/resourceGroups", + "apiVersion": "2018-05-01", + "location": "[parameters('groupLocation')]", + "properties": {} + }, + { + "type": "Microsoft.Resources/deployments", + "apiVersion": "2018-05-01", + "name": "storageDeployment", + "resourceGroup": "[parameters('groupName')]", + "dependsOn": [ + "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]" + ], + "properties": { + "mode": "Incremental", + "template": { + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "variables": {}, + "resources": [ + { + "apiVersion": "2021-03-01", + "type": "Microsoft.BotService/botServices", + "name": "[parameters('azureBotId')]", + "location": "[parameters('azureBotRegion')]", + "kind": "azurebot", + "sku": { + "name": "[parameters('azureBotSku')]" + }, + "properties": { + "name": "[parameters('azureBotId')]", + "displayName": "[parameters('azureBotId')]", + "iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png", + "endpoint": "[variables('botEndpoint')]", + "msaAppId": "[parameters('appId')]", + "luisAppIds": [], + "schemaTransformationVersion": "1.3", + "isCmekEnabled": false, + "isIsolated": false + } + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json new file mode 100644 index 0000000000..612112a32b --- /dev/null +++ b/samples/bot-message-reaction/python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json @@ -0,0 +1,227 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "groupName": { + "type": "string", + "metadata": { + "description": "Specifies the name of the Resource Group." + } + }, + "groupLocation": { + "type": "string", + "metadata": { + "description": "Specifies the location of the Resource Group." + } + }, + "appServiceName": { + "type": "string", + "metadata": { + "description": "The globally unique name of the Web App." + } + }, + "appServicePlanName": { + "type": "string", + "metadata": { + "description": "The name of the App Service Plan." + } + }, + "appServicePlanLocation": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "The location of the App Service Plan." + } + }, + "appServicePlanSku": { + "type": "object", + "defaultValue": { + "name": "S1", + "tier": "Standard", + "size": "S1", + "family": "S", + "capacity": 1 + }, + "metadata": { + "description": "The SKU of the App Service Plan. Defaults to Standard values." + } + }, + "appId": { + "type": "string", + "metadata": { + "description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings." + } + }, + "appSecret": { + "type": "string", + "metadata": { + "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Required for MultiTenant and SingleTenant app types." + } + } + }, + "variables": { + "appServicePlanName": "[parameters('appServicePlanName')]", + "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), parameters('groupLocation'), parameters('appServicePlanLocation'))]", + "appServiceName": "[parameters('appServiceName')]", + "resourceGroupId": "[concat(subscription().id, '/resourceGroups/', parameters('groupName'))]" + }, + "resources": [ + { + "name": "[parameters('groupName')]", + "type": "Microsoft.Resources/resourceGroups", + "apiVersion": "2018-05-01", + "location": "[parameters('groupLocation')]", + "properties": {} + }, + { + "type": "Microsoft.Resources/deployments", + "apiVersion": "2018-05-01", + "name": "storageDeployment", + "resourceGroup": "[parameters('groupName')]", + "dependsOn": [ + "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]" + ], + "properties": { + "mode": "Incremental", + "template": { + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": {}, + "variables": {}, + "resources": [ + { + "comments": "Create a new App Service Plan", + "type": "Microsoft.Web/serverfarms", + "name": "[variables('appServicePlanName')]", + "apiVersion": "2018-02-01", + "location": "[variables('resourcesLocation')]", + "sku": "[parameters('appServicePlanSku')]", + "kind": "linux", + "properties": { + "name": "[variables('appServicePlanName')]", + "perSiteScaling": false, + "reserved": true, + "targetWorkerCount": 0, + "targetWorkerSizeId": 0 + } + }, + { + "comments": "Create a Web App using the new App Service Plan", + "type": "Microsoft.Web/sites", + "apiVersion": "2015-08-01", + "location": "[variables('resourcesLocation')]", + "kind": "app,linux", + "dependsOn": [ + "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/serverfarms/', variables('appServicePlanName'))]" + ], + "name": "[variables('appServiceName')]", + "properties": { + "name": "[variables('appServiceName')]", + "hostNameSslStates": [ + { + "name": "[concat(parameters('appServiceName'), '.azurewebsites.net')]", + "sslState": "Disabled", + "hostType": "Standard" + }, + { + "name": "[concat(parameters('appServiceName'), '.scm.azurewebsites.net')]", + "sslState": "Disabled", + "hostType": "Repository" + } + ], + "serverFarmId": "[variables('appServicePlanName')]", + "siteConfig": { + "appSettings": [ + { + "name": "SCM_DO_BUILD_DURING_DEPLOYMENT", + "value": "true" + }, + { + "name": "MicrosoftAppId", + "value": "[parameters('appId')]" + }, + { + "name": "MicrosoftAppPassword", + "value": "[parameters('appSecret')]" + } + ], + "cors": { + "allowedOrigins": [ + "https://botservice.hosting.portal.azure.net", + "https://hosting.onecloud.azure-test.net/" + ] + }, + "webSocketsEnabled": true + } + } + }, + { + "type": "Microsoft.Web/sites/config", + "apiVersion": "2016-08-01", + "name": "[concat(parameters('appServiceName'), '/web')]", + "location": "[variables('resourcesLocation')]", + "dependsOn": [ + "[concat(variables('resourceGroupId'), '/providers/Microsoft.Web/sites/', parameters('appServiceName'))]" + ], + "properties": { + "numberOfWorkers": 1, + "defaultDocuments": [ + "Default.htm", + "Default.html", + "Default.asp", + "index.htm", + "index.html", + "iisstart.htm", + "default.aspx", + "index.php", + "hostingstart.html" + ], + "netFrameworkVersion": "v4.0", + "phpVersion": "", + "pythonVersion": "", + "nodeVersion": "", + "linuxFxVersion": "PYTHON|3.7", + "requestTracingEnabled": false, + "remoteDebuggingEnabled": false, + "remoteDebuggingVersion": "VS2017", + "httpLoggingEnabled": true, + "logsDirectorySizeLimit": 35, + "detailedErrorLoggingEnabled": false, + "publishingUsername": "[concat('$', parameters('appServiceName'))]", + "scmType": "None", + "use32BitWorkerProcess": true, + "webSocketsEnabled": false, + "alwaysOn": false, + "appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP", + "managedPipelineMode": "Integrated", + "virtualApplications": [ + { + "virtualPath": "/", + "physicalPath": "site\\wwwroot", + "preloadEnabled": false, + "virtualDirectories": null + } + ], + "winAuthAdminState": 0, + "winAuthTenantState": 0, + "customAppPoolIdentityAdminState": false, + "customAppPoolIdentityTenantState": false, + "loadBalancing": "LeastRequests", + "routingRules": [], + "experiments": { + "rampUpRules": [] + }, + "autoHealEnabled": false, + "vnetName": "", + "minTlsVersion": "1.2", + "ftpsState": "AllAllowed", + "reservedInstanceCount": 0 + } + } + ], + "outputs": {} + } + } + } + ] +} \ No newline at end of file diff --git a/samples/bot-message-reaction/python/env/.env.local b/samples/bot-message-reaction/python/env/.env.local new file mode 100644 index 0000000000..22987ef6bb --- /dev/null +++ b/samples/bot-message-reaction/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/bot-message-reaction/python/infra/azure.bicep b/samples/bot-message-reaction/python/infra/azure.bicep new file mode 100644 index 0000000000..8734cb547b --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction/python/infra/azure.parameters.json b/samples/bot-message-reaction/python/infra/azure.parameters.json new file mode 100644 index 0000000000..23fbfffad3 --- /dev/null +++ b/samples/bot-message-reaction/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": "BotMessageReaction" + } + } + } \ No newline at end of file diff --git a/samples/bot-message-reaction/python/requirements.txt b/samples/bot-message-reaction/python/requirements.txt new file mode 100644 index 0000000000..385d723f9c --- /dev/null +++ b/samples/bot-message-reaction/python/requirements.txt @@ -0,0 +1,2 @@ +requests==2.32.3 +botbuilder-integration-aiohttp>=4.16.2 diff --git a/samples/bot-message-reaction/python/teamsapp.local.yml b/samples/bot-message-reaction/python/teamsapp.local.yml new file mode 100644 index 0000000000..a28178edac --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction-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: botmessagereaction-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: botmessagereaction${{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-message-reaction/python/teamsapp.yml b/samples/bot-message-reaction/python/teamsapp.yml new file mode 100644 index 0000000000..3304ce74b1 --- /dev/null +++ b/samples/bot-message-reaction/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-message-reaction-python + +environmentFolderPath: ./env