Skip to content

Commit 1307140

Browse files
Merge pull request #1481 from OfficeDev/v-mfurquan/python-conversion-bot-message-reaction
Conversion Bot Message Reaction To Python
2 parents 12cec09 + 3d8b3ec commit 1307140

33 files changed

+838
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# TeamsFx files
2+
env/.env.*.user
3+
env/.env.local
4+
appManifest/build/
5+
6+
# python virtual environment
7+
.venv/
8+
9+
# misc
10+
.env
11+
.deployment/
12+
13+
# tmp files
14+
__pycache__/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"recommendations": [
3+
"TeamsDevApp.ms-teams-vscode-extension",
4+
"ms-python.python",
5+
]
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
"name": "Launch App (Edge)",
6+
"type": "msedge",
7+
"request": "launch",
8+
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
9+
"cascadeTerminateToConfigurations": [
10+
"Python: Run App Locally"
11+
],
12+
"presentation": {
13+
"group": "all",
14+
"hidden": true
15+
},
16+
"internalConsoleOptions": "neverOpen"
17+
},
18+
{
19+
"name": "Launch App (Chrome)",
20+
"type": "chrome",
21+
"request": "launch",
22+
"url": "https://teams.microsoft.com/l/app/${{local:TEAMS_APP_ID}}?installAppPackage=true&webjoin=true&${account-hint}",
23+
"cascadeTerminateToConfigurations": [
24+
"Python: Run App Locally"
25+
],
26+
"presentation": {
27+
"group": "all",
28+
"hidden": true
29+
},
30+
"internalConsoleOptions": "neverOpen"
31+
},
32+
{
33+
"name": "Python: Run App Locally",
34+
"type": "debugpy",
35+
"request": "launch",
36+
"program": "${workspaceFolder}/app.py",
37+
"cwd": "${workspaceFolder}",
38+
"console": "integratedTerminal"
39+
}
40+
],
41+
"compounds": [
42+
{
43+
"name": "Debug (Edge)",
44+
"configurations": [
45+
"Launch App (Edge)",
46+
"Python: Run App Locally"
47+
],
48+
"preLaunchTask": "Prepare Teams App Resources",
49+
"presentation": {
50+
"group": "all",
51+
"order": 1
52+
},
53+
"stopAll": true
54+
},
55+
{
56+
"name": "Debug (Chrome)",
57+
"configurations": [
58+
"Launch App (Chrome)",
59+
"Python: Run App Locally"
60+
],
61+
"preLaunchTask": "Prepare Teams App Resources",
62+
"presentation": {
63+
"group": "all",
64+
"order": 2
65+
},
66+
"stopAll": true
67+
}
68+
]
69+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"debug.onTaskErrors": "abort"
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// This file is automatically generated by Teams Toolkit.
2+
// The teamsfx tasks defined in this file require Teams Toolkit version >= 5.0.0.
3+
// See https://aka.ms/teamsfx-tasks for details on how to customize each task.
4+
{
5+
"version": "2.0.0",
6+
"tasks": [
7+
{
8+
"label": "Prepare Teams App Resources",
9+
"dependsOn": [
10+
"Validate prerequisites",
11+
"Start local tunnel",
12+
"Provision",
13+
"Deploy"
14+
],
15+
"dependsOrder": "sequence"
16+
},
17+
{
18+
// Check all required prerequisites.
19+
// See https://aka.ms/teamsfx-tasks/check-prerequisites to know the details and how to customize the args.
20+
"label": "Validate prerequisites",
21+
"type": "teamsfx",
22+
"command": "debug-check-prerequisites",
23+
"args": {
24+
"prerequisites": [
25+
"m365Account", // Sign-in prompt for Microsoft 365 account, then validate if the account enables the sideloading permission.
26+
"portOccupancy" // Validate available ports to ensure those debug ones are not occupied.
27+
],
28+
"portOccupancy": [
29+
3978, // app service port
30+
]
31+
}
32+
},
33+
{
34+
// Start the local tunnel service to forward public URL to local port and inspect traffic.
35+
// See https://aka.ms/teamsfx-tasks/local-tunnel for the detailed args definitions.
36+
"label": "Start local tunnel",
37+
"type": "teamsfx",
38+
"command": "debug-start-local-tunnel",
39+
"args": {
40+
"type": "dev-tunnel",
41+
"ports": [
42+
{
43+
"portNumber": 3978,
44+
"protocol": "http",
45+
"access": "public",
46+
"writeToEnvironmentFile": {
47+
"endpoint": "BOT_ENDPOINT", // output tunnel endpoint as BOT_ENDPOINT
48+
"domain": "BOT_DOMAIN" // output tunnel domain as BOT_DOMAIN
49+
}
50+
}
51+
],
52+
"env": "local"
53+
},
54+
"isBackground": true,
55+
"problemMatcher": "$teamsfx-local-tunnel-watch"
56+
},
57+
{
58+
// Create the debug resources.
59+
// See https://aka.ms/teamsfx-tasks/provision to know the details and how to customize the args.
60+
"label": "Provision",
61+
"type": "teamsfx",
62+
"command": "provision",
63+
"args": {
64+
"env": "local"
65+
}
66+
},
67+
{
68+
// Build project.
69+
// See https://aka.ms/teamsfx-tasks/deploy to know the details and how to customize the args.
70+
"label": "Deploy",
71+
"type": "teamsfx",
72+
"command": "deploy",
73+
"args": {
74+
"env": "local"
75+
}
76+
}
77+
]
78+
}
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
---
2+
page_type: sample
3+
description: This sample app demonstrates how to use message reactions in Microsoft Teams with a bot built on the Bot Framework.
4+
products:
5+
- office-teams
6+
- office
7+
- office-365
8+
languages:
9+
- Python
10+
extensions:
11+
contentType: samples
12+
createdDate: "2024-12-12"
13+
urlFragment: officedev-microsoft-teams-samples-bot-message-reaction-Python
14+
---
15+
16+
# Teams Message Reactions Bot Python Sample
17+
18+
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.
19+
20+
## Included Features
21+
* Bots
22+
* Message Reactions
23+
24+
## Interaction with bot
25+
![Message Reaction](Images/MessageReactions.gif)
26+
27+
## Try it yourself - experience the App in your Microsoft Teams client
28+
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)).
29+
30+
**Teams Message Reactions Bot:** [Manifest](/samples/bot-message-reaction/csharp/demo-manifest/bot-message-reaction.zip)
31+
32+
## Prerequisites
33+
34+
- Microsoft Teams is installed and you have an account
35+
- [Python SDK](https://www.python.org/downloads/) min version 3.8
36+
- [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
37+
- [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)
38+
39+
## Run the app (Using Teams Toolkit for Visual Studio Code)
40+
41+
The simplest way to run this sample in Teams is to use Teams Toolkit for Visual Studio Code.
42+
43+
1. Ensure you have downloaded and installed [Visual Studio Code](https://code.visualstudio.com/docs/setup/setup-overview)
44+
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)
45+
1. Select **File > Open Folder** in VS Code and choose this samples directory from the repo
46+
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.
47+
1. Using the extension, sign in with your Microsoft 365 account where you have permissions to upload custom apps
48+
1. Select **Debug > Start Debugging** or **F5** to run the app in a Teams web client.
49+
1. In the browser that launches, select the **Add** button to install the app to Teams.
50+
51+
> 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.
52+
53+
## Setup for bot
54+
55+
In Azure portal, create a [Azure Bot resource](https://docs.microsoft.com/azure/bot-service/bot-service-quickstart-registration).
56+
- For bot handle, make up a name.
57+
- Select "Use existing app registration" (Create the app registration in Microsoft Entra ID beforehand.)
58+
- __*If you don't have an Azure account*__ create an [Azure free account here](https://azure.microsoft.com/free/)
59+
60+
In the new Azure Bot resource in the Portal,
61+
- Ensure that you've [enabled the Teams Channel](https://learn.microsoft.com/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
62+
- 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`
63+
64+
## Run the app (Manually Uploading to Teams)
65+
## Setup for code
66+
> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
67+
the Teams service needs to call into the bot.
68+
69+
1) Clone the repository
70+
71+
```bash
72+
git clone https://github.com/OfficeDev/Microsoft-Teams-Samples.git
73+
```
74+
75+
2) Run ngrok - point to port 3978
76+
77+
```bash
78+
ngrok http 3978 --host-header="localhost:3978"
79+
```
80+
81+
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:
82+
83+
```bash
84+
devtunnel host -p 3978 --allow-anonymous
85+
```
86+
87+
3) In a terminal, navigate to `samples/bot-message-reaction/Python`
88+
89+
4) Activate your desired virtual environment
90+
91+
5) Install dependencies by running ```pip install -r requirements.txt``` in the project folder.
92+
93+
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.)
94+
95+
7) __*This step is specific to Teams.*__
96+
- **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`)
97+
- **Zip** up the contents of the `appManifest` folder to create a `manifest.zip`
98+
- **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")
99+
100+
8) Run your bot with `python app.py`
101+
102+
## Running the sample
103+
104+
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.
105+
106+
- **App Installation:**
107+
![App Installation ](Images/1.InstallApp.png)
108+
109+
- **Personal Scope Interactions:**
110+
![personalScope-AddApp ](Images/2.PersonalScope_Echo_Bot.png)
111+
112+
![personalScope-AddApp ](Images/3.PersonalScope_AddedLikeToHelloMsg.png)
113+
114+
![personalScope-Interaction ](Images/4.PersonalScope_AddedSurpriseToWelcomeMsg.png)
115+
116+
- **Group Chat Scope Interactions:**
117+
![groupChat-Interaction ](Images/5.GroupChat-EchoBot.png)
118+
119+
![groupChat-Interaction ](Images/6.GroupChat_LikeReaction.png)
120+
121+
![groupChat-Interaction ](Images/7.GroupChat_Like_Angry_Reaction.png)
122+
123+
![groupChat-Interaction ](Images/8.Remove_Reaction_Notification.png)
124+
125+
- **Team Scope Interactions:**
126+
![Team-Interaction ](Images/9.Install_To_Teams.png)
127+
128+
![Team-Interaction ](Images/10.Teams_EchoBot.png)
129+
130+
![Team-Interaction ](Images/11.Teams_AddedHeartToMsg.png)
131+
132+
## Deploy the bot to Azure
133+
134+
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.
135+
136+
## Further reading
137+
138+
- [Bot Framework Documentation](https://docs.botframework.com)
139+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
140+
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
141+
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
142+
- [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)
143+
144+
145+
<img src="https://pnptelemetry.azurewebsites.net/microsoft-teams-samples/samples/bot-message-reaction-Python" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
class ActivityLog:
5+
# Constructor to initialize the ActivityLog class with a storage object.
6+
def __init__(self, storage):
7+
self._storage = storage # The storage object is used for storing and retrieving activities.
8+
9+
# Asynchronous method to append an activity to the log.
10+
async def append(self, activity_id, activity):
11+
# Check if activity_id is provided; raise an error if not.
12+
if activity_id is None:
13+
raise TypeError('activity_id is required for ActivityLog.append')
14+
15+
# Check if activity is provided; raise an error if not.
16+
if activity is None:
17+
raise TypeError('activity is required for ActivityLog.append')
18+
19+
# Create an object to store the activity with the activity_id as the key.
20+
obj = {activity_id: {"activity": activity}}
21+
22+
# Use the storage's write method to save the activity.
23+
await self._storage.write(obj)
24+
25+
# Asynchronous method to find and retrieve an activity from the log by its ID.
26+
async def find(self, activity_id):
27+
# Check if activity_id is provided; raise an error if not.
28+
if activity_id is None:
29+
raise TypeError('activity_id is required for ActivityLog.find')
30+
31+
# Use the storage's read method to fetch the activity by its ID.
32+
# The read method is expected to return a dictionary where keys are IDs and values are the stored objects.
33+
items = await self._storage.read([activity_id])
34+
35+
# Retrieve the activity from the fetched data if it exists, otherwise return None.
36+
return items.get(activity_id, {}).get("activity") if items else None
37+

0 commit comments

Comments
 (0)