Skip to content

Commit 018e7e6

Browse files
authoredApr 4, 2024··
Add send_slack_message() (#16)
* Add send_slack_message() * Add send_slack_message() * Fix type
1 parent 673fb84 commit 018e7e6

File tree

4 files changed

+220
-2
lines changed

4 files changed

+220
-2
lines changed
 

‎poetry.lock

+161-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pyhelper_utils/notifications.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from logging import Logger
2+
import requests
3+
import json
4+
5+
6+
def send_slack_message(
7+
message: str,
8+
webhook_url: str = None,
9+
logger: Logger = None,
10+
raise_on_error: bool = True,
11+
) -> None:
12+
"""
13+
Send slack message via slack webhook url.
14+
15+
Args:
16+
message (str): message to send.
17+
webhook_url (str): slack webhook url.
18+
logger (Logger): logger to use, if not passed no logs will be displayed.
19+
"""
20+
try:
21+
if webhook_url:
22+
slack_data = {"text": message}
23+
if logger:
24+
logger.info(f"Sending message to slack: {message}")
25+
26+
response = requests.post(
27+
webhook_url,
28+
data=json.dumps(slack_data),
29+
headers={"Content-Type": "application/json"},
30+
)
31+
if response.status_code != 200:
32+
if logger:
33+
logger.error(
34+
f"Request to slack returned an error {response.status_code} with the following message: {response.text}"
35+
)
36+
except Exception as ex:
37+
if logger:
38+
logger.error(f"Failed to send slack message. error: {ex}")
39+
40+
if raise_on_error:
41+
raise

‎pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ classifiers = [
4040
[tool.poetry.dependencies]
4141
python = "^3.8"
4242
python-simple-logger = "^1.0.19"
43+
requests = "^2.31.0"
4344

4445
[tool.poetry.group.tests.dependencies]
4546
pytest = "^8.1.1"

0 commit comments

Comments
 (0)
Please sign in to comment.