Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversion Bot Message Reaction To Python #1481

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions samples/bot-message-reaction/python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# TeamsFx files
env/.env.*.user
env/.env.local
appManifest/build/

# python virtual environment
.venv/

# misc
.env
.deployment/

# tmp files
__pycache__/
6 changes: 6 additions & 0 deletions samples/bot-message-reaction/python/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"TeamsDevApp.ms-teams-vscode-extension",
"ms-python.python",
]
}
69 changes: 69 additions & 0 deletions samples/bot-message-reaction/python/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch App (Edge)",
"type": "msedge",
"request": "launch",
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
"cascadeTerminateToConfigurations": [
"Python: Run App Locally"
],
"presentation": {
"group": "all",
"hidden": true
},
"internalConsoleOptions": "neverOpen"
},
{
"name": "Launch App (Chrome)",
"type": "chrome",
"request": "launch",
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
"cascadeTerminateToConfigurations": [
"Python: Run App Locally"
],
"presentation": {
"group": "all",
"hidden": true
},
"internalConsoleOptions": "neverOpen"
},
{
"name": "Python: Run App Locally",
"type": "debugpy",
"request": "launch",
"program": "${workspaceFolder}/app.py",
"cwd": "${workspaceFolder}",
"console": "integratedTerminal"
}
],
"compounds": [
{
"name": "Debug (Edge)",
"configurations": [
"Launch App (Edge)",
"Python: Run App Locally"
],
"preLaunchTask": "Prepare Teams App Resources",
"presentation": {
"group": "all",
"order": 1
},
"stopAll": true
},
{
"name": "Debug (Chrome)",
"configurations": [
"Launch App (Chrome)",
"Python: Run App Locally"
],
"preLaunchTask": "Prepare Teams App Resources",
"presentation": {
"group": "all",
"order": 2
},
"stopAll": true
}
]
}
3 changes: 3 additions & 0 deletions samples/bot-message-reaction/python/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"debug.onTaskErrors": "abort"
}
78 changes: 78 additions & 0 deletions samples/bot-message-reaction/python/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
]
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
145 changes: 145 additions & 0 deletions samples/bot-message-reaction/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
---
page_type: sample
description: This sample app demonstrates how to use message reactions in Microsoft Teams with a bot built on the Bot Framework.
products:
- office-teams
- office
- office-365
languages:
- Python
extensions:
contentType: samples
createdDate: "2024-12-12"
urlFragment: officedev-microsoft-teams-samples-bot-message-reaction-Python
---

# Teams Message Reactions Bot Python Sample

This sample app demonstrates the implementation of message reactions in Microsoft Teams using the Bot Framework. The bot responds dynamically to reactions, supporting personal, group, and team scopes.

## Included Features
* Bots
* Message Reactions

## Interaction with bot
![Message Reaction](Images/MessageReactions.gif)

## Try it yourself - experience the App in your Microsoft Teams client
Please find below demo manifest which is deployed on Microsoft Azure and you can try it yourself by uploading the app package (.zip file link below) to your Teams and/or as a personal app. (Sideloading must be enabled for your tenant, [see steps here](https://docs.microsoft.com/microsoftteams/platform/concepts/build-and-test/prepare-your-o365-tenant#enable-custom-teams-apps-and-turn-on-custom-app-uploading)).

**Teams Message Reactions Bot:** [Manifest](/samples/bot-message-reaction/csharp/demo-manifest/bot-message-reaction.zip)
Copy link
Preview

Copilot AI Jan 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The link to the manifest file points to the C# version instead of the Python version. It should be corrected to avoid confusion.

Suggested change
**Teams Message Reactions Bot:** [Manifest](/samples/bot-message-reaction/csharp/demo-manifest/bot-message-reaction.zip)
**Teams Message Reactions Bot:** [Manifest](/samples/bot-message-reaction/python/demo-manifest/bot-message-reaction.zip)

Copilot is powered by AI, so mistakes are possible. Review output carefully before use.

Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
Copy link
Contributor Author

@Mohammed-MSFT Mohammed-MSFT Jan 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have demo manifest in chsarp so we added in nodejs same like this and also following same in python.


## Prerequisites

- Microsoft Teams is installed and you have an account
- [Python SDK](https://www.python.org/downloads/) min version 3.8
- [dev tunnel](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/get-started?tabs=windows) or [ngrok](https://ngrok.com/) latest version or equivalent tunnelling solution
- [Teams Toolkit for VS Code](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) or [TeamsFx CLI](https://learn.microsoft.com/microsoftteams/platform/toolkit/teamsfx-cli?pivots=version-one)

## Run the app (Using Teams Toolkit for Visual Studio Code)

The simplest way to run this sample in Teams is to use Teams Toolkit for Visual Studio Code.

1. Ensure you have downloaded and installed [Visual Studio Code](https://code.visualstudio.com/docs/setup/setup-overview)
1. Install the [Teams Toolkit extension](https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension) and [Python Extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
1. Select **File > Open Folder** in VS Code and choose this samples directory from the repo
1. Press **CTRL+Shift+P** to open the command box and enter **Python: Create Environment** to create and activate your desired virtual environment. Remember to select `requirements.txt` as dependencies to install when creating the virtual environment.
1. Using the extension, sign in with your Microsoft 365 account where you have permissions to upload custom apps
1. Select **Debug > Start Debugging** or **F5** to run the app in a Teams web client.
1. In the browser that launches, select the **Add** button to install the app to Teams.

> If you do not have permission to upload custom apps (sideloading), Teams Toolkit will recommend creating and using a Microsoft 365 Developer Program account - a free program to get your own dev environment sandbox that includes Teams.

## Setup for bot

In Azure portal, create a [Azure Bot resource](https://docs.microsoft.com/azure/bot-service/bot-service-quickstart-registration).
- For bot handle, make up a name.
- Select "Use existing app registration" (Create the app registration in Microsoft Entra ID beforehand.)
- __*If you don't have an Azure account*__ create an [Azure free account here](https://azure.microsoft.com/free/)

In the new Azure Bot resource in the Portal,
- Ensure that you've [enabled the Teams Channel](https://learn.microsoft.com/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
- In Settings/Configuration/Messaging endpoint, enter the current `https` URL you were given by running the tunneling application. Append it with the path `/api/messages`

## Run the app (Manually Uploading to Teams)
## Setup for code
> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
the Teams service needs to call into the bot.

1) Clone the repository

```bash
git clone https://github.com/OfficeDev/Microsoft-Teams-Samples.git
```

2) Run ngrok - point to port 3978

```bash
ngrok http 3978 --host-header="localhost:3978"
```

Alternatively, you can also use the `dev tunnels`. Please follow [Create and host a dev tunnel](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/get-started?tabs=windows) and host the tunnel with anonymous user access command as shown below:

```bash
devtunnel host -p 3978 --allow-anonymous
```

3) In a terminal, navigate to `samples/bot-message-reaction/Python`

4) Activate your desired virtual environment

5) Install dependencies by running ```pip install -r requirements.txt``` in the project folder.

6) Update the `config.py` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.)

7) __*This step is specific to Teams.*__
- **Edit** the `manifest.json` contained in the `appManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `${{AAD_APP_CLIENT_ID}}` and `${{TEAMS_APP_ID}}` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`)
- **Zip** up the contents of the `appManifest` folder to create a `manifest.zip`
- **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")

8) Run your bot with `python app.py`

## Running the sample

Message the bot and it will respond with an 'Echo: [your message]'. Add a message reaction to the bots response, and the bot will reply accordingly.

- **App Installation:**
![App Installation ](Images/1.InstallApp.png)

- **Personal Scope Interactions:**
![personalScope-AddApp ](Images/2.PersonalScope_Echo_Bot.png)

![personalScope-AddApp ](Images/3.PersonalScope_AddedLikeToHelloMsg.png)

![personalScope-Interaction ](Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png)

- **Group Chat Scope Interactions:**
![groupChat-Interaction ](Images/5.GroupChat-EchoBot.png)

![groupChat-Interaction ](Images/6.GroupChat_LikeReaction.png)

![groupChat-Interaction ](Images/7.GroupChat_Like_Angry_Reaction.png)

![groupChat-Interaction ](Images/8.Remove_Reaction_Notification.png)

- **Team Scope Interactions:**
![Team-Interaction ](Images/9.Install_To_Teams.png)

![Team-Interaction ](Images/10.Teams_EchoBot.png)

![Team-Interaction ](Images/11.Teams_AddedHeartToMsg.png)

## Deploy the bot to Azure

To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.

## Further reading

- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Teams Message Reaction Events](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/subscribe-to-conversation-events?tabs=dotnet#message-reaction-events)


<img src="https://pnptelemetry.azurewebsites.net/microsoft-teams-samples/samples/bot-message-reaction-Python" />
37 changes: 37 additions & 0 deletions samples/bot-message-reaction/python/activity_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

class ActivityLog:
# Constructor to initialize the ActivityLog class with a storage object.
def __init__(self, storage):
self._storage = storage # The storage object is used for storing and retrieving activities.

# Asynchronous method to append an activity to the log.
async def append(self, activity_id, activity):
# Check if activity_id is provided; raise an error if not.
if activity_id is None:
raise TypeError('activity_id is required for ActivityLog.append')

# Check if activity is provided; raise an error if not.
if activity is None:
raise TypeError('activity is required for ActivityLog.append')

# Create an object to store the activity with the activity_id as the key.
obj = {activity_id: {"activity": activity}}

# Use the storage's write method to save the activity.
await self._storage.write(obj)

# Asynchronous method to find and retrieve an activity from the log by its ID.
async def find(self, activity_id):
# Check if activity_id is provided; raise an error if not.
if activity_id is None:
raise TypeError('activity_id is required for ActivityLog.find')

# Use the storage's read method to fetch the activity by its ID.
# The read method is expected to return a dictionary where keys are IDs and values are the stored objects.
items = await self._storage.read([activity_id])

# Retrieve the activity from the fetched data if it exists, otherwise return None.
return items.get(activity_id, {}).get("activity") if items else None

Loading