class Notifier: """ Notifier class is responsible for creating and managing the notification Args: summary: title of the notification message: message to be displayed icon: icon of notification bar """ def __init__(self, app_name: str, summary: str, message: str = "", icon: str = "") -> None: self._app_name = app_name self._summary = summary self._message = message self._icon = icon notify2.init(self._app_name) self._notification = Notification(self._summary, self._message, self._icon) def show(self, urgency_level: int = notify2.URGENCY_NORMAL) -> None: """ Show notification bar Args: urgency_level: level of urgency (NORMAL, LOW, CRITICAL) """ self._notification.set_urgency(urgency_level) self._notification.show() def close(self) -> None: """ Remove notification bar from tray """ self._notification.close()
def notify(self, title, message, timeout=10): n = Notification( "{app} - {title}".format(app=self._app_name, title=title), message, pyinstaller_resource_path("icon.png")) n.timeout = timeout * 1000 n.add_action("open", "Open App", self.open) n.show() self._notifications.append(n)
def notify(): init('Notify') n = Notification("Drink Water", "Hey asshole, drink some water FFS") n.show() sleep(10) n.close() return True
def timer(time_string, name): """Send notification after time is complete. Time should be formatted with hms e.g 1h30m or 3h20m30s. """ notify2.init("timer") print("Starting timer!") sleep(to_seconds(time_string)) print("Done!") n = Notification("Timer finished!", name) n.show()
def send(process=None, subject_format='{executable} process {pid} ended', timeout=notify2.EXPIRES_NEVER): """Display a Desktop Notification via DBUS (notify2) :param process: information about process. (.info() inserted into body) :param subject_format: subject format string. (uses process.__dict__) :param timeout: how long to display notification (milliseconds) default 0 (never expires) """ notif = Notification(subject_format.format(**process.__dict__), process.info()) notif.timeout = timeout notif.show()
def on_start(self): if self._should_run(): self._run_command() self.finish_async() else: n = Notification( summary=str(self.command), message="Run now?", # TODO include command name icon='dialog-question', ) n.set_timeout(EXPIRES_NEVER) n.add_action("error", "<b>Run</b>", lambda n, action: self._run_command(n)) n.add_action("close", "Close", lambda n, action: n.close()) n.connect('closed', lambda n: self.finish_async()) n.show()
class DLink2730URouterStatus: def __init__ ( self ): # Parse config.ini self.CONFIG_PATH = "./config.ini" self.config = ConfigParser() self.config.read(self.CONFIG_PATH) self.configuration = self.config.sections()[0] self.platform = self.config.get(self.configuration, 'platform').lower() self.router_user = self.config.get(self.configuration, 'router_user') self.router_pass = self.config.get(self.configuration, 'router_pass') # Reference Map : ( status , color style - console output , router string* ) self.connection_status = ( ( "Online" , "\033[32m" , "Up" ) , ( "Offline" , "\033[31m" , "Down" ) , ( "Disconnected" , "\033[33m" ) ) self.color_reset = "\033[m" # Reset console color self.ignore = 404 # Report this code in case of error - notifier will ignore this # Buffer last reported code to this container self.buffer = self.ignore # Initialize container to ignore default code self.duration = 3 # Notification and timeloop self.ICON_PATH = "./wlan.ico" # Platform-specific notifier: if self.platform == "windows": # Import 'Windows 10' Toast module: from win10toast import ToastNotifier # Instantiate self.notifier_windows = ToastNotifier() elif self.platform == "linux": # Import 'Linux Desktop Notification' module (Tested on Debian 10 Buster): from notify2 import init, Notification # Instantiate self.notifier_linux = init( "DLink-2730U Router Connection Status Notifier" ) self.n = Notification( "Connection Status" , message = "Daemon Running" , icon = self.ICON_PATH ) # Todo: Fetch and parse router page # Return: Connection code def get_connection_status( self ): try: status_page = get( "http://192.168.1.1/status.htm" , auth = ( self.router_user , self.router_pass ) ).content # Disconnected except OSError: return 2 status_page_parsed = BeautifulSoup( status_page , "html.parser" ) try: status_text = status_page_parsed.find_all( "font" ) [7].text # Check online & offline values in connection_status for index , status in enumerate( self.connection_status[:-1] ) : if status[-1] in status_text : return index except IndexError: return self.ignore # Todo: Notify connection status def notify( self , index ): print( f"{ self.connection_status[ index ][ 1 ] }{ self.connection_status[ index ][ 0 ] }" , self.color_reset ) if self.platform == "windows": self.notifier_windows.show_toast ( title = "" , msg = f"Connection Status: { self.connection_status[ index ][ 0 ] }" , duration = self.duration , icon_path = self.ICON_PATH ) elif self.platform == "linux": self.n.update(f"Connection Status: { self.connection_status[ index ][ 0 ] }", icon = self.ICON_PATH) self.n.show()
import power import time import notify2 from notify2 import Notification notify2.init("Charger Warning") n = Notification("WARNING", "Laptop running on battery. Plug in charger!") n.set_urgency(notify2.URGENCY_CRITICAL) while (True): source = power.PowerManagement().get_providing_power_source_type() if source == power.POWER_TYPE_BATTERY: n.show() print('NOT CHARGING!') else: print('CHARGING') time.sleep(300)
from psutil import sensors_battery from notify2 import init, Notification from time import sleep if __name__ == '__main__': init('battery notification') notification = Notification('Battery low', "Your battery is almost empty. Plug in your computer now or save your work.") shown = False while True: battery = sensors_battery() if battery.percent < 80 and not battery.power_plugged and not shown: notification.update('Battery low', f'Your battery is almost empty. Plug in your computer now or save your work\n' f'You have {battery.secsleft // 60} minutes left.') notification.show() shown = True sleep(300) sleep(10)