Skip to content
Merged
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
39 changes: 28 additions & 11 deletions dpytools/slack/slack.py
Original file line number Diff line number Diff line change
@@ -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.
...
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})
35 changes: 35 additions & 0 deletions tests/test_slack.py
Original file line number Diff line number Diff line change
@@ -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'})