diff --git a/dpytools/slack/slack.py b/dpytools/slack/slack.py index dc826c5..13eb617 100644 --- a/dpytools/slack/slack.py +++ b/dpytools/slack/slack.py @@ -1,14 +1,31 @@ +import logging +from dpytools.http_clients.base import BaseHttpClient class SlackNotifier: - def __init__(self): - # Set a webhok via an env var, ask Mike for a - #web hook url. - ... - - def notify(self, msg: str): - # Check formatting options for messages to slack. - # From memory you style it via sending a dictionary. - # It's a post request so do use the http client - # we've developing elsewhere in this library. - ... \ No newline at end of file + def __init__(self, webhook_url): + if not webhook_url: + raise ValueError('webhook_url is not set') + self.webhook_url = webhook_url + self.http_client = BaseHttpClient() + + def notify(self, msg_dict: dict): + """ + Send a message to the Slack webhook. + + The msg_dict parameter should be a dictionary that matches the + structure documented at https://api.slack.com/messaging/webhooks + """ + try: + response = self.http_client.post(self.webhook_url, json=msg_dict) + response.raise_for_status() + except Exception as e: + logging.error(f'Failed to send notification: {e}') + + def msg_str(self, msg: str): + """ + Send a string message to the Slack webhook. + + The msg parameter is wrapped into a dictionary before being sent. + """ + self.notify({'text': msg}) \ No newline at end of file diff --git a/tests/test_slack.py b/tests/test_slack.py new file mode 100644 index 0000000..32b85db --- /dev/null +++ b/tests/test_slack.py @@ -0,0 +1,35 @@ +import pytest +from unittest.mock import patch, MagicMock +from requests import HTTPError, Response +from dpytools.http_clients.base import BaseHttpClient +from dpytools.slack.slack import SlackNotifier + +@patch.object(BaseHttpClient, 'post') +def test_notify(mock_post): + """ + Test that the notify method sends a POST request + """ + webhook_url = 'http://example.com' + mock_response = MagicMock(Response) + mock_response.status_code = 200 + mock_post.return_value = mock_response + + notifier = SlackNotifier(webhook_url) + notifier.notify({'text': 'Test message'}) + + mock_post.assert_called_once_with(webhook_url, json={'text': 'Test message'}) + +@patch.object(BaseHttpClient, 'post') +def test_msg_str(mock_post): + """ + Test that the msg_str method sends a POST request with a string message + """ + webhook_url = 'http://example.com' + mock_response = MagicMock(Response) + mock_response.status_code = 200 + mock_post.return_value = mock_response + + notifier = SlackNotifier(webhook_url) + notifier.msg_str('Test message') + + mock_post.assert_called_once_with(webhook_url, json={'text': 'Test message'}) \ No newline at end of file