diff --git a/bot-conversation-python/.gitignore b/bot-conversation-python/.gitignore new file mode 100644 index 00000000..1954bc87 --- /dev/null +++ b/bot-conversation-python/.gitignore @@ -0,0 +1,14 @@ +# TeamsFx files +env/.env.*.user +env/.env.local +appPackage/build/ + +# python virtual environment +.venv/ + +# misc +.env +.deployment/ + +# tmp files +__pycache__/ \ No newline at end of file diff --git a/bot-conversation-python/.vscode/extensions.json b/bot-conversation-python/.vscode/extensions.json new file mode 100644 index 00000000..bf8c33db --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/.vscode/launch.json b/bot-conversation-python/.vscode/launch.json new file mode 100644 index 00000000..9c7356e2 --- /dev/null +++ b/bot-conversation-python/.vscode/launch.json @@ -0,0 +1,69 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch App (Edge)", + "type": "msedge", + "request": "launch", + "url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}", + "cascadeTerminateToConfigurations": [ + "Python: Run App Locally" + ], + "presentation": { + "group": "all", + "hidden": true + }, + "internalConsoleOptions": "neverOpen" + }, + { + "name": "Launch App (Chrome)", + "type": "chrome", + "request": "launch", + "url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}", + "cascadeTerminateToConfigurations": [ + "Python: Run App Locally" + ], + "presentation": { + "group": "all", + "hidden": true + }, + "internalConsoleOptions": "neverOpen" + }, + { + "name": "Python: Run App Locally", + "type": "python", + "request": "launch", + "program": "${workspaceFolder}/app.py", + "cwd": "${workspaceFolder}", + "console": "integratedTerminal", + } + ], + "compounds": [ + { + "name": "Debug (Edge)", + "configurations": [ + "Launch App (Edge)", + "Python: Run App Locally" + ], + "preLaunchTask": "Prepare Teams App Resources", + "presentation": { + "group": "all", + "order": 1 + }, + "stopAll": true + }, + { + "name": "Debug (Chrome)", + "configurations": [ + "Launch App (Chrome)", + "Python: Run App Locally" + ], + "preLaunchTask": "Prepare Teams App Resources", + "presentation": { + "group": "all", + "order": 2 + }, + "stopAll": true + } + ] +} diff --git a/bot-conversation-python/.vscode/settings.json b/bot-conversation-python/.vscode/settings.json new file mode 100644 index 00000000..3014fd9c --- /dev/null +++ b/bot-conversation-python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} diff --git a/bot-conversation-python/.vscode/tasks.json b/bot-conversation-python/.vscode/tasks.json new file mode 100644 index 00000000..2161094d --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/Images/1.BotInstallationMessage.PNG b/bot-conversation-python/Images/1.BotInstallationMessage.PNG new file mode 100644 index 00000000..a98e1a03 Binary files /dev/null and b/bot-conversation-python/Images/1.BotInstallationMessage.PNG differ diff --git a/bot-conversation-python/Images/2.WelcomeCard.PNG b/bot-conversation-python/Images/2.WelcomeCard.PNG new file mode 100644 index 00000000..3d4dc6b7 Binary files /dev/null and b/bot-conversation-python/Images/2.WelcomeCard.PNG differ diff --git a/bot-conversation-python/Images/3.MentionMe.PNG b/bot-conversation-python/Images/3.MentionMe.PNG new file mode 100644 index 00000000..0a839a2f Binary files /dev/null and b/bot-conversation-python/Images/3.MentionMe.PNG differ diff --git a/bot-conversation-python/Images/4.MessageAllMembers.PNG b/bot-conversation-python/Images/4.MessageAllMembers.PNG new file mode 100644 index 00000000..a285ddde Binary files /dev/null and b/bot-conversation-python/Images/4.MessageAllMembers.PNG differ diff --git a/bot-conversation-python/Images/BotConversation.gif b/bot-conversation-python/Images/BotConversation.gif new file mode 100644 index 00000000..287fc27a Binary files /dev/null and b/bot-conversation-python/Images/BotConversation.gif differ diff --git a/bot-conversation-python/README.md b/bot-conversation-python/README.md new file mode 100644 index 00000000..3e2c679b --- /dev/null +++ b/bot-conversation-python/README.md @@ -0,0 +1,146 @@ +--- +page_type: sample +description: This sample app demonstrates use of different bot conversation events available in bot framework v4 for personal and teams scope. +products: +- office-teams +- office +- office-365 +languages: +- python +extensions: + contentType: samples + createdDate: "12-12-2019 13:38:25" +urlFragment: officedev-microsoft-teams-samples-bot-conversation-python + +--- + +# Teams Conversation Bot + +Bot Framework v4 Conversation Bot sample for Teams ([Messages in bot conversations](https://learn.microsoft.com/microsoftteams/platform/bots/how-to/conversations/conversation-messages?tabs=dotnet)). + +This bot has been created using [Bot Framework](https://dev.botframework.com). This sample shows +how to incorporate basic conversational flow into a Teams application. It also illustrates a few of the Teams specific calls you can make from your bot. + +## Included Features +* Bots +* Adaptive Cards +* Teams Conversation Events +* Immersive Reading Support for Cards + +## Interaction with bot +![BotConversation](Images/BotConversation.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 Conversation Bot:** [Manifest](/samples/bot-conversation/csharp/demo-manifest/bot-conversation.zip) + +## Prerequisites + +- Microsoft Teams is installed and you have an account +- [Python SDK](https://www.python.org/downloads/) min version 3.6 +- [dev tunnel](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/get-started?tabs=windows) or [ngrok](https://ngrok.com/) latest version or equivalent tunnelling solution + + +## To try this sample + +## 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 [Bot Framework registration 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 [Bot Framework registration](https://docs.microsoft.com/microsoftteams/platform/bots/how-to/create-a-bot-for-teams#register-your-web-service-with-the-bot-framework) + +4) In a terminal, go to `samples\bot-conversation` + +5) Activate your desired virtual environment + +6) Install dependencies by running ```pip install -r requirements.txt``` in the project folder. + +7) Update the `config.py` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.) + +8) __*This step is specific to Teams.*__ + - **Edit** the `manifest.json` contained in the `appPackage` 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 `appPackage` folder to create a `manifest.zip` + - **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app") + +9) Run your bot with `python app.py` + +## Interacting with the bot + +You can interact with this bot by sending it a message, or selecting a command from the command list. The bot will respond to the following strings. + +1. **Show Welcome** + - **Result:** The bot will send the welcome card for you to interact with + - **Valid Scopes:** personal, group chat, team chat +2. **MentionMe** + - **Result:** The bot will respond to the message and mention the user + - **Valid Scopes:** personal, group chat, team chat +3. **MessageAllMembers** + - **Result:** The bot will send a 1-on-1 message to each member in the current conversation (aka on the conversation's roster). + - **Valid Scopes:** personal, group chat, team chat + +You can select an option from the command list by typing ```@TeamsConversationBot``` into the compose message area and ```What can I do?``` text above the compose area. + +## Running the sample + +The bot initialization message +![Message](Images/1.BotInstallationMessage.PNG) + +The bot will send the welcome card for you to interact with +![WelcomeCard](Images/2.WelcomeCard.PNG) + +The bot will respond to the message and mention the user +![MentionMe](Images/3.MentionMe.PNG) + +The bot initialization message +![MessageAllMembers](Images/4.MessageAllMembers.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) +- [Messages in bot conversations](https://learn.microsoft.com/microsoftteams/platform/bots/how-to/conversations/conversation-messages?tabs=dotnet) + + \ No newline at end of file diff --git a/bot-conversation-python/app.py b/bot-conversation-python/app.py new file mode 100644 index 00000000..1ed01df2 --- /dev/null +++ b/bot-conversation-python/app.py @@ -0,0 +1,94 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import sys +import traceback +import uuid +from datetime import datetime +from http import HTTPStatus + +from aiohttp import web +from aiohttp.web import Request, Response, json_response +from botbuilder.core import ( + BotFrameworkAdapterSettings, + TurnContext, + BotFrameworkAdapter, +) +from botbuilder.core.integration import aiohttp_error_middleware +from botbuilder.schema import Activity, ActivityTypes + +from bots import TeamsConversationBot +from config import DefaultConfig + +CONFIG = DefaultConfig() + +# Create adapter. +# See https://aka.ms/about-bot-adapter to learn more about how bots work. +SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD) +ADAPTER = BotFrameworkAdapter(SETTINGS) + + +# Catch-all for errors. +async def on_error(context: TurnContext, error: Exception): + # This check writes out errors to console log .vs. app insights. + # NOTE: In production environment, you should consider logging this to Azure + # application insights. + print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) + traceback.print_exc() + + # Send a message to the user + await context.send_activity("The bot encountered an error or bug.") + await context.send_activity( + "To continue to run this bot, please fix the bot source code." + ) + # Send a trace activity if we're talking to the Bot Framework Emulator + if context.activity.channel_id == "emulator": + # Create a trace activity that contains the error object + trace_activity = Activity( + label="TurnError", + name="on_turn_error Trace", + timestamp=datetime.utcnow(), + type=ActivityTypes.trace, + value=f"{error}", + value_type="https://www.botframework.com/schemas/error", + ) + # Send a trace activity, which will be displayed in Bot Framework Emulator + await context.send_activity(trace_activity) + + +ADAPTER.on_turn_error = on_error + +# If the channel is the Emulator, and authentication is not in use, the AppId will be null. +# We generate a random AppId for this case only. This is not required for production, since +# the AppId will have a value. +APP_ID = SETTINGS.app_id if SETTINGS.app_id else uuid.uuid4() + +# Create the Bot +BOT = TeamsConversationBot(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]) +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/bot-conversation-python/appPackage/color.png b/bot-conversation-python/appPackage/color.png new file mode 100644 index 00000000..325ebe2f Binary files /dev/null and b/bot-conversation-python/appPackage/color.png differ diff --git a/bot-conversation-python/appPackage/manifest.json b/bot-conversation-python/appPackage/manifest.json new file mode 100644 index 00000000..1e9d434f --- /dev/null +++ b/bot-conversation-python/appPackage/manifest.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.14/MicrosoftTeams.schema.json", + "manifestVersion": "1.14", + "version": "1.0.0", + "id": "${{TEAMS_APP_ID}}", + "packageName": "com.teams.sample.teamsconversationbot", + "developer": { + "name": "teamsConversationBot", + "websiteUrl": "https://www.microsoft.com", + "privacyUrl": "https://www.teams.com/privacy", + "termsOfUseUrl": "https://www.teams.com/termsofuser" + }, + "icons": { + "outline": "outline.png", + "color": "color.png" + }, + "name": { + "short": "TeamsConversationBot", + "full": "TeamsConversationBot" + }, + "description": { + "short": "TeamsConversationBot", + "full": "TeamsConversationBot" + }, + "accentColor": "#FFFFFF", + "bots": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "scopes": [ + "personal", + "groupchat", + "team" + ], + "isNotificationOnly": false, + "supportsCalling": false, + "supportsVideo": false, + "supportsFiles": false, + "commandLists": [ + { + "scopes": [ + "personal", + "groupchat", + "team" + ], + "commands": [ + { + "title": "MentionMe", + "description": "Sends message with @mention of the sender" + }, + { + "title": "Show Welcome", + "description": "Shows the welcome card" + }, + { + "title": "MessageAllMembers", + "description": "Send 1 to 1 message to all members of the current conversation" + } + ] + } + ] + } + ], + "permissions": [ + "identity", + "messageTeamMembers" + ], + "validDomains": ["${{BOT_DOMAIN}}"] + } diff --git a/bot-conversation-python/appPackage/outline.png b/bot-conversation-python/appPackage/outline.png new file mode 100644 index 00000000..736aeb92 Binary files /dev/null and b/bot-conversation-python/appPackage/outline.png differ diff --git a/bot-conversation-python/assets/sample.json b/bot-conversation-python/assets/sample.json new file mode 100644 index 00000000..10c6ad2a --- /dev/null +++ b/bot-conversation-python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-bot-conversation-python", + "source": "officeDev", + "title": "Conversation Bot using Bot Framework v4", + "shortDescription": "This sample app demonstrates use of different bot conversation events available in bot framework v4 for personal and teams scope.", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/bot-conversation/python", + "longDescription": [ + "This sample app demonstrates use of different bot conversation events available in bot framework v4 for personal and teams scope." + ], + "creationDateTime": "2019-10-17", + "updateDateTime": "2022-10-01", + "products": [ + "Teams" + ], + "metadata": [ + { + "key": "TEAMS-SAMPLE-SOURCE", + "value": "OfficeDev" + }, + { + "key": "TEAMS-SERVER-LANGUAGE", + "value": "python" + }, + { + "key": "TEAMS-SERVER-PLATFORM", + "value": "python" + }, + { + "key": "TEAMS-FEATURES", + "value": "bot" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/bot-conversation/python/Images/BotConversation.gif", + "alt": "Solution UX showing Conversation Bot using python" + } + ], + "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/bot-conversation-python/bots/__init__.py b/bot-conversation-python/bots/__init__.py new file mode 100644 index 00000000..ae6aca93 --- /dev/null +++ b/bot-conversation-python/bots/__init__.py @@ -0,0 +1,3 @@ +from .teams_conversation_bot import TeamsConversationBot + +__all__ = ["TeamsConversationBot"] \ No newline at end of file diff --git a/bot-conversation-python/bots/teams_conversation_bot.py b/bot-conversation-python/bots/teams_conversation_bot.py new file mode 100644 index 00000000..b94b4013 --- /dev/null +++ b/bot-conversation-python/bots/teams_conversation_bot.py @@ -0,0 +1,227 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import os +import json + +from typing import List +from botbuilder.core import CardFactory, TurnContext, MessageFactory +from botbuilder.core.teams import TeamsActivityHandler, TeamsInfo +from botbuilder.schema import CardAction, HeroCard, Mention, ConversationParameters, Attachment, Activity +from botbuilder.schema.teams import TeamInfo, TeamsChannelAccount +from botbuilder.schema._connector_client_enums import ActionTypes + +ADAPTIVECARDTEMPLATE = "resources/UserMentionCardTemplate.json" + +class TeamsConversationBot(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 team { member.given_name } { member.surname }. " + ) + + async def on_message_activity(self, turn_context: TurnContext): + TurnContext.remove_recipient_mention(turn_context.activity) + text = turn_context.activity.text.strip().lower() + + if "mention me" in text: + await self._mention_adaptive_card_activity(turn_context) + return + + if "mention" in text: + await self._mention_activity(turn_context) + return + + if "update" in text: + await self._send_card(turn_context, True) + return + + if "message" in text: + await self._message_all_members(turn_context) + return + + if "who" in text: + await self._get_member(turn_context) + return + + if "delete" in text: + await self._delete_card_activity(turn_context) + return + + await self._send_card(turn_context, False) + return + + async def _mention_adaptive_card_activity(self, turn_context: TurnContext): + TeamsChannelAccount: member = None + try: + member = await TeamsInfo.get_member( + turn_context, turn_context.activity.from_property.id + ) + except Exception as e: + if "MemberNotFoundInConversation" in e.args[0]: + await turn_context.send_activity("Member not found.") + return + else: + raise + + card_path = os.path.join(os.getcwd(), ADAPTIVECARDTEMPLATE) + with open(card_path, "rb") as in_file: + template_json = json.load(in_file) + + for t in template_json["body"]: + t["text"] = t["text"].replace("${userName}", member.name) + for e in template_json["msteams"]["entities"]: + e["text"] = e["text"].replace("${userName}", member.name) + e["mentioned"]["id"] = e["mentioned"]["id"].replace("${userUPN}", member.user_principal_name) + e["mentioned"]["id"] = e["mentioned"]["id"].replace("${userAAD}", member.additional_properties["aadObjectId"]) + e["mentioned"]["name"] = e["mentioned"]["name"].replace("${userName}", member.name) + + adaptive_card_attachment = Activity( + attachments=[CardFactory.adaptive_card(template_json)] + ) + await turn_context.send_activity(adaptive_card_attachment) + + async def _mention_activity(self, turn_context: TurnContext): + mention = Mention( + mentioned=turn_context.activity.from_property, + text=f"{turn_context.activity.from_property.name}", + type="mention", + ) + + reply_activity = MessageFactory.text(f"Hello {mention.text}") + reply_activity.entities = [Mention().deserialize(mention.serialize())] + await turn_context.send_activity(reply_activity) + + async def _send_card(self, turn_context: TurnContext, isUpdate): + buttons = [ + CardAction( + type=ActionTypes.message_back, + title="Message all members", + text="messageallmembers", + ), + CardAction(type=ActionTypes.message_back, title="Who am I?", text="whoami"), + CardAction(type=ActionTypes.message_back, title="Find me in Adaptive Card", text="mention me"), + CardAction( + type=ActionTypes.message_back, title="Delete card", text="deletecard" + ), + ] + if isUpdate: + await self._send_update_card(turn_context, buttons) + else: + await self._send_welcome_card(turn_context, buttons) + + async def _send_welcome_card(self, turn_context: TurnContext, buttons): + buttons.append( + CardAction( + type=ActionTypes.message_back, + title="Update Card", + text="updatecardaction", + value={"count": 0}, + ) + ) + card = HeroCard( + title="Welcome Card", text="Click the buttons.", buttons=buttons + ) + await turn_context.send_activity( + MessageFactory.attachment(CardFactory.hero_card(card)) + ) + + async def _send_update_card(self, turn_context: TurnContext, buttons): + data = turn_context.activity.value + data["count"] += 1 + buttons.append( + CardAction( + type=ActionTypes.message_back, + title="Update Card", + text="updatecardaction", + value=data, + ) + ) + card = HeroCard( + title="Updated card", text=f"Update count {data['count']}", buttons=buttons + ) + + updated_activity = MessageFactory.attachment(CardFactory.hero_card(card)) + updated_activity.id = turn_context.activity.reply_to_id + await turn_context.update_activity(updated_activity) + + async def _get_member(self, turn_context: TurnContext): + TeamsChannelAccount: member = None + try: + member = await TeamsInfo.get_member( + turn_context, turn_context.activity.from_property.id + ) + except Exception as e: + if "MemberNotFoundInConversation" in e.args[0]: + await turn_context.send_activity("Member not found.") + else: + raise + else: + await turn_context.send_activity(f"You are: {member.name}") + + async def _message_all_members(self, turn_context: TurnContext): + team_members = await self._get_paged_members(turn_context) + + for member in team_members: + conversation_reference = TurnContext.get_conversation_reference( + turn_context.activity + ) + + conversation_parameters = ConversationParameters( + is_group=False, + bot=turn_context.activity.recipient, + members=[member], + tenant_id=turn_context.activity.conversation.tenant_id, + ) + + async def get_ref(tc1): + conversation_reference_inner = TurnContext.get_conversation_reference( + tc1.activity + ) + return await tc1.adapter.continue_conversation( + conversation_reference_inner, send_message, self._app_id + ) + + async def send_message(tc2: TurnContext): + return await tc2.send_activity( + f"Hello {member.name}. I'm a Teams conversation bot." + ) # pylint: disable=cell-var-from-loop + + await turn_context.adapter.create_conversation( + conversation_reference, get_ref, conversation_parameters + ) + + await turn_context.send_activity( + MessageFactory.text("All messages have been sent") + ) + + async def _get_paged_members( + self, turn_context: TurnContext + ) -> List[TeamsChannelAccount]: + paged_members = [] + continuation_token = None + + while True: + current_page = await TeamsInfo.get_paged_members( + turn_context, continuation_token, 100 + ) + continuation_token = current_page.continuation_token + paged_members.extend(current_page.members) + + if continuation_token is None: + break + + return paged_members + + async def _delete_card_activity(self, turn_context: TurnContext): + await turn_context.delete_activity(turn_context.activity.reply_to_id) diff --git a/bot-conversation-python/config.py b/bot-conversation-python/config.py new file mode 100644 index 00000000..c682ef85 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json new file mode 100644 index 00000000..cc1800c0 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json new file mode 100644 index 00000000..54a7d628 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/readme.md b/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/readme.md new file mode 100644 index 00000000..c86cbf9d --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json new file mode 100644 index 00000000..60c9c1bb --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/bot-conversation-python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json new file mode 100644 index 00000000..3a44abf2 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json new file mode 100644 index 00000000..f1806181 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json new file mode 100644 index 00000000..f3f07b49 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/readme.md b/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/readme.md new file mode 100644 index 00000000..dbdfabf9 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json new file mode 100644 index 00000000..927307e0 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/bot-conversation-python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json new file mode 100644 index 00000000..612112a3 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/env/.env.dev b/bot-conversation-python/env/.env.dev new file mode 100644 index 00000000..1d95a988 --- /dev/null +++ b/bot-conversation-python/env/.env.dev @@ -0,0 +1,4 @@ +# This file includes environment variables that will be committed to git by default. + +# Built-in environment variables +TEAMSFX_ENV=dev \ No newline at end of file diff --git a/bot-conversation-python/env/.env.local b/bot-conversation-python/env/.env.local new file mode 100644 index 00000000..241211d0 --- /dev/null +++ b/bot-conversation-python/env/.env.local @@ -0,0 +1,20 @@ +# 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= \ No newline at end of file diff --git a/bot-conversation-python/infra/azure.bicep b/bot-conversation-python/infra/azure.bicep new file mode 100644 index 00000000..8734cb54 --- /dev/null +++ b/bot-conversation-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/bot-conversation-python/infra/azure.parameters.json b/bot-conversation-python/infra/azure.parameters.json new file mode 100644 index 00000000..44af7b62 --- /dev/null +++ b/bot-conversation-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": "bot-conversation" + } + } + } \ No newline at end of file diff --git a/bot-conversation-python/requirements.txt b/bot-conversation-python/requirements.txt new file mode 100644 index 00000000..c6424216 --- /dev/null +++ b/bot-conversation-python/requirements.txt @@ -0,0 +1,2 @@ +requests==2.31.0 +botbuilder-integration-aiohttp>=4.14.5 diff --git a/bot-conversation-python/resources/UserMentionCardTemplate.json b/bot-conversation-python/resources/UserMentionCardTemplate.json new file mode 100644 index 00000000..ed929568 --- /dev/null +++ b/bot-conversation-python/resources/UserMentionCardTemplate.json @@ -0,0 +1,35 @@ +{ + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "type": "AdaptiveCard", + "version": "1.0", + "body": [ + { + "type": "TextBlock", + "text": "Mention a user by User Principle Name: Hello ${userName} UPN" + }, + { + "type": "TextBlock", + "text": "Mention a user by AAD Object Id: Hello ${userName} AAD" + } + ], + "msteams": { + "entities": [ + { + "type": "mention", + "text": "${userName} UPN", + "mentioned": { + "id": "${userUPN}", + "name": "${userName}" + } + }, + { + "type": "mention", + "text": "${userName} AAD", + "mentioned": { + "id": "${userAAD}", + "name": "${userName}" + } + } + ] + } +} \ No newline at end of file diff --git a/bot-conversation-python/teamsapp.local.yml b/bot-conversation-python/teamsapp.local.yml new file mode 100644 index 00000000..4416cab5 --- /dev/null +++ b/bot-conversation-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-conversation-python + +provision: + # Creates a new Azure Active Directory (AAD) app to authenticate users if the environment variable that stores clientId is empty + - uses: aadApp/create + with: + name: teamsConversationBot-aad # Note: when you run aadApp/update, the AAD app name will be updated based on the definition in manifest. If you don't want to change the name, make sure the name in AAD manifest is the same with the name defined here. + generateClientSecret: true # If the value is false, the action will not generate client secret for you + signInAudience: "AzureADMultipleOrgs" # Multitenant + writeToEnvironmentFile: # Write the information of created resources into environment file for the specified environment variable(s). + clientId: AAD_APP_CLIENT_ID + clientSecret: SECRET_AAD_APP_CLIENT_SECRET # Environment variable that starts with `SECRET_` will be stored to the .env.{envName}.user environment file + objectId: AAD_APP_OBJECT_ID + tenantId: AAD_APP_TENANT_ID + authority: AAD_APP_OAUTH_AUTHORITY + authorityHost: AAD_APP_OAUTH_AUTHORITY_HOST + + # Creates a Teams app + - uses: teamsApp/create + with: + # Teams app name + name: teamsConversationBot-${{TEAMSFX_ENV}} + # 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: ./appPackage/manifest.json + + # Build Teams app package with latest env value + - uses: teamsApp/zipAppPackage + with: + # Path to manifest template + manifestPath: ./appPackage/manifest.json + outputZipPath: ./appPackage/build/appPackage.${{TEAMSFX_ENV}}.zip + outputJsonPath: ./appPackage/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: ./appPackage/build/appPackage.${{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: ./appPackage/build/appPackage.${{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/bot-conversation-python/teamsapp.yml b/bot-conversation-python/teamsapp.yml new file mode 100644 index 00000000..991ae7b5 --- /dev/null +++ b/bot-conversation-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-conversation-python + +environmentFolderPath: ./env