notifox 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
notifox/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ from .client import NotifoxClient
2
+ from .exceptions import (
3
+ NotifoxAPIError,
4
+ NotifoxAuthenticationError,
5
+ NotifoxConnectionError,
6
+ NotifoxError,
7
+ NotifoxRateLimitError,
8
+ )
9
+
10
+ __all__ = [
11
+ "NotifoxClient",
12
+ "NotifoxError",
13
+ "NotifoxAPIError",
14
+ "NotifoxAuthenticationError",
15
+ "NotifoxRateLimitError",
16
+ "NotifoxConnectionError",
17
+ ]
18
+ __version__ = "0.1.1"
notifox/client.py ADDED
@@ -0,0 +1,182 @@
1
+ # notifox/client.py
2
+ import os
3
+ from typing import Any, Dict, Optional
4
+
5
+ import requests
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
8
+
9
+ from .exceptions import (
10
+ NotifoxAPIError,
11
+ NotifoxAuthenticationError,
12
+ NotifoxConnectionError,
13
+ NotifoxError,
14
+ NotifoxRateLimitError,
15
+ )
16
+
17
+
18
+ class NotifoxClient:
19
+ """
20
+ Python SDK for Notifox alerting API.
21
+
22
+ Examples:
23
+ client = NotifoxClient(api_key="your_api_key")
24
+ client.send_alert(audience="user1", alert="Server down!")
25
+
26
+ client = NotifoxClient() # Reads from NOTIFOX_API_KEY env var
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ api_key: Optional[str] = None,
32
+ base_url: str = "https://api.notifox.com",
33
+ timeout: float = 30.0,
34
+ max_retries: int = 3
35
+ ):
36
+ """
37
+ Initialize the Notifox client.
38
+
39
+ Args:
40
+ api_key: Your Notifox API key. If not provided, will attempt to read from
41
+ the NOTIFOX_API_KEY environment variable.
42
+ base_url: Base URL for the Notifox API. Defaults to https://api.notifox.com
43
+ timeout: Request timeout in seconds. Defaults to 30.0
44
+ max_retries: Maximum number of retries for failed requests. Defaults to 3
45
+ """
46
+ self.api_key = api_key or os.getenv("NOTIFOX_API_KEY")
47
+ if not self.api_key:
48
+ raise NotifoxError(
49
+ "API key is required. Provide it as an argument or set the "
50
+ "NOTIFOX_API_KEY environment variable."
51
+ )
52
+
53
+ self.base_url = base_url.rstrip("/")
54
+ self.timeout = timeout
55
+
56
+ # Create a session with retry logic
57
+ self.session = requests.Session()
58
+ retry_strategy = Retry(
59
+ total=max_retries,
60
+ backoff_factor=0.5,
61
+ status_forcelist=[429, 500, 502, 503, 504]
62
+ )
63
+ adapter = HTTPAdapter(max_retries=retry_strategy)
64
+ self.session.mount("https://", adapter)
65
+
66
+ def _handle_response(self, response: requests.Response) -> Dict[str, Any]:
67
+ """
68
+ Handle API response and raise appropriate exceptions for errors.
69
+
70
+ Args:
71
+ response: The HTTP response from the API
72
+
73
+ Returns:
74
+ The JSON response data
75
+
76
+ Raises:
77
+ NotifoxAuthenticationError: For 401 or 403 status codes
78
+ NotifoxRateLimitError: For 429 status code
79
+ NotifoxAPIError: For other error status codes
80
+ """
81
+ if response.status_code == 401 or response.status_code == 403:
82
+ raise NotifoxAuthenticationError(
83
+ f"Authentication failed: {response.status_code}",
84
+ status_code=response.status_code,
85
+ response_text=response.text
86
+ )
87
+
88
+ if response.status_code == 429:
89
+ raise NotifoxRateLimitError(
90
+ "Rate limit exceeded. Please try again later.",
91
+ status_code=response.status_code,
92
+ response_text=response.text
93
+ )
94
+
95
+ if response.status_code >= 400:
96
+ raise NotifoxAPIError(
97
+ f"API error: {response.status_code} - {response.text}",
98
+ status_code=response.status_code,
99
+ response_text=response.text
100
+ )
101
+
102
+ return response.json()
103
+
104
+ def send_alert(
105
+ self,
106
+ audience: str,
107
+ alert: str
108
+ ) -> Dict[str, Any]:
109
+ """
110
+ Sends an alert to the specified audience.
111
+
112
+ Args:
113
+ audience: Audience identifier (e.g., mike, devops, support)
114
+ alert: The alert message to send
115
+
116
+ Returns:
117
+ API response as a dictionary
118
+
119
+ Raises:
120
+ NotifoxAuthenticationError: If authentication fails
121
+ NotifoxRateLimitError: If rate limit is exceeded
122
+ NotifoxAPIError: For other API errors
123
+ NotifoxConnectionError: If there's a connection issue
124
+ """
125
+ url = f"{self.base_url}/alert"
126
+ headers = {"Authorization": f"Bearer {self.api_key}"}
127
+ payload = {
128
+ "audience": audience,
129
+ "alert": alert,
130
+ }
131
+
132
+ try:
133
+ resp = self.session.post(
134
+ url,
135
+ headers=headers,
136
+ json=payload,
137
+ timeout=self.timeout
138
+ )
139
+ return self._handle_response(resp)
140
+ except requests.exceptions.Timeout:
141
+ raise NotifoxConnectionError(
142
+ f"Request timed out after {self.timeout} seconds"
143
+ ) from None
144
+ except requests.exceptions.ConnectionError as e:
145
+ raise NotifoxConnectionError(f"Connection error: {str(e)}") from e
146
+ except requests.exceptions.RequestException as e:
147
+ raise NotifoxError(f"Request failed: {str(e)}") from e
148
+
149
+ def calculate_parts(self, alert: str) -> Dict[str, Any]:
150
+ """
151
+ Calculates the parts of the alert.
152
+
153
+ Args:
154
+ alert: The alert message to calculate the parts of
155
+
156
+ Returns:
157
+ A dictionary containing information about the alert
158
+ """
159
+
160
+ url = f"{self.base_url}/alert/parts"
161
+ payload = {
162
+ "alert": alert
163
+ }
164
+
165
+ try:
166
+ resp = self.session.post(
167
+ url,
168
+ json=payload,
169
+ timeout=self.timeout
170
+ )
171
+
172
+ return self._handle_response(resp)
173
+ except requests.exceptions.Timeout:
174
+ raise NotifoxConnectionError(
175
+ f"Request timed out after {self.timeout} seconds"
176
+ ) from None
177
+ except requests.exceptions.ConnectionError as e:
178
+ raise NotifoxConnectionError(f"Connection error: {str(e)}") from e
179
+ except requests.exceptions.RequestException as e:
180
+ raise NotifoxError(f"Request failed: {str(e)}") from e
181
+ except Exception as e:
182
+ raise NotifoxError("An unknown error occurred") from e
notifox/exceptions.py ADDED
@@ -0,0 +1,28 @@
1
+ # notifox/exceptions.py
2
+ class NotifoxError(Exception):
3
+ """Base exception for all Notifox SDK errors."""
4
+ pass
5
+
6
+
7
+ class NotifoxAPIError(NotifoxError):
8
+ """Raised when the API returns an error response."""
9
+
10
+ def __init__(self, message: str, status_code: int, response_text: str = ""):
11
+ self.status_code = status_code
12
+ self.response_text = response_text
13
+ super().__init__(message)
14
+
15
+
16
+ class NotifoxAuthenticationError(NotifoxAPIError):
17
+ """Raised when authentication fails (401/403)."""
18
+ pass
19
+
20
+
21
+ class NotifoxRateLimitError(NotifoxAPIError):
22
+ """Raised when rate limit is exceeded (429)."""
23
+ pass
24
+
25
+
26
+ class NotifoxConnectionError(NotifoxError):
27
+ """Raised when there's a connection error to the API."""
28
+ pass
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: notifox
3
+ Version: 0.1.2
4
+ Summary: Official Python SDK for Notifox alerting API
5
+ Author: Mathis Van Eetvelde
6
+ License: MIT
7
+ Project-URL: Homepage, https://notifox.com
8
+ Project-URL: Console, https://console.notifox.com
9
+ Project-URL: Docs, https://notifox.com/docs
10
+ Project-URL: API, https://api.notifox.com/
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.28.0
15
+ Dynamic: license-file
16
+
17
+ # notifox-py
18
+
19
+ Python SDK for [Notifox](https://notifox.com).
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install notifox
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```python
30
+ from notifox import NotifoxClient
31
+
32
+ client = NotifoxClient(api_key="your_api_key_here")
33
+ client.send_alert(audience="mike", alert="Database server is down!")
34
+ ```
35
+
36
+ Or use the environment variable:
37
+
38
+ ```bash
39
+ export NOTIFOX_API_KEY="your_api_key_here"
40
+ ```
41
+
42
+ ```python
43
+ client = NotifoxClient() # Reads from NOTIFOX_API_KEY
44
+ client.send_alert(audience="mike", alert="High CPU usage!")
45
+ ```
46
+
47
+ ### Configuration
48
+
49
+ ```python
50
+ client = NotifoxClient(
51
+ api_key="your_api_key",
52
+ base_url="https://api.notifox.com",
53
+ timeout=30.0,
54
+ max_retries=3
55
+ )
56
+ ```
57
+
58
+ ## Calculate parts
59
+
60
+ When you send a message, the length and characters dictate how many parts you will be charged for. You can read more about calculating the parts [here](https://docs.notifox.com/docs/reference/parts).
61
+
62
+ The Notifox Alerts API exposes a route that lets you calculate the amount of parts a message will be without sending the alert.
63
+
64
+ ```python
65
+ from notifox import NotifoxClient
66
+
67
+ client = NotifoxClient()
68
+
69
+ # Calculate the parts of the alert
70
+ response = client.calculate_parts(
71
+ alert="Hello, world!"
72
+ )
73
+
74
+ # {'parts': 1, 'cost': 0.025, 'currency': 'USD', 'encoding': 'GSM-7', 'characters': 22, 'message': 'Notifox: Hello, world!'}
75
+ ```
76
+
77
+ ## Error Handling
78
+
79
+ ```python
80
+ from notifox import (
81
+ NotifoxClient,
82
+ NotifoxAuthenticationError,
83
+ NotifoxRateLimitError,
84
+ NotifoxAPIError,
85
+ NotifoxConnectionError
86
+ )
87
+
88
+ client = NotifoxClient(api_key="your_api_key")
89
+
90
+ try:
91
+ client.send_alert(audience="admin", alert="System is running low on memory")
92
+ except NotifoxAuthenticationError:
93
+ print("Authentication failed. Check your API key.")
94
+ except NotifoxRateLimitError:
95
+ print("Rate limit exceeded. Please wait before sending more alerts.")
96
+ except NotifoxAPIError as e:
97
+ print(f"API error ({e.status_code}): {e.response_text}")
98
+ except NotifoxConnectionError as e:
99
+ print(f"Connection failed: {e}")
100
+ ```
101
+
102
+ Available exceptions:
103
+ - `NotifoxError` - Base exception
104
+ - `NotifoxAuthenticationError` - Authentication failed (401/403)
105
+ - `NotifoxRateLimitError` - Rate limit exceeded (429)
106
+ - `NotifoxAPIError` - General API errors
107
+ - `NotifoxConnectionError` - Network errors
@@ -0,0 +1,8 @@
1
+ notifox/__init__.py,sha256=dvO0GnAfHz9qqs53aecJf-saVHet2XAotFVFPiWCbkY,382
2
+ notifox/client.py,sha256=8F0RfO-id7dWcPzPUedUiwVolKW489YbQqtx6ZKSX7g,5913
3
+ notifox/exceptions.py,sha256=lHDVJrOo5Y-xa0_KyLI2pwPW3yJAlEUpWKDdlpqlnLM,752
4
+ notifox-0.1.2.dist-info/licenses/LICENSE,sha256=eZtQec-wzyeDB7eeTSsosa9_a6RR0ebVBPPxn7xSakQ,1094
5
+ notifox-0.1.2.dist-info/METADATA,sha256=MEGyF38hI7ExSNNS81avYRJzmPT1d2j9bPTteLT74ho,2730
6
+ notifox-0.1.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ notifox-0.1.2.dist-info/top_level.txt,sha256=VvmvnNCybE97RLvBOCrYNYCKGdhhVkPBVdYW_kM_spc,8
8
+ notifox-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Van Eetvelde Ventures LLC DBA Notifox
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ notifox