Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Slack notifier #26

Merged
merged 1 commit into from
Apr 22, 2021
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
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,22 @@ SENDER="sender@example.com" SENDER_NAME="ChiaDog" RECIPIENT="you@example.com" HO

```

### Slack, WhatsApp, ...?
### Slack

[Slack](https://slack.com/) apps are a simple way to get notifications in a channel in your Slack workspace. Follow the instructions for *Creating an App* on the [Getting started with Incoming Webhooks](https://api.slack.com/messaging/webhooks#getting_started) guide.

Copy & paste the Webhook URL into your `config.yaml`, that's it!

- **Costs**: $0
- **Advantages**: Easy setup

You can test if the setup works correctly with:

```
SLACK_WEBHOOK_URL=<webhook_url> python3 -m unittest tests.notifier.test_slack_notifier
```

### WhatsApp, ...?

These integrations can be easily added. Contributions are welcome!

Expand Down
3 changes: 3 additions & 0 deletions config-example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,6 @@ notifier:
discord:
enable: false
webhook_url: 'https://discord.com/api/webhooks/...'
slack:
enable: false
webhook_url: 'https://hooks.slack.com/services/...'
2 changes: 2 additions & 0 deletions src/notifier/notify_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .smtp_notifier import SMTPNotifier
from .telegram_notifier import TelegramNotifier
from .discord_notifier import DiscordNotifier
from .slack_notifier import SlackNotifier
from src.config import Config


Expand All @@ -34,6 +35,7 @@ def _initialize_notifiers(self):
"telegram": TelegramNotifier,
"discord": DiscordNotifier,
"smtp": SMTPNotifier,
"slack": SlackNotifier,
}
for key in self._config.keys():
if key not in key_notifier_mapping.keys():
Expand Down
52 changes: 52 additions & 0 deletions src/notifier/slack_notifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# std
import http.client
import logging
import json
import urllib.parse
from typing import List

# project
from . import Notifier, Event, EventType


class SlackNotifier(Notifier):
def __init__(self, title_prefix: str, config: dict):
logging.info("Initializing Slack notifier.")
super().__init__(title_prefix, config)
try:
self.webhook_url = config["webhook_url"]
except KeyError as key:
logging.error(f"Invalid config.yaml. Missing key: {key}")

def send_events_to_user(self, events: List[Event]) -> bool:
errors = False
for event in events:
if event.type == EventType.USER:
priority = ""

if event.priority == event.priority.HIGH:
priority = "🚨"
elif event.priority == event.priority.NORMAL:
priority = "⚠️"

request_body = json.dumps(
{
"text": f"{priority} *{self._title_prefix} {event.service.name}*\n{event.message}",
}
)

o = urllib.parse.urlparse(self.webhook_url)
conn = http.client.HTTPSConnection(o.netloc)
conn.request(
"POST",
o.path,
request_body,
{"Content-type": "application/json"},
)
response = conn.getresponse()
if response.getcode() != 200:
logging.warning(f"Problem sending event to user, code: {response.getcode()}")
errors = True
conn.close()

return errors
74 changes: 74 additions & 0 deletions tests/notifier/test_slack_notifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# std
import os
import unittest

# project
from src.notifier import Event, EventType, EventPriority, EventService
from src.notifier.slack_notifier import SlackNotifier


class TestSlackNotifier(unittest.TestCase):
def setUp(self) -> None:
webhook_url = os.getenv("SLACK_WEBHOOK_URL")
self.assertIsNotNone(webhook_url, "You must export SLACK_WEBHOOK_URL as env variable")
self.notifier = SlackNotifier(title_prefix="Test", config={"enable": True, "webhook_url": webhook_url})

@unittest.skipUnless(os.getenv("SLACK_WEBHOOK_URL"), "Run only if webhook available")
def testSlackLowPriorityNotifications(self):
errors = self.notifier.send_events_to_user(
events=[
Event(
type=EventType.USER,
priority=EventPriority.LOW,
service=EventService.HARVESTER,
message="Low priority notification 1.",
),
Event(
type=EventType.USER,
priority=EventPriority.LOW,
service=EventService.HARVESTER,
message="Low priority notification 2.",
),
]
)
self.assertFalse(errors)

@unittest.skipUnless(os.getenv("SLACK_WEBHOOK_URL"), "Run only if webhook available")
def testSlackNormalPriorityNotifications(self):
errors = self.notifier.send_events_to_user(
events=[
Event(
type=EventType.USER,
priority=EventPriority.NORMAL,
service=EventService.HARVESTER,
message="Normal priority notification 1.",
),
Event(
type=EventType.USER,
priority=EventPriority.NORMAL,
service=EventService.HARVESTER,
message="Normal priority notification 2.",
),
]
)
self.assertFalse(errors)

@unittest.skipUnless(os.getenv("SLACK_WEBHOOK_URL"), "Run only if webhook available")
def testSlackHighPriorityNotifications(self):
errors = self.notifier.send_events_to_user(
events=[
Event(
type=EventType.USER,
priority=EventPriority.HIGH,
service=EventService.HARVESTER,
message="High priority notification 1.",
),
Event(
type=EventType.USER,
priority=EventPriority.HIGH,
service=EventService.HARVESTER,
message="High priority notification 2.",
),
]
)
self.assertFalse(errors)