From 927150c78dcbaffd62713406a9ccd9238525840a Mon Sep 17 00:00:00 2001 From: Guillaume Charest <1690085+gcharest@users.noreply.github.com> Date: Wed, 17 Apr 2024 21:54:27 +0000 Subject: [PATCH] feat: get slack user's email --- app/integrations/slack/users.py | 18 ++++++++++++++++- app/tests/integrations/slack/test_users.py | 23 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/app/integrations/slack/users.py b/app/integrations/slack/users.py index ba4e488c..870736a3 100644 --- a/app/integrations/slack/users.py +++ b/app/integrations/slack/users.py @@ -3,6 +3,7 @@ This module contains the user related functionality for the Slack integration. """ import re +from slack_sdk import WebClient SLACK_USER_ID_REGEX = r"^[A-Z0-9]+$" @@ -33,7 +34,22 @@ def get_user_id_from_request(body): return match.group(0) -def get_user_locale(client, user_id=None): +def get_user_email(client: WebClient, body): + """ + Returns the user email from the body of a request, otherwise None. + Supports the following formats: + - user_id (Slack slash command) + - user (Slack Message, Modal, Block) + - event.user (Slack Event) + """ + user_id = get_user_id_from_request(body) + if user_id: + user_info = client.users_info(user=user_id) + if user_info["ok"]: + return user_info["user"]["profile"]["email"] + + +def get_user_locale(client: WebClient, user_id=None): """ Returns the user locale from a command's user_id if valid, "en-US" as default otherwise """ diff --git a/app/tests/integrations/slack/test_users.py b/app/tests/integrations/slack/test_users.py index 0aadddc9..71ae10eb 100644 --- a/app/tests/integrations/slack/test_users.py +++ b/app/tests/integrations/slack/test_users.py @@ -1,6 +1,7 @@ from unittest.mock import MagicMock from integrations.slack import users +from slack_sdk import WebClient def test_get_user_id_from_request_with_user_id(): @@ -127,3 +128,25 @@ def users_profile_get(user): message = "Hello, <@U1234> and <@U5678>! Welcome to the team. Also welcome <@U9101> and <@U1121>." expected_message = "Hello, @john_doe and @jane_smith! Welcome to the team. Also welcome @joe_smith and @jenn_smith." assert users.replace_user_id_with_handle(client, message) == expected_message + + +def test_get_user_email(): + # Mock the WebClient + client = MagicMock(spec=WebClient) + + # Test when the user ID is found in the request body and the users_info call is successful + client.users_info.return_value = { + "ok": True, + "user": {"profile": {"email": "test@example.com"}}, + } + body = {"user_id": "U1234"} + assert users.get_user_email(client, body) == "test@example.com" + + # Test when the user ID is not found in the request body + body = {} + assert users.get_user_email(client, body) is None + + # Test when the users_info call is not successful + client.users_info.return_value = {"ok": False} + body = {"user_id": "U1234"} + assert users.get_user_email(client, body) is None