### Feature-Complete Application Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md This example demonstrates a full-featured application that sends an interactive notification with buttons and a reply field. It also includes setup for asynchronous event handling and signal interruption. ```python import asyncio import signal from desktop_notifier import ( DesktopNotifier, Button, ReplyField, Urgency, Capability, DEFAULT_SOUND, ) class NotificationApp: def __init__(self): self.notifier = DesktopNotifier(app_name="MyApp") self.setup_handlers() def setup_handlers(self): self.notifier.on_clicked = self.on_clicked self.notifier.on_button_pressed = self.on_button_pressed self.notifier.on_replied = self.on_replied def on_clicked(self, notification_id): print(f"Notification clicked: {notification_id}") def on_button_pressed(self, notification_id, button_id): print(f"Button pressed: {button_id}") def on_replied(self, notification_id, reply_text): print(f"User replied: {reply_text}") async def send_interactive_notification(self): caps = await self.notifier.get_capabilities() kwargs = { "title": "Action Required", "message": "Please respond to this request", "urgency": Urgency.Normal, } if Capability.BUTTONS in caps: kwargs["buttons"] = [ Button(title="Accept"), Button(title="Reject"), ] if Capability.REPLY_FIELD in caps: kwargs["reply_field"] = ReplyField() if Capability.SOUND in caps: kwargs["sound"] = DEFAULT_SOUND return await self.notifier.send(**kwargs) async def main(self): # Check authorization if not await self.notifier.has_authorisation(): await self.notifier.request_authorisation() # Send notification await self.send_interactive_notification() # Run forever until interrupted stop = asyncio.Event() loop = asyncio.get_running_loop() loop.add_signal_handler(signal.SIGINT, stop.set) await stop.wait() async def main(): app = NotificationApp() await app.main() asyncio.run(main()) ``` -------------------------------- ### Install desktop-notifier Source: https://github.com/samschott/desktop-notifier/blob/main/README.md Install the library using pip. This command ensures you have the latest version. ```bash pip3 install -U desktop-notifier ``` -------------------------------- ### Event Handler Setup (Notification Level) Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Illustrates how to set up event handlers for individual notifications. ```python # Example for setting up notification-level event handlers. # These handlers are specific to a single notification. ``` -------------------------------- ### Minimal Backend Implementation Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md This example demonstrates a no-op backend that does not actually send notifications, serving as a basic template for implementing a DesktopNotifierBackend. ```python from desktop_notifier.backends.base import DesktopNotifierBackend from desktop_notifier.common import Notification, Capability class DummyBackend(DesktopNotifierBackend): """A no-op backend that doesn't actually send notifications""" async def request_authorisation(self) -> bool: return True async def has_authorisation(self) -> bool: return True async def _send(self, notification: Notification) -> None: # Don't actually send anything pass async def _clear(self, identifier: str) -> None: pass async def _clear_all(self) -> None: pass async def _get_capabilities(self) -> frozenset[Capability]: return frozenset() ``` -------------------------------- ### Async API Quick Start Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Basic asynchronous notification sending using the DesktopNotifier class. Ensure asyncio is installed and imported. ```python import asyncio from desktop_notifier import DesktopNotifier async def main(): notifier = DesktopNotifier(app_name="MyApp") await notifier.send(title="Hello", message="World!") asyncio.run(main()) ``` -------------------------------- ### DesktopNotifierSync Initialization Examples Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Demonstrates simple synchronous notifier instantiation and configuration with a custom application name. ```python from desktop_notifier import DesktopNotifierSync # Simple synchronous notifier notifier = DesktopNotifierSync() # With custom app name notifier = DesktopNotifierSync(app_name="My Application") # Send without awaiting notification_id = notifier.send(title="Alert", message="Synchronous") ``` -------------------------------- ### Example Implementation of _get_capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Provides an example of how a subclass might implement the _get_capabilities method, returning a set of supported features. ```python async def _get_capabilities(self) -> frozenset[Capability]: return frozenset([ Capability.APP_NAME, Capability.TITLE, Capability.MESSAGE, Capability.BUTTONS, Capability.REPLY_FIELD, ]) ``` -------------------------------- ### Event Handler Setup (Class Level) Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Demonstrates setting up event handlers for all notifications at the class level. ```python # Example for setting up class-level event handlers. # These handlers would apply to all notifications sent by the notifier instance. ``` -------------------------------- ### Asynchronous API - Minimal Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Demonstrates the basic usage of the asynchronous DesktopNotifier to send a simple notification. ```APIDOC ## Asynchronous API - Minimal Example ### Description This example shows the simplest way to send a notification using the asynchronous API. ### Method `send(title: str, message: str)` ### Request Example ```python import asyncio from desktop_notifier import DesktopNotifier async def main(): notifier = DesktopNotifier() await notifier.send(title="Hello", message="World") asyncio.run(main()) ``` ``` -------------------------------- ### Example: Requesting and Handling Authorisation Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Shows how to request user authorization for sending notifications and how to catch the AuthorisationError if permission is denied. ```python from desktop_notifier import DesktopNotifier, AuthorisationError import asyncio async def main(): notifier = DesktopNotifier() try: authorized = await notifier.request_authorisation() if not authorized: raise AuthorisationError("User denied notification permission") except AuthorisationError as e: print(f"Authorization failed: {e}") asyncio.run(main()) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/samschott/desktop-notifier/blob/main/CONTRIBUTING.md Install the package with the 'dev' extra to include all necessary development dependencies, such as linters and pre-commit hooks. ```shell pip3 install 'desktop-notifier[dev]' ``` -------------------------------- ### Synchronous API - Minimal Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Shows the basic usage of the synchronous DesktopNotifierSync to send a simple notification. ```APIDOC ## Synchronous API - Minimal Example ### Description This example demonstrates the simplest way to send a notification using the synchronous API. ### Method `send(title: str, message: str)` ### Request Example ```python from desktop_notifier import DesktopNotifierSync notifier = DesktopNotifierSync() notifier.send(title="Hello", message="World") ``` ``` -------------------------------- ### Synchronous API - Full-Featured Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Illustrates sending a notification with advanced options using the synchronous API. ```APIDOC ## Synchronous API - Full-Featured Example ### Description This example demonstrates sending a notification with advanced features using the synchronous API, including custom urgency, buttons, and reply fields. ### Method `send(title: str, message: str, urgency: Urgency, buttons: list[Button], reply_field: ReplyField)` ### Request Example ```python from desktop_notifier import ( DesktopNotifierSync, Button, ReplyField, Urgency, ) notifier = DesktopNotifierSync(app_name="MyApp") notifier.send( title="Alert", message="Click me!", urgency=Urgency.Critical, buttons=[ Button(title="OK"), Button(title="Cancel"), ], reply_field=ReplyField(), ) ``` ``` -------------------------------- ### Example: Checking Supported Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Demonstrates how to retrieve and iterate through supported notification capabilities, and how to check for a specific capability like REPLY_FIELD. ```python from desktop_notifier import DesktopNotifier, Capability import asyncio async def main(): notifier = DesktopNotifier() capabilities = await notifier.get_capabilities() print("Supported capabilities:") for cap in capabilities: print(f" - {cap.name}") # Check specific capability if Capability.REPLY_FIELD in capabilities: print("This platform supports reply fields") else: print("This platform does not support reply fields") asyncio.run(main()) ``` -------------------------------- ### Sync API Quick Start Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Basic synchronous notification sending using the DesktopNotifierSync class. Suitable for non-async applications. ```python from desktop_notifier import DesktopNotifierSync notifier = DesktopNotifierSync(app_name="MyApp") notifier.send(title="Hello", message="World!") ``` -------------------------------- ### Asynchronous API - Full-Featured Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Illustrates sending a notification with advanced options like urgency, buttons, reply fields, and callbacks. ```APIDOC ## Asynchronous API - Full-Featured Example ### Description This example demonstrates sending a notification with various advanced features, including custom urgency, interactive buttons, a reply field, and event callbacks. ### Method `send(title: str, message: str, urgency: Urgency, buttons: list[Button], reply_field: ReplyField, sound: Sound, on_clicked: callable, on_dismissed: callable)` ### Request Example ```python import asyncio from desktop_notifier import ( DesktopNotifier, Button, ReplyField, Urgency, DEFAULT_SOUND, ) async def main(): notifier = DesktopNotifier(app_name="MyApp") await notifier.send( title="Alert", message="Click me!", urgency=Urgency.Critical, buttons=[ Button(title="OK", on_pressed=lambda: print("OK pressed")), Button(title="Cancel"), ], reply_field=ReplyField(on_replied=lambda text: print(f"Replied: {text}")), sound=DEFAULT_SOUND, on_clicked=lambda: print("Clicked"), on_dismissed=lambda: print("Dismissed"), ) # Keep event loop running for callbacks await asyncio.sleep(30) asyncio.run(main()) ``` ``` -------------------------------- ### Resource Constraint Violation Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/errors.md Shows correct usage for creating a Sound resource by setting exactly one of 'name', 'path', or 'uri'. ```python from desktop_notifier import Sound # Correct usage - system sound sound = Sound(name="default") # OK # Correct usage - file path from pathlib import Path sound = Sound(path=Path("alert.mp3")) # OK # Correct usage - URI sound = Sound(uri="file:///usr/share/sounds/alert.wav") # OK ``` -------------------------------- ### FileResource Constraint Violation Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/errors.md Demonstrates how to correctly create a FileResource (like Icon) by setting exactly one of 'path' or 'uri'. Incorrect usage will raise a RuntimeError. ```python from desktop_notifier import Icon # This raises RuntimeError - no path or uri try: icon = Icon() # INVALID except RuntimeError as e: print(f"Error: {e}") # This raises RuntimeError - both set try: icon = Icon(path=Path("icon.png"), uri="file:///icon.png") # INVALID except RuntimeError as e: print(f"Error: {e}") # Correct usage icon = Icon(path=Path("icon.png")) # OK icon = Icon(uri="file:///icon.png") # OK ``` -------------------------------- ### Send Notifications in Real Usage Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/usage-patterns.md This example shows how to send a notification using the DesktopNotifier in a typical application flow. Ensure the DesktopNotifier is initialized before sending. ```python # Real usage async def send_important_alert(notifier): """Function to test""" await notifier.send( title="Important", message="Alert" ) async def test_alert(): notifier = DesktopNotifier() await send_important_alert(notifier) asyncio.run(test_alert()) ``` -------------------------------- ### Send Notification with Default Sound Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Example of sending a notification using the system's default sound by referencing the DEFAULT_SOUND constant. ```python from desktop_notifier import DesktopNotifier, DEFAULT_SOUND async def main(): notifier = DesktopNotifier() await notifier.send( title="Alert", message="With default sound", sound=DEFAULT_SOUND ) asyncio.run(main()) ``` -------------------------------- ### Interactive Notification Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Sending a notification with interactive buttons and a reply field. Requires the notifier object to be initialized. ```python from desktop_notifier import Button, ReplyField await notifier.send( title="Message", message="From Alice", buttons=[Button(title="Reply")], reply_field=ReplyField(on_replied=lambda text: print(f"Replied: {text}")), on_clicked=lambda: print("Clicked"), ) ``` -------------------------------- ### Windows Configuration with Buttons and Sound Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Configure notifications for Windows 10+ using WinRT. This example demonstrates sending a toast notification with buttons and a default sound. Note the limitations, such as no support for reply fields or urgency levels. ```python from desktop_notifier import DesktopNotifier, Button, Sound import asyncio async def main(): notifier = DesktopNotifier(app_name="Windows App") # Windows supports buttons and sounds await notifier.send( title="Notification", message="Windows toast notification", buttons=[ Button(title="Yes"), Button(title="No") ], sound=Sound(name="default") ) asyncio.run(main()) ``` -------------------------------- ### Linux Configuration with Urgency and Timeout Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Configure notifications for Linux environments requiring a D-Bus notification service. This example sets critical urgency and a specific timeout, supporting features like buttons and HTML markup depending on the notification daemon. ```python from desktop_notifier import DesktopNotifier, Urgency import asyncio async def main(): notifier = DesktopNotifier(app_name="linux-app") # Set urgency for Linux notification server await notifier.send( title="Alert", message="High priority", urgency=Urgency.Critical, buttons=[Button(title="Action")], timeout=30 # 30 second timeout ) asyncio.run(main()) ``` -------------------------------- ### Get Platform Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Check which notification features (e.g., buttons, reply fields, sound) are supported by the current platform. ```python caps = await notifier.get_capabilities() if Capability.BUTTONS in caps: print("Buttons supported") if Capability.REPLY_FIELD in caps: print("Reply fields supported") if Capability.SOUND in caps: print("Sound supported") ``` -------------------------------- ### Get Platform-Specific Backend Class Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Retrieves the appropriate DesktopNotifier backend class based on the operating system and version. Raises RuntimeError if the configuration is unsupported. ```python def get_backend_class() -> Type[DesktopNotifierBackend] ``` -------------------------------- ### Button-Specific Handler Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Demonstrates setting a handler directly on a Button object. This provides the highest precedence for button press events, overriding both notification-level and class-level handlers. ```python from desktop_notifier import Button button = Button( title="My Button", on_pressed=lambda: print("Button-specific handler") ) ``` -------------------------------- ### Mixing Sync and Async Code for Notifications Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/usage-patterns.md This example shows how to use a synchronous notification API within an asynchronous context by running the synchronous code in a separate thread pool to prevent blocking the event loop. ```python import asyncio from desktop_notifier import DesktopNotifierSync from concurrent.futures import ThreadPoolExecutor def send_sync_notification(title, message): """Synchronous notification in thread pool""" notifier = DesktopNotifierSync() return notifier.send(title=title, message=message) async def main(): # Send notification in thread pool to avoid blocking event loop loop = asyncio.get_event_loop() with ThreadPoolExecutor(max_workers=1) as executor: # Run sync notification code in thread notification_id = await loop.run_in_executor( executor, send_sync_notification, "Async to Sync", "Sent from async context" ) print(f"Sent: {notification_id}") asyncio.run(main()) ``` -------------------------------- ### Reply Field Handler Example Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Shows how to define a handler directly within a ReplyField object. This handler takes precedence for reply events, overriding class-level `on_replied` settings. ```python from desktop_notifier import ReplyField reply_field = ReplyField( on_replied=lambda text: print(f"Reply field handler: {text}") ) ``` -------------------------------- ### Get Current Notifications Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Retrieve a list of IDs for all currently displayed notifications. ```python ids = await notifier.get_current_notifications() ``` -------------------------------- ### Get Current Notifications from Cache Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Retrieves a list of currently displayed notification identifiers from the internal cache. ```python async def get_current_notifications(self) -> list[str]: return list(self._notification_cache.keys()) ``` -------------------------------- ### DesktopNotifierBackend Constructor Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Initializes the backend with application name and an optional default icon. Subclasses must call this constructor. ```APIDOC ## DesktopNotifierBackend Constructor ### Description Initializes the backend with application name and an optional default icon. Subclasses must call this constructor. ### Signature ```python def __init__(self, app_name: str, app_icon: Icon | None = None) -> None ``` ### Parameters - **app_name** (str) - Required - Application name for the notification center. - **app_icon** (Icon | None) - Optional - Default icon for notifications. ``` -------------------------------- ### Initialize DesktopNotifier Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Create a DesktopNotifier instance with default settings or custom application name and icon. ```python from desktop_notifier import DesktopNotifier, Icon from pathlib import Path # Create with default settings notifier = DesktopNotifier() # Create with custom app name and icon custom_icon = Icon(path=Path("/path/to/icon.png")) notifier = DesktopNotifier(app_name="My App", app_icon=custom_icon) ``` -------------------------------- ### Get Desktop Notifier Version Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Retrieves the current version of the desktop-notifier library. This is useful for compatibility checks or logging. ```python from desktop_notifier import __version__ print(__version__) # "6.2.0" ``` -------------------------------- ### Import Main Classes Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Import the primary `DesktopNotifier` (for async operations) and `DesktopNotifierSync` (for synchronous operations) classes from the library. ```python # Main classes from desktop_notifier import DesktopNotifier, DesktopNotifierSync ``` -------------------------------- ### Get Supported Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Retrieves the set of supported capabilities for the notification backend. The result is cached after the first call for efficiency. ```python async def get_capabilities(self) -> frozenset[Capability]: if not self._capabilities: self._capabilities = await self._get_capabilities() return self._capabilities ``` -------------------------------- ### Async/Sync Integration Patterns Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Demonstrates how to integrate the asynchronous and synchronous versions of the notifier. ```python # Example code showing patterns for integrating async and sync notifier usage. ``` -------------------------------- ### Import DesktopNotifierBackend Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Import the abstract base class for notification backends. ```python from desktop_notifier.backends.base import DesktopNotifierBackend ``` -------------------------------- ### Initialize DesktopNotifierSync Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Instantiate DesktopNotifierSync with default settings or custom application name and icon. ```python from desktop_notifier import DesktopNotifierSync, Icon from pathlib import Path # Simple usage notifier = DesktopNotifierSync() # With custom settings icon = Icon(path=Path("/path/to/icon.png")) notifier = DesktopNotifierSync(app_name="My App", app_icon=icon) ``` -------------------------------- ### Send Notification with Default and Custom Sound Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Demonstrates sending notifications using both the default system sound and a custom sound file. Requires importing DesktopNotifier, Sound, and DEFAULT_SOUND. ```python from desktop_notifier import DesktopNotifier, Sound, DEFAULT_SOUND from pathlib import Path import asyncio async def main(): notifier = DesktopNotifier() # Using default system sound await notifier.send( title="Alert", message="With default sound", sound=DEFAULT_SOUND ) # Using custom sound file custom_sound = Sound(path=Path("/path/to/alert.mp3")) await notifier.send( title="Custom", message="With custom sound", sound=custom_sound ) asyncio.run(main()) ``` -------------------------------- ### Get Currently Displayed Notification IDs Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Retrieves a list of identifiers for all notifications currently being displayed by the application. This is useful for tracking active notifications. ```python notifier = DesktopNotifierSync() notifier.send(title="First", message="Message 1") notifier.send(title="Second", message="Message 2") current = notifier.get_current_notifications() print(f"Displayed: {current}") ``` -------------------------------- ### DesktopNotifier Async API Usage Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Demonstrates initializing the asynchronous DesktopNotifier, sending a notification with options, handling events, and managing notifications. Requires Icon, Urgency, Button, and Capability to be imported or available. ```python notifier = DesktopNotifier( app_name="MyApp", app_icon=Icon(name="application-icon"), ) # Send notification notification_id = await notifier.send( title="Title", message="Message", urgency=Urgency.Normal, buttons=[Button("Action")], ) # Handle events notifier.on_clicked = lambda id: print(f"Clicked: {id}") notifier.on_button_pressed = lambda id, btn_id: print(f"Button: {btn_id}") # Manage notifications current = await notifier.get_current_notifications() await notifier.clear(notification_id) await notifier.clear_all() # Check capabilities caps = await notifier.get_capabilities() if Capability.REPLY_FIELD in caps: print("Reply fields supported") ``` -------------------------------- ### Send Notification with All Options Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Demonstrates sending a notification using the send() method with all available parameters. ```python notification_id = await notifier.send( title="Title", # Required message="Message", # Required urgency=Urgency.Normal, # Critical, Normal, Low icon=Icon(name="icon-name"), # Optional buttons=[Button("Label")], # Optional reply_field=ReplyField(), # Optional attachment=Attachment(path=Path("file")), # Optional sound=DEFAULT_SOUND, # Optional thread="group-id", # macOS only timeout=10, # Linux: seconds on_dispatched=lambda: None, # Optional callback on_clicked=lambda: None, # Optional callback on_dismissed=lambda: None, # Optional callback ) ``` -------------------------------- ### Get Current Notifications Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Retrieves a list of unique identifiers for all notifications currently being displayed by the application. This is useful for managing or querying the state of active notifications. ```python async def main(): notifier = DesktopNotifier() # Send some notifications await notifier.send(title="First", message="Message 1") await notifier.send(title="Second", message="Message 2") # Get all currently displayed notifications current = await notifier.get_current_notifications() print(f"Displayed notifications: {current}") asyncio.run(main()) ``` -------------------------------- ### Get Supported Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Fetches a set of capabilities supported by the underlying notification system. This helps in determining which features, like buttons or reply fields, can be used. ```python from desktop_notifier import DesktopNotifierSync, Capability notifier = DesktopNotifierSync() capabilities = notifier.get_capabilities() if Capability.BUTTONS in capabilities: print("Buttons supported") if Capability.REPLY_FIELD in capabilities: print("Reply fields supported") ``` -------------------------------- ### Import DesktopNotifierSync Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Import the DesktopNotifierSync class from the desktop_notifier.sync module. ```python from desktop_notifier import DesktopNotifierSync ``` -------------------------------- ### Basic Notification (1 Line) Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Demonstrates the simplest way to send a notification using the desktop-notifier library. ```python notifier.send("Hello world!") ``` -------------------------------- ### Access and Set App Name Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Get the current application name or set a new one for the notifier. The setter modifies the application's identifier in the notification center. ```python notifier = DesktopNotifier() print(notifier.app_name) # "Python" notifier.app_name = "My Application" ``` -------------------------------- ### Resource as_name Method Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Illustrates the as_name method of the Resource class, which returns the resource name. Raises AttributeError if not initialized with a name. ```python def as_name(self) -> str: pass ``` -------------------------------- ### Capability Detection and Graceful Degradation Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Shows how to detect platform capabilities and implement fallback logic for unsupported features. ```python # Example demonstrating how to check for supported features (capabilities) and degrade gracefully. # This ensures the application behaves correctly on different platforms. ``` -------------------------------- ### Specify Icons for Notifications Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md The Icon class allows you to define notification icons using system icon names, file paths, or URIs. This example demonstrates creating Icon instances for each type and using one in a notification. ```python from desktop_notifier import DesktopNotifier, Icon from pathlib import Path import asyncio async def main(): notifier = DesktopNotifier() # Using system icon system_icon = Icon(name="dialog-information") # Using file path file_icon = Icon(path=Path("/usr/share/icons/hicolor/64x64/apps/python.png")) # Using URI uri_icon = Icon(uri="file:///home/user/icon.png") await notifier.send( title="Info", message="With custom icon", icon=system_icon ) asyncio.run(main()) ``` -------------------------------- ### Interactive Buttons with Callbacks Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Illustrates how to add buttons to notifications and handle user interactions via callbacks. ```python # Example demonstrating interactive buttons with callbacks. # This involves defining Button objects and associating actions with them. ``` -------------------------------- ### Configure Notification Sound by File Path Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Specify a notification sound using its absolute file path. Ensure the path is correct and accessible. ```python from pathlib import Path from desktop_notifier import Sound sound = Sound(path=Path("/path/to/alert.mp3")) ``` -------------------------------- ### Import DesktopNotifier Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Import the DesktopNotifier class from the library. ```python from desktop_notifier import DesktopNotifier ``` -------------------------------- ### Testing Patterns Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Illustrates common patterns for testing the desktop-notifier functionality. ```python # Example code for testing the desktop-notifier library. # This might involve mocking or specific test setups. ``` -------------------------------- ### Class-Level Event Handlers Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Explains how to set up callbacks for various notification events directly on the notifier instance. ```APIDOC ## Class-Level Event Handlers ### Description These properties allow you to register callback functions that will be executed when specific notification events occur. ### Handlers - `on_clicked`: Called when a notification is clicked. - `on_dismissed`: Called when a notification is dismissed. - `on_button_pressed`: Called when a notification button is pressed. - `on_replied`: Called when a user replies to a notification. - `on_dispatched`: Called when a notification is successfully sent. ### Example ```python notifier = DesktopNotifier() # Called when notification is clicked notifier.on_clicked = lambda notification_id: print(f"Clicked: {notification_id}") # Called when notification is dismissed notifier.on_dismissed = lambda notification_id: print(f"Dismissed: {notification_id}") # Called when button is pressed notifier.on_button_pressed = lambda notif_id, btn_id: print(f"Button: {btn_id}") # Called when user replies notifier.on_replied = lambda notif_id, text: print(f"Reply: {text}") # Called when notification sent to server notifier.on_dispatched = lambda notification_id: print(f"Dispatched: {notification_id}") ``` ``` -------------------------------- ### Resource is_file Method Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Shows the is_file method of the Resource class, returning True if the resource was initialized with a path or URI. ```python def is_file(self) -> bool: pass ``` -------------------------------- ### Button Creation Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Create simple buttons or buttons with callbacks. Multiple buttons can be provided as a list. ```python from desktop_notifier import Button # Simple button Button(title="OK") # Button with callback Button( title="Action", on_pressed=lambda: print("Pressed") ) # Multiple buttons buttons=[ Button(title="Accept", on_pressed=on_accept), Button(title="Reject", on_pressed=on_reject), ] ``` -------------------------------- ### Configure Notification Icon by File Path Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Specify an icon for the notification using its absolute file path. Ensure the path is correct and accessible. ```python from pathlib import Path from desktop_notifier import Icon icon = Icon(path=Path("/usr/share/icons/icon.png")) ``` -------------------------------- ### Import Constants Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Import predefined constants such as `DEFAULT_ICON` and `DEFAULT_SOUND` for use in notification creation. ```python # Constants from desktop_notifier import DEFAULT_ICON, DEFAULT_SOUND ``` -------------------------------- ### Configuring DesktopNotifier Constructor Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Initialize the DesktopNotifier with custom application name and a default application icon. These settings apply to all notifications sent by this notifier instance. ```python notifier = DesktopNotifier( app_name="MyApp", # Application name (default: "Python") app_icon=Icon(name="app"), # Default icon (default: Python icon) ) ``` -------------------------------- ### FileResource as_path Method Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Demonstrates the as_path method of the FileResource class, which returns the resource as a Path object, converting URIs if necessary. ```python def as_path(self) -> Path: pass ``` -------------------------------- ### Background Service with Persistent Handlers Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/DELIVERABLE_SUMMARY.txt Illustrates patterns for running a background service that manages notifications and their handlers. ```python # Example for implementing a background service that uses persistent notification handlers. ``` -------------------------------- ### DesktopNotifier Constructor Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Initializes a new instance of the DesktopNotifier. You can customize the application name and icon used in notifications. ```APIDOC ## Constructor: DesktopNotifier ### Description Initializes a new instance of the DesktopNotifier. You can customize the application name and icon used in notifications. ### Signature ```python def __init__( self, app_name: str = "Python", app_icon: Icon | None = DEFAULT_ICON, notification_limit: int | None = None, ) -> None ``` ### Parameters * `app_name` (str, Optional): Name to identify the application in the notification center. Defaults to "Python". * `app_icon` (Icon | None, Optional): Default icon to use for notifications. Accepts `Icon` instances referencing file paths or named system icons. Defaults to `DEFAULT_ICON`. * `notification_limit` (int | None, Optional): Deprecated. Has no effect. ### Example ```python from desktop_notifier import DesktopNotifier, Icon from pathlib import Path # Create with default settings notifier = DesktopNotifier() # Create with custom app name and icon custom_icon = Icon(path=Path("/path/to/icon.png")) notifier = DesktopNotifier(app_name="My App", app_icon=custom_icon) ``` ``` -------------------------------- ### Basic Async Notification Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/usage-patterns.md The simplest way to send a notification using async. Requires `asyncio` and `DesktopNotifier`. ```python import asyncio from desktop_notifier import DesktopNotifier async def main(): notifier = DesktopNotifier(app_name="MyApp") await notifier.send( title="Hello", message="This is a notification" ) asyncio.run(main()) ``` -------------------------------- ### FileResource as_uri Method Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Illustrates the as_uri method of the FileResource class, which returns the resource as a URI string. ```python def as_uri(self) -> str: pass ``` -------------------------------- ### DesktopNotifierSync Initialization Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Initializes the synchronous DesktopNotifierSync class for use in non-async contexts. ```python notifier = DesktopNotifierSync(app_name="MyApp") ``` -------------------------------- ### Import Data Classes Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Import necessary data classes for creating notifications, buttons, reply fields, icons, sounds, and attachments. ```python # Data classes from desktop_notifier import ( Notification, Button, ReplyField, Icon, Sound, Attachment, ) ``` -------------------------------- ### Check Platform Capabilities Before Using Features Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Query the system's capabilities to ensure a feature, like buttons, is supported before attempting to use it. This prevents errors on platforms that do not support certain features. ```python caps = await notifier.get_capabilities() if Capability.BUTTONS not in caps: # Buttons not supported, use basic notification pass ``` -------------------------------- ### Configure Notification Sound by URI Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Specify a notification sound using a URI. This allows for more flexible referencing of sound resources. ```python from desktop_notifier import Sound sound = Sound(uri="file:///usr/share/sounds/alert.wav") ``` -------------------------------- ### Sound Specification Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Specify sounds using system names (recommended), file paths, URIs, or the default sound. ```python # System sound (recommended) Sound(name="default") # File path Sound(path=Path("/path/to/sound.mp3")) # URI Sound(uri="file:///path/to/sound.wav") # Use default DEFAULT_SOUND ``` -------------------------------- ### send() Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Sends a desktop notification synchronously with various customization options. ```APIDOC ## send() ### Description Sends a desktop notification synchronously. ### Method `send` ### Parameters #### Path Parameters - `title` (str) - Required - Notification title. - `message` (str) - Required - Notification message. - `urgency` (Urgency) - Optional - Urgency level (Critical, Normal, or Low). Defaults to `Urgency.Normal`. - `icon` (Icon | None) - Optional - Custom icon for this notification. Defaults to `None`. - `buttons` (Sequence[Button]) - Optional - Interactive buttons. Defaults to `()`. - `reply_field` (ReplyField | None) - Optional - Text reply field. Defaults to `None`. - `on_dispatched` (Callable[[], Any] | None) - Optional - Callback when dispatched. Defaults to `None`. - `on_clicked` (Callable[[], Any] | None) - Optional - Callback when clicked. Defaults to `None`. - `on_dismissed` (Callable[[], Any] | None) - Optional - Callback when dismissed. Defaults to `None`. - `attachment` (Attachment | None) - Optional - File attachment. Defaults to `None`. - `sound` (Sound | None) - Optional - Notification sound. Defaults to `None`. - `thread` (str | None) - Optional - Notification thread identifier. Defaults to `None`. - `timeout` (int) - Optional - Timeout in seconds. Defaults to `-1`. ### Returns `str` - Notification identifier. ### Request Example ```python from desktop_notifier import DesktopNotifierSync, Button, ReplyField, Urgency, DEFAULT_SOUND notifier = DesktopNotifierSync(app_name="Sample App") notifier.send( title="Julius Caesar", message="Et tu, Brute?", urgency=Urgency.Critical, buttons=[ Button( title="Mark as read", on_pressed=lambda: print("Marked as read"), ) ], reply_field=ReplyField( title="Reply", button_title="Send", on_replied=lambda text: print("Brutus replied:", text), ), on_dispatched=lambda: print("Notification showing"), on_clicked=lambda: print("Notification clicked"), on_dismissed=lambda: print("Notification dismissed"), sound=DEFAULT_SOUND, ) ``` ``` -------------------------------- ### Icon Specification Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Specify icons using system names (recommended), file paths, or URIs. ```python # System icon (recommended) Icon(name="dialog-information") # File path Icon(path=Path("/path/to/icon.png")) # URI Icon(uri="file:///path/to/icon.png") ``` -------------------------------- ### Send Notification with File Attachment Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Shows how to send a notification with a file attachment. Requires importing DesktopNotifier and Attachment. The attachment is specified using a file path. ```python from desktop_notifier import DesktopNotifier, Attachment from pathlib import Path import asyncio async def main(): notifier = DesktopNotifier() attachment = Attachment(path=Path("/home/user/photo.png")) await notifier.send( title="Photo Shared", message="Check out this photo", attachment=attachment ) asyncio.run(main()) ``` -------------------------------- ### Checking Platform Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/README.md Asynchronously retrieve the capabilities supported by the current platform. This allows for feature detection, such as whether buttons or reply fields are supported. ```python from desktop_notifier import Capability caps = await notifier.get_capabilities() if Capability.BUTTONS in caps: # Can use buttons pass if Capability.REPLY_FIELD in caps: # Can use reply fields pass if Capability.SOUND in caps: # Can use sounds pass ``` -------------------------------- ### _get_capabilities() Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/backends_base.md Abstract method to retrieve the set of capabilities supported by the current platform. ```APIDOC ## _get_capabilities() ### Description Return the set of capabilities supported by this platform. ### Signature ```python @abstractmethod async def _get_capabilities(self) -> frozenset[Capability] ``` ### Returns - **frozenset[Capability]** - Set of supported capabilities. ### Example Implementation ```python async def _get_capabilities(self) -> frozenset[Capability]: return frozenset([ Capability.APP_NAME, Capability.TITLE, Capability.MESSAGE, Capability.BUTTONS, Capability.REPLY_FIELD, ]) ``` ``` -------------------------------- ### Desktop Notifier Capabilities Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Lists all supported capabilities for desktop notifications. Use this to check platform support before implementing features. ```python from desktop_notifier import Capability Capability.APP_NAME # Custom app name Capability.TITLE # Notification title Capability.MESSAGE # Notification message Capability.URGENCY # Different urgency levels Capability.ICON # Custom icons Capability.ICON_FILE # Icons from files Capability.ICON_NAME # Named system icons Capability.BUTTONS # Interactive buttons Capability.REPLY_FIELD # Text reply fields Capability.ATTACHMENT # File attachments Capability.ON_DISPATCHED # Dispatched callbacks Capability.ON_CLICKED # Click callbacks Capability.ON_DISMISSED # Dismissal callbacks Capability.SOUND # Custom sounds Capability.SOUND_FILE # Sounds from files Capability.SOUND_NAME # Named system sounds Capability.THREAD # Notification grouping Capability.TIMEOUT # Custom timeouts ``` -------------------------------- ### Configure Notification Icon by URI Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md Specify an icon for the notification using a URI. This allows for more flexible referencing of icon resources. ```python from desktop_notifier import Icon icon = Icon(uri="file:///home/user/icon.png") ``` -------------------------------- ### DesktopNotifier Constructor Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md The DesktopNotifier class accepts configuration through constructor parameters for app name, app icon, and notification limit. ```python def __init__( self, app_name: str = "Python", app_icon: Icon | None = DEFAULT_ICON, notification_limit: int | None = None, ) -> None ``` -------------------------------- ### Import Common Types Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Import necessary types like Notification, Button, and Urgency from the desktop_notifier.common module. ```python from desktop_notifier import ( Notification, Button, ReplyField, Icon, Sound, Attachment, Urgency, Capability, ) ``` -------------------------------- ### Create and Access Notification Properties Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/types.md Constructs a Notification object with various fields like buttons, reply field, sound, and callbacks. Demonstrates accessing buttons via the buttons_dict. ```python from desktop_notifier import Notification, Button, ReplyField, Urgency, Sound notification = Notification( title="New Order", message="Order #12345 received", urgency=Urgency.Normal, buttons=[ Button(title="View Details"), Button(title="Dismiss") ], reply_field=ReplyField(title="Reply"), sound=Sound(name="default"), thread="orders", timeout=10, on_clicked=lambda: print("Notification clicked"), on_dismissed=lambda: print("Notification dismissed"), ) # Access buttons by identifier for button_id, button in notification.buttons_dict.items(): print(f"{button_id}: {button.title}") ``` -------------------------------- ### Use Default System Sound Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/configuration.md To use the platform's default notification sound, assign the DEFAULT_SOUND constant to the sound parameter. ```python from desktop_notifier import DEFAULT_SOUND, Sound # Platform default sound = DEFAULT_SOUND ``` -------------------------------- ### Handle AuthorisationError Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/quick-reference.md Demonstrates how to catch and handle `AuthorisationError`, which is raised for permission-related issues. ```python from desktop_notifier import AuthorisationError try: # Authorization-related error raise AuthorisationError("Permission denied") except AuthorisationError: pass ``` -------------------------------- ### Handle Errors and Logging in Python Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/usage-patterns.md Implement robust error handling and logging for desktop notifications using asyncio and Python's logging module. ```python import asyncio import logging from desktop_notifier import DesktopNotifier, AuthorisationError ``` -------------------------------- ### DesktopNotifierSync Constructor Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier_sync.md Initializes a new instance of the DesktopNotifierSync class. You can customize the application name and icon used for notifications. ```APIDOC ## Constructor ```python def __init__( self, app_name: str = "Python", app_icon: Icon | None = DEFAULT_ICON, notification_limit: int | None = None, ) -> None ``` ### Parameters - **app_name** (str) - Name to identify the application in the notification center. - **app_icon** (Icon | None) - Default icon to use for notifications. - **notification_limit** (int | None) - Deprecated. Has no effect. ### Example ```python from desktop_notifier import DesktopNotifierSync, Icon from pathlib import Path # Simple usage notifier = DesktopNotifierSync() # With custom settings icon = Icon(path=Path("/path/to/icon.png")) notifier = DesktopNotifierSync(app_name="My App", app_icon=icon) ``` ``` -------------------------------- ### Send Desktop Notification with Options Source: https://github.com/samschott/desktop-notifier/blob/main/_autodocs/api-reference/desktop_notifier.md Use this method to send a desktop notification with various customization options like urgency, buttons, reply fields, and callbacks. It's a convenience method that simplifies the process of creating and sending notifications. ```python import asyncio from desktop_notifier import DesktopNotifier, Urgency, Button, ReplyField async def main(): notifier = DesktopNotifier(app_name="Chat App") notification_id = await notifier.send( title="New Message", message="Alice: Hello, how are you?", urgency=Urgency.Normal, buttons=[ Button(title="Reply", on_pressed=lambda: print("Opening reply")) ], reply_field=ReplyField( title="Reply", button_title="Send", on_replied=lambda text: print(f"Replied: {text}") ), on_clicked=lambda: print("Notification clicked"), thread="alice-chat", ) print(f"Notification ID: {notification_id}") # Keep event loop running to handle callbacks await asyncio.sleep(10) asyncio.run(main()) ```