diff --git a/msgext-search-python/.gitignore b/msgext-search-python/.gitignore new file mode 100644 index 00000000..1954bc87 --- /dev/null +++ b/msgext-search-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/msgext-search-python/.vscode/extensions.json b/msgext-search-python/.vscode/extensions.json new file mode 100644 index 00000000..bf8c33db --- /dev/null +++ b/msgext-search-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/msgext-search-python/.vscode/launch.json b/msgext-search-python/.vscode/launch.json new file mode 100644 index 00000000..b0f13538 --- /dev/null +++ b/msgext-search-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 + } + ] +} \ No newline at end of file diff --git a/msgext-search-python/.vscode/settings.json b/msgext-search-python/.vscode/settings.json new file mode 100644 index 00000000..2e7a56f7 --- /dev/null +++ b/msgext-search-python/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "debug.onTaskErrors": "abort" +} \ No newline at end of file diff --git a/msgext-search-python/.vscode/tasks.json b/msgext-search-python/.vscode/tasks.json new file mode 100644 index 00000000..2161094d --- /dev/null +++ b/msgext-search-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/msgext-search-python/Images/1-add-ME.png b/msgext-search-python/Images/1-add-ME.png new file mode 100644 index 00000000..0231c3f6 Binary files /dev/null and b/msgext-search-python/Images/1-add-ME.png differ diff --git a/msgext-search-python/Images/1.PNG b/msgext-search-python/Images/1.PNG new file mode 100644 index 00000000..f99e52b1 Binary files /dev/null and b/msgext-search-python/Images/1.PNG differ diff --git a/msgext-search-python/Images/10-mention-Search-SelectedItem.png b/msgext-search-python/Images/10-mention-Search-SelectedItem.png new file mode 100644 index 00000000..50c0fe03 Binary files /dev/null and b/msgext-search-python/Images/10-mention-Search-SelectedItem.png differ diff --git a/msgext-search-python/Images/3-Open-ME.png b/msgext-search-python/Images/3-Open-ME.png new file mode 100644 index 00000000..b484b298 Binary files /dev/null and b/msgext-search-python/Images/3-Open-ME.png differ diff --git a/msgext-search-python/Images/4-Opened-ME.png b/msgext-search-python/Images/4-Opened-ME.png new file mode 100644 index 00000000..9aa0cbb8 Binary files /dev/null and b/msgext-search-python/Images/4-Opened-ME.png differ diff --git a/msgext-search-python/Images/5-search-Result-ME.png b/msgext-search-python/Images/5-search-Result-ME.png new file mode 100644 index 00000000..5b28909a Binary files /dev/null and b/msgext-search-python/Images/5-search-Result-ME.png differ diff --git a/msgext-search-python/Images/6-selected-Item-ME.png b/msgext-search-python/Images/6-selected-Item-ME.png new file mode 100644 index 00000000..45055b96 Binary files /dev/null and b/msgext-search-python/Images/6-selected-Item-ME.png differ diff --git a/msgext-search-python/Images/7-posted-Item-ME.png b/msgext-search-python/Images/7-posted-Item-ME.png new file mode 100644 index 00000000..7f51964c Binary files /dev/null and b/msgext-search-python/Images/7-posted-Item-ME.png differ diff --git a/msgext-search-python/Images/8-mention-Search-CommandBar.png b/msgext-search-python/Images/8-mention-Search-CommandBar.png new file mode 100644 index 00000000..78a28328 Binary files /dev/null and b/msgext-search-python/Images/8-mention-Search-CommandBar.png differ diff --git a/msgext-search-python/Images/9-mention-Search-Result.png b/msgext-search-python/Images/9-mention-Search-Result.png new file mode 100644 index 00000000..3b87e18a Binary files /dev/null and b/msgext-search-python/Images/9-mention-Search-Result.png differ diff --git a/msgext-search-python/Images/msgext-search.gif b/msgext-search-python/Images/msgext-search.gif new file mode 100644 index 00000000..b9ce73b7 Binary files /dev/null and b/msgext-search-python/Images/msgext-search.gif differ diff --git a/msgext-search-python/README.md b/msgext-search-python/README.md new file mode 100644 index 00000000..70caf778 --- /dev/null +++ b/msgext-search-python/README.md @@ -0,0 +1,123 @@ +--- +page_type: sample +description: This sample app demonstrate how to use Messaging Extensions Search +products: +- office-teams +- office +- office-365 +languages: +- python +extensions: + contentType: samples + createdDate: "12-12-2019 13:38:25" +urlFragment: officedev-microsoft-teams-samples-bot-message-extension-python + +--- + +# Teams Messaging Extensions Search + +[Messaging Extensions](https://docs.microsoft.com/microsoftteams/platform/messaging-extensions/what-are-messaging-extensions) are a special kind of Microsoft Teams application that is support by the [Bot Framework](https://dev.botframework.com) v4. + +There are two basic types of Messaging Extension in Teams: [Search-based](https://docs.microsoft.com/microsoftteams/platform/messaging-extensions/how-to/search-commands/define-search-command) and [Action-based](https://docs.microsoft.com/microsoftteams/platform/messaging-extensions/how-to/action-commands/define-action-command). This sample illustrates how to +build a Search-based Messaging Extension. + +## Included Features +* Bots +* Message Extensions +* Search Commands + +## Interaction with Messaging Extension +![msgext-search ](Images/msgext-search.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 Messaging Extensions Search:** [Manifest](/samples/msgext-search/csharp/demo-manifest/msgext-search.zip) + +## Prerequisites + +- Microsoft Teams is installed and you have an account +- [Python SDK](https://www.python.org/downloads/) version 3.7 +- [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 + ``` + +1) 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 + ``` + +1) 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 tunnelling 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) + +1) Bring up a terminal, navigate to `Microsoft-Teams-Samples\samples\msgext-search\python` folder + +1) Activate your desired virtual environment + +1) Install dependencies by running ```pip install -r requirements.txt``` in the project folder. + +1) 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.) + +1) __*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") + +1) Run your bot with `python app.py` + +## Interacting with the bot in Teams + +> Note this `manifest.json` specified that the feature will be available from both the `compose` and `commandBox` areas of Teams. Please refer to Teams documentation for more details. + +In Teams, the command bar is located at the top of the window. When you at mention the bot what you type is forwarded (as you type) to the bot for processing. By way of illustration, this sample uses the text it receives to query the NuGet package store. + +There is a secondary, drill down, event illustrated in this sample: clicking on the results from the initial query will result in the bot receiving another event. + +## 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 + +- [Search based messaging extension](https://learn.microsoft.com/microsoftteams/platform/messaging-extensions/how-to/search-commands/define-search-command) +- [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) + + \ No newline at end of file diff --git a/msgext-search-python/app.py b/msgext-search-python/app.py new file mode 100644 index 00000000..354d0ef5 --- /dev/null +++ b/msgext-search-python/app.py @@ -0,0 +1,89 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import sys +import traceback +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 SearchBasedMessagingExtension +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 + +# Create the Bot +BOT = SearchBasedMessagingExtension() + + +# 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/msgext-search-python/appPackage/color.png b/msgext-search-python/appPackage/color.png new file mode 100644 index 00000000..325ebe2f Binary files /dev/null and b/msgext-search-python/appPackage/color.png differ diff --git a/msgext-search-python/appPackage/manifest.json b/msgext-search-python/appPackage/manifest.json new file mode 100644 index 00000000..8f445e04 --- /dev/null +++ b/msgext-search-python/appPackage/manifest.json @@ -0,0 +1,49 @@ +{ + "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.14/MicrosoftTeams.schema.json", + "manifestVersion": "1.14", + "version": "1.0", + "id": "${{TEAMS_APP_ID}}", + "packageName": "com.microsoft.teams.samples.searchExtension", + "developer": { + "name": "Microsoft Corp", + "websiteUrl": "https://example.azurewebsites.net", + "privacyUrl": "https://example.azurewebsites.net/privacy", + "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse" + }, + "name": { + "short": "search-extension-settings", + "full": "Microsoft Teams V4 Search Messaging Extension Bot and settings" + }, + "description": { + "short": "Microsoft Teams V4 Search Messaging Extension Bot and settings", + "full": "Sample Search Messaging Extension Bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK" + }, + "icons": { + "outline": "outline.png", + "color": "color.png" + }, + "accentColor": "#abcdef", + "composeExtensions": [ + { + "botId": "${{AAD_APP_CLIENT_ID}}", + "canUpdateConfiguration": true, + "commands": [ + { + "id": "searchQuery", + "context": [ "compose", "commandBox" ], + "description": "Test command to run query", + "title": "Search", + "type": "query", + "parameters": [ + { + "name": "searchQuery", + "title": "Search Query", + "description": "Your search query", + "inputType": "text" + } + ] + } + ] + } + ] + } \ No newline at end of file diff --git a/msgext-search-python/appPackage/outline.png b/msgext-search-python/appPackage/outline.png new file mode 100644 index 00000000..736aeb92 Binary files /dev/null and b/msgext-search-python/appPackage/outline.png differ diff --git a/msgext-search-python/assets/sample.json b/msgext-search-python/assets/sample.json new file mode 100644 index 00000000..41371c40 --- /dev/null +++ b/msgext-search-python/assets/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-msgext-search-python", + "source": "officeDev", + "title": "Search Based Messaging Extension", + "shortDescription": "This sample app demonstrate how to use search based Messaging Extension", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/msgext-search/python", + "longDescription": [ + "This sample app demonstrate how to use search based Messaging Extension" + ], + "creationDateTime": "2019-10-17", + "updateDateTime": "2022-10-05", + "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": "ME" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/msgext-search/python/Images/msgext-search.jpg", + "alt": "Solution UX showing search based messaging extension" + } + ], + "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/msgext-search-python/bots/__init__.py b/msgext-search-python/bots/__init__.py new file mode 100644 index 00000000..d35ade2a --- /dev/null +++ b/msgext-search-python/bots/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from .search_based_messaging_extension import SearchBasedMessagingExtension + +__all__ = ["SearchBasedMessagingExtension"] diff --git a/msgext-search-python/bots/search_based_messaging_extension.py b/msgext-search-python/bots/search_based_messaging_extension.py new file mode 100644 index 00000000..bdbce9db --- /dev/null +++ b/msgext-search-python/bots/search_based_messaging_extension.py @@ -0,0 +1,80 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import requests + +from botbuilder.core import CardFactory, MessageFactory, TurnContext +from botbuilder.schema import HeroCard, CardAction +from botbuilder.schema.teams import ( + MessagingExtensionAttachment, + MessagingExtensionQuery, + MessagingExtensionResult, + MessagingExtensionResponse, +) +from botbuilder.core.teams import TeamsActivityHandler + + +class SearchBasedMessagingExtension(TeamsActivityHandler): + async def on_teams_messaging_extension_query( + self, turn_context: TurnContext, query: MessagingExtensionQuery + ): + search_query = str(query.parameters[0].value).strip() + if search_query == "": + await turn_context.send_activity( + MessageFactory.text("You cannot enter a blank string for the search") + ) + return + + search_results = self._get_search_results(search_query) + + attachments = [] + for obj in search_results: + hero_card = HeroCard( + title=obj["name"], tap=CardAction(type="invoke", value=obj) + ) + + attachment = MessagingExtensionAttachment( + content_type=CardFactory.content_types.hero_card, + content=HeroCard(title=obj["name"]), + preview=CardFactory.hero_card(hero_card), + ) + attachments.append(attachment) + return MessagingExtensionResponse( + compose_extension=MessagingExtensionResult( + type="result", attachment_layout="list", attachments=attachments + ) + ) + + async def on_teams_messaging_extension_select_item( + self, turn_context: TurnContext, query + ) -> MessagingExtensionResponse: + hero_card = HeroCard( + title=query["name"], + subtitle=query["summary"], + buttons=[ + CardAction( + type="openUrl", value=query['url'] + ) + ], + ) + attachment = MessagingExtensionAttachment( + content_type=CardFactory.content_types.hero_card, content=hero_card + ) + + return MessagingExtensionResponse( + compose_extension=MessagingExtensionResult( + type="result", attachment_layout="list", attachments=[attachment] + ) + ) + + def _get_search_results(self, query: str): + url = f"https://api.github.com/search/repositories?q={query}" + headers = {"Accept": "application/vnd.github.v3+json"} + response = requests.get(url, headers=headers) + search_results = [] + for result in response.json()["items"]: + name = result["name"] + description = result["description"] + url = result["html_url"] + search_results.append({"name": name, "summary": description, "url": url}) + return search_results[:10] if len(search_results) > 10 else search_results diff --git a/msgext-search-python/config.py b/msgext-search-python/config.py new file mode 100644 index 00000000..e24a3521 --- /dev/null +++ b/msgext-search-python/config.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import os + + +class DefaultConfig: + """ Bot Configuration """ + + PORT = 3978 + APP_ID = os.environ.get("MicrosoftAppId", "<>") + APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "<>") diff --git a/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json b/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json new file mode 100644 index 00000000..cc1800c0 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json b/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-BotApp-with-rg.json new file mode 100644 index 00000000..54a7d628 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/readme.md b/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/readme.md new file mode 100644 index 00000000..c86cbf9d --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json b/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json new file mode 100644 index 00000000..60c9c1bb --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json b/msgext-search-python/deploymentTemplates/deployUseExistResourceGroup/template-BotApp-with-rg.json new file mode 100644 index 00000000..3a44abf2 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json b/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json new file mode 100644 index 00000000..f1806181 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json b/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-BotApp-new-rg.json new file mode 100644 index 00000000..f3f07b49 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/readme.md b/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/readme.md new file mode 100644 index 00000000..dbdfabf9 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json b/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/template-AzureBot-new-rg.json new file mode 100644 index 00000000..927307e0 --- /dev/null +++ b/msgext-search-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/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json b/msgext-search-python/deploymentTemplates/deployWithNewResourceGroup/template-BotApp-new-rg.json new file mode 100644 index 00000000..612112a3 --- /dev/null +++ b/msgext-search-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/msgext-search-python/env/.env.dev b/msgext-search-python/env/.env.dev new file mode 100644 index 00000000..1d95a988 --- /dev/null +++ b/msgext-search-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/msgext-search-python/env/.env.local b/msgext-search-python/env/.env.local new file mode 100644 index 00000000..241211d0 --- /dev/null +++ b/msgext-search-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/msgext-search-python/infra/azure.bicep b/msgext-search-python/infra/azure.bicep new file mode 100644 index 00000000..8734cb54 --- /dev/null +++ b/msgext-search-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/msgext-search-python/infra/azure.parameters.json b/msgext-search-python/infra/azure.parameters.json new file mode 100644 index 00000000..569d0df8 --- /dev/null +++ b/msgext-search-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": "msgext-search" + } + } + } \ No newline at end of file diff --git a/msgext-search-python/requirements.txt b/msgext-search-python/requirements.txt new file mode 100644 index 00000000..94b912a5 --- /dev/null +++ b/msgext-search-python/requirements.txt @@ -0,0 +1,2 @@ +botbuilder-integration-aiohttp>=4.14.5 +requests==2.31.0 diff --git a/msgext-search-python/sample.json b/msgext-search-python/sample.json new file mode 100644 index 00000000..95293757 --- /dev/null +++ b/msgext-search-python/sample.json @@ -0,0 +1,68 @@ +[ + { + "name": "officedev-microsoft-teams-samples-msgext-link-unfurling-python", + "source": "officeDev", + "title": "Link Unfurling in Messaging Extension using Bot Framework v4", + "shortDescription": "This sample app demonstrate how to use link unfurling in Messaging Extension using Bot Framework v4", + "url": "https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/msgext-link-unfurling/python", + "longDescription": [ + "This sample app demonstrate how to use link unfurling in Messaging Extension using Bot Framework v4" + ], + "creationDateTime": "2019-10-17", + "updateDateTime": "2022-09-22", + "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": "ME" + } + ], + "thumbnails": [ + { + "type": "image", + "order": 100, + "url": "https://raw.githubusercontent.com/OfficeDev/Microsoft-Teams-Samples/main/samples/msgext-link-unfurling/python/Images/msgextunfurling.png", + "alt": "Solution UX showing Link Unfurling in Messaging Extension using Bot Framework v4" + } + ], + "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/msgext-search-python/teamsapp.local.yml b/msgext-search-python/teamsapp.local.yml new file mode 100644 index 00000000..4d39db65 --- /dev/null +++ b/msgext-search-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:msgext-search-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: msgext-search-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: msgext-search-${{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/msgext-search-python/teamsapp.yml b/msgext-search-python/teamsapp.yml new file mode 100644 index 00000000..baf04f76 --- /dev/null +++ b/msgext-search-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:msgext-search-python + +environmentFolderPath: ./env \ No newline at end of file