0
# High-Level Notification API
1
2
The `gntp.notifier` module provides the main high-level API for sending notifications using GNTP. It offers both simple fire-and-forget notifications through the `mini()` function and full-featured notification management through the `GrowlNotifier` class.
3
4
## Capabilities
5
6
### Simple Fire-and-Forget Notifications
7
8
The `mini()` function provides a simple one-line way to send notifications without managing application registration or connection details.
9
10
```python { .api }
11
def mini(description, applicationName='PythonMini', noteType="Message",
12
title="Mini Message", applicationIcon=None, hostname='localhost',
13
password=None, port=23053, sticky=False, priority=None,
14
callback=None, notificationIcon=None, identifier=None,
15
notifierFactory=GrowlNotifier):
16
"""
17
Single notification function for fire-and-forget notifications.
18
19
Parameters:
20
- description (str): Notification message (required)
21
- applicationName (str): Name of sending application
22
- noteType (str): Type of notification
23
- title (str): Notification title
24
- applicationIcon (str or bytes): Application icon URL or binary data
25
- hostname (str): Growl server hostname
26
- password (str): Network password for authentication
27
- port (int): Growl server port
28
- sticky (bool): Make notification sticky
29
- priority (int): Priority level (-2 to 2)
30
- callback (str): URL callback for notification clicks
31
- notificationIcon (str or bytes): Notification-specific icon
32
- identifier (str): Coalescing identifier for grouping notifications
33
- notifierFactory (class): Factory class for creating notifier instances
34
35
Returns:
36
bool or tuple: True on success, error tuple on failure
37
"""
38
```
39
40
### Full-Featured Notification Management
41
42
The `GrowlNotifier` class provides comprehensive notification management with application registration, multiple notification types, and persistent connections.
43
44
```python { .api }
45
class GrowlNotifier(object):
46
"""
47
Helper class to simplify sending Growl messages.
48
49
Attributes:
50
- passwordHash (str): Password hash algorithm ('MD5', 'SHA1', 'SHA256', 'SHA512')
51
- socketTimeout (int): Socket timeout in seconds (default: 3)
52
"""
53
54
def __init__(self, applicationName='Python GNTP', notifications=[],
55
defaultNotifications=None, applicationIcon=None,
56
hostname='localhost', password=None, port=23053):
57
"""
58
Initialize GrowlNotifier instance.
59
60
Parameters:
61
- applicationName (str): Sending application name
62
- notifications (list): List of valid notification types
63
- defaultNotifications (list): Notifications enabled by default
64
- applicationIcon (str or bytes): Application icon URL or binary data
65
- hostname (str): Remote Growl server hostname
66
- password (str): Network password for authentication
67
- port (int): Remote Growl server port
68
"""
69
70
def register(self):
71
"""
72
Send GNTP Registration to Growl server.
73
74
Must be called before sending notifications. Registers the application
75
and its supported notification types with the Growl server.
76
77
Returns:
78
bool or tuple: True on success, error tuple on failure
79
80
Raises:
81
NetworkError: When connection to Growl server fails
82
AuthError: When authentication fails
83
ParseError: When server response is invalid
84
"""
85
86
def notify(self, noteType, title, description, icon=None, sticky=False,
87
priority=None, callback=None, identifier=None, custom={}):
88
"""
89
Send a GNTP notification.
90
91
Must have registered with Growl beforehand or message will be ignored.
92
93
Parameters:
94
- noteType (str): Notification type (must be in registered notifications)
95
- title (str): Notification title
96
- description (str): Main notification content
97
- icon (str or bytes): Icon URL or binary data
98
- sticky (bool): Make notification sticky
99
- priority (int): Message priority (-2 to 2)
100
- callback (str): URL callback for notification clicks
101
- identifier (str): Coalescing ID for grouping related notifications
102
- custom (dict): Custom attributes (keys should have X- prefix)
103
104
Returns:
105
bool or tuple: True on success, error tuple on failure
106
107
Raises:
108
AssertionError: When noteType not in registered notifications
109
NetworkError: When connection to Growl server fails
110
AuthError: When authentication fails
111
"""
112
113
def subscribe(self, id, name, port):
114
"""
115
Send a Subscribe request to remote machine.
116
117
Parameters:
118
- id (str): Subscriber ID
119
- name (str): Subscriber name
120
- port (int): Subscriber port
121
122
Returns:
123
bool or tuple: True on success, error tuple on failure
124
"""
125
126
def add_origin_info(self, packet):
127
"""
128
Add optional Origin headers to GNTP packet.
129
130
Headers include machine name, software name/version, and platform info.
131
132
Parameters:
133
- packet: GNTP packet object to modify
134
"""
135
136
def register_hook(self, packet):
137
"""
138
Hook for modifying registration packets before sending.
139
140
Override in subclasses to customize registration behavior.
141
142
Parameters:
143
- packet: GNTPRegister packet to modify
144
"""
145
146
def notify_hook(self, packet):
147
"""
148
Hook for modifying notification packets before sending.
149
150
Override in subclasses to customize notification behavior.
151
152
Parameters:
153
- packet: GNTPNotice packet to modify
154
"""
155
156
def subscribe_hook(self, packet):
157
"""
158
Hook for modifying subscription packets before sending.
159
160
Override in subclasses to customize subscription behavior.
161
162
Parameters:
163
- packet: GNTPSubscribe packet to modify
164
"""
165
```
166
167
## Usage Examples
168
169
### Basic Fire-and-Forget Notification
170
171
```python
172
import gntp.notifier
173
174
# Simple notification with default settings
175
gntp.notifier.mini("Task completed successfully!")
176
177
# Notification with custom title and priority
178
gntp.notifier.mini(
179
"Build finished with 3 warnings",
180
title="Build Status",
181
priority=1,
182
applicationName="Build System"
183
)
184
```
185
186
### Application Registration and Multiple Notifications
187
188
```python
189
import gntp.notifier
190
191
# Create notifier with multiple notification types
192
app = gntp.notifier.GrowlNotifier(
193
applicationName="Task Manager",
194
notifications=["Task Started", "Task Completed", "Task Failed"],
195
defaultNotifications=["Task Completed", "Task Failed"],
196
hostname="localhost",
197
password="mypassword"
198
)
199
200
# Register with Growl (required)
201
result = app.register()
202
if result is not True:
203
print(f"Registration failed: {result}")
204
exit(1)
205
206
# Send different types of notifications
207
app.notify("Task Started", "Building project", "Starting compilation...")
208
209
app.notify(
210
"Task Completed",
211
"Build successful",
212
"Project built in 2.3 seconds",
213
priority=1,
214
icon="http://example.com/success.png"
215
)
216
217
app.notify(
218
"Task Failed",
219
"Build failed",
220
"Compilation error in main.py line 42",
221
priority=2,
222
sticky=True,
223
callback="http://example.com/build-log"
224
)
225
```
226
227
### Working with Icons and Binary Data
228
229
```python
230
import gntp.notifier
231
232
# URL-based icon
233
gntp.notifier.mini(
234
"New email received",
235
title="Email",
236
notificationIcon="http://example.com/email-icon.png"
237
)
238
239
# Binary icon data (useful for offline/embedded icons)
240
with open('/path/to/icon.png', 'rb') as f:
241
icon_data = f.read()
242
243
gntp.notifier.mini(
244
"File saved",
245
title="Editor",
246
notificationIcon=icon_data
247
)
248
```
249
250
### Custom Attributes and Coalescing
251
252
```python
253
import gntp.notifier
254
255
app = gntp.notifier.GrowlNotifier(
256
applicationName="Download Manager",
257
notifications=["Download Progress"]
258
)
259
app.register()
260
261
# Send progress notifications that replace each other
262
for progress in [25, 50, 75, 100]:
263
app.notify(
264
"Download Progress",
265
f"Download {progress}% complete",
266
f"Downloaded {progress}MB of 100MB",
267
identifier="download-123", # Same ID causes replacement
268
custom={
269
"X-Progress": str(progress),
270
"X-Download-ID": "123"
271
}
272
)
273
```
274
275
## Error Handling
276
277
```python
278
import gntp.notifier
279
import gntp.errors
280
281
try:
282
app = gntp.notifier.GrowlNotifier(hostname="unreachable-host")
283
app.register()
284
except gntp.errors.NetworkError as e:
285
print(f"Network error: {e}")
286
except gntp.errors.AuthError as e:
287
print(f"Authentication failed: {e}")
288
except gntp.errors.ParseError as e:
289
print(f"Invalid response from server: {e}")
290
```