Skip to content

Commit

Permalink
feat: get slack user's email
Browse files Browse the repository at this point in the history
  • Loading branch information
gcharest authored Apr 17, 2024
1 parent f401ced commit 927150c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
18 changes: 17 additions & 1 deletion app/integrations/slack/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]+$"

Expand Down Expand Up @@ -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
"""
Expand Down
23 changes: 23 additions & 0 deletions app/tests/integrations/slack/test_users.py
Original file line number Diff line number Diff line change
@@ -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():
Expand Down Expand Up @@ -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": "[email protected]"}},
}
body = {"user_id": "U1234"}
assert users.get_user_email(client, body) == "[email protected]"

# 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

0 comments on commit 927150c

Please sign in to comment.