def display_notification(url): import gi gi.require_version('Gtk', '2.0') from gi.repository import Gtk import notify2 if not notify2.init('shurl', mainloop='glib'): raise RuntimeError("Could not connect to notification service.") server_caps = notify2.get_server_caps() n = notify2.Notification("Shortened URL:", url, icon="applications-internet") if 'actions' in server_caps: def open_url(notification, action): import webbrowser webbrowser.open(url) notification.close() n.add_action("default", "Open URL", open_url) n.connect('closed', lambda *args: Gtk.main_quit()) n.set_category("network") n.set_urgency(notify2.URGENCY_NORMAL) n.set_timeout(0) if not n.show(): raise RuntimeError("Failed to send notification.") if 'actions' in server_caps: Gtk.main()
def sas_invite_notification(self, message): notificaton = notify2.Notification( "Key verification invite", message=( f"{message.user_id} via {message.device_id} has started " f"a key verification process."), ) notificaton.set_category("im") def accept_cb(notification, action_key, user_data): message = user_data self.device_if.AcceptKeyVerification(message.pan_user, message.user_id, message.device_id) def cancel_cb(notification, action_key, user_data): message = user_data self.device_if.CancelKeyVerification(message.pan_user, message.user_id, message.device_id) if "actions" in notify2.get_server_caps(): notificaton.add_action("accept", "Accept", accept_cb, message) notificaton.add_action("cancel", "Cancel", cancel_cb, message) notificaton.show()
def sas_show_notification(self, message): emojis = [x[0] for x in message.emoji] emoji_str = " ".join(emojis) notificaton = notify2.Notification( "Short authentication string", message=( f"Short authentication string for the key verification of" f" {message.user_id} via {message.device_id}:\n" f"{emoji_str}"), ) notificaton.set_category("im") def confirm_cb(notification, action_key, user_data): message = user_data self.device_if.ConfirmKeyVerification(message.pan_user, message.user_id, message.device_id) def cancel_cb(notification, action_key, user_data): message = user_data self.device_if.CancelKeyVerification(message.pan_user, message.user_id, message.device_id) if "actions" in notify2.get_server_caps(): notificaton.add_action("confirm", "Confirm", confirm_cb, message) notificaton.add_action("cancel", "Cancel", cancel_cb, message) notificaton.show()
def test_icon_only(self): if 'x-canonical-private-icon-only' in notify2.get_server_caps(): n = notify2.Notification ("", # for a11y-reasons put something meaningfull here "", # for a11y-reasons put something meaningfull here "notification-device-eject") n.set_hint_string ("x-canonical-private-icon-only", "true"); n.show ()
def test_icon_only(self): if 'x-canonical-private-icon-only' in notify2.get_server_caps(): n = notify2.Notification( "", # for a11y-reasons put something meaningfull here "", # for a11y-reasons put something meaningfull here "notification-device-eject") n.set_hint_string("x-canonical-private-icon-only", "true") n.show()
def draw_notification(): notify2.init ('SaveMyCode!', mainloop='glib') server_capability = notify2.get_server_caps() notification = notify2.Notification ('Starting work on a new project?') if 'actions' in server_capability: notification.add_action ('add', 'Add', add_button_click) notification.add_action ('ignore', 'Ignore', ignore_button_click) notification.connect ('closed', close_notification) notification.show() Gtk.main()
def draw_notification (set_difference): notify2.init ('SaveMyCode!', mainloop='glib') server_capability = notify2.get_server_caps() notification = notify2.Notification ('Starting work on a new project?', 'Should I add the new folder in root directory to the list of ' + 'input directories?') if 'actions' in server_capability: notification.add_action ('add', 'Add', add_sub_directory, set_difference) notification.add_action ('ignore', 'Ignore', ignore_sub_directory, set_difference) notification.connect ('closed', close_notification) notification.show() Gtk.main()
def notify(self, title, summary, icon="", data=None, default_cb=EMPTY_FUNCTION, closed_cb=EMPTY_FUNCTION): server_capabilities = notify2.get_server_caps() n = notify2.Notification(title, summary, icon) if ('actions' in server_capabilities) or OVERRIDE_NO_ACTIONS: n.add_action("default", "Default Action", default_cb, data) n.connect('closed', closed_cb) n.set_timeout(self.timeout) if not n.show(): print("Failed to send notification") sys.exit(1)
def __init__(self, argv): super(MyApp, self).__init__(argv) # This needs to be before any other use of notify2, but after the Qt # application has been instantiated. notify2.init("Multi Action Test", mainloop='qt') server_capabilities = notify2.get_server_caps() n = notify2.Notification("Low disk space", "You can free up some disk space by " + "emptying the trash can.") n.set_urgency(notify2.URGENCY_CRITICAL) n.set_category("device") if ('actions' in server_capabilities) or OVERRIDE_NO_ACTIONS: n.add_action("help", "Help", self.help_cb) n.add_action("ignore", "Ignore", self.ignore_cb) n.add_action("empty", "Empty Trash", self.empty_cb) n.connect('closed', self.closed_cb) n.show()
def __init__(self, calendar_file=None, calendar_url=None, default_url=None, args=None): if args is None: args = list() QtWidgets.QApplication.__init__(self, args) self.setQuitOnLastWindowClosed(False) self.setStyleSheet("""\ QToolTip { white-space: nowrap; color: #ffffff; background-color: #000000; border: 10px solid black; }""") self.calendar = Calendar( url = calendar_url, file = calendar_file, default_url = default_url, ) ## setup notifier notify2.init("Meeting Alaram Notifier", mainloop='glib') self.notify_capabilities = notify2.get_server_caps() # icon = QtGui.QIcon(":/img/taskwarrior.ico") icon = "/usr/share/icons/Adwaita/scalable/status/alarm-symbolic.svg" self.notification = notify2.Notification("inactive", icon=icon) self.notification.set_urgency(notify2.URGENCY_NORMAL) ## setup report timer self._timer = QtCore.QTimer() self._timer.timeout.connect(self.do_report) ## setup tray icon self._tray = TrayIcon(self.calendar, parent=self) self._tray.exit_clicked.connect(self.quit) self._in_dialog = False
def main(): """The main entry point, compatible with setuptools entry points.""" # If we're running on Python 2, take responsibility for preventing # output from causing UnicodeEncodeErrors. (Done here so it should only # happen when not being imported by some other program.) if sys.version_info.major < 3: reload(sys) sys.setdefaultencoding('utf-8') # pylint: disable=no-member from argparse import ArgumentParser, RawTextHelpFormatter parser = ArgumentParser(formatter_class=RawTextHelpFormatter, description=__doc__.replace('\r\n', '\n').split('\n--snip--\n')[0]) parser.add_argument('--version', action='version', version="%%(prog)s v%s" % __version__) parser.add_argument('--no-prompt', default=False, action='store_true', help="Jump straight to applying updates") args = parser.parse_args() loop = gobject.MainLoop() notify.init("update_notifier") apt = AptWrapper() if args.no_prompt: cb_update_requested() elif apt.get_updates(): if 'actions' in notify.get_server_caps(): prompt = NotificationPrompt(loop) prompt.prompt("Updates Available", "Packages updates are available via apt-get", cb_update_requested, 'Update') else: raise NotImplementedError("TODO: Fall back to Zenity") else: sys.exit() gobject.timeout_add(TIMEOUT, loop.quit) loop.run()
def unverified_notification(self, message): notificaton = notify2.Notification( "Unverified devices.", message=( f"There are unverified devices in the room " f"{message.room_display_name}." ), ) notificaton.set_category("im") def send_cb(notification, action_key, user_data): message = user_data self.control_if.SendAnyways(message.pan_user, message.room_id) def cancel_cb(notification, action_key, user_data): message = user_data self.control_if.CancelSending(message.pan_user, message.room_id) if "actions" in notify2.get_server_caps(): notificaton.add_action("send", "Send anyways", send_cb, message) notificaton.add_action("cancel", "Cancel sending", cancel_cb, message) notificaton.show()
happiness_check_notification.set_timeout(notify2.EXPIRES_NEVER) for rating in range(1, 6): happiness_check_notification.add_action(str(rating), str(rating), rating_callback) happiness_check_notification.connect('closed', closed_callback) if not happiness_check_notification.show(): print('Failed to show notification.') sys.exit(1) Gtk.main() if __name__ == "__main__": os.chdir(os.path.dirname(os.path.realpath(__file__))) if not notify2.init('Wellness Checker', mainloop='glib'): sys.exit(1) if 'actions' not in notify2.get_server_caps(): sys.exit(1) if decide_to_ask(60, 5): print('Asking about happiness.') ask_about_happiness() else: print('Not asking about happiness.') sys.exit(0)
def test_get_server_caps(self): r = notify2.get_server_caps() assert isinstance(r, list), type(r)
CMD = input("Pay to {} for {} with {} mBTC y/n: ".format(DEST,DESC,MBTC)) if CMD == 'y': PAYMENT = stub.SendPaymentSync(ln.SendRequest(payment_request=LN_INVOICE)) if PAYMENT.payment_error: _ = input("Transaction to {} failed with {}, press any key to exit".format(DEST,PAYMENT.payment_error)) else: print("Transaction to {} is successful".format(DEST)) sleep(1) else: _ = input("Transaction to {} is cancelled, press any key to exit".format(DEST)) else: if not notify2.init("Multi Action Test", mainloop='glib'): sys.exit(1) SERVER_CAPS = notify2.get_server_caps() if 'actions' in SERVER_CAPS: if DEST in whitelist and MBTC <= MAX_AUTOPAY_AMT and BALANCE >= MIN_AUTOPAY_BALANCE : notify2.Notification("Lightning Pay", "Autopaying to \n{}\n for {}\nwith {} mBTC".format(DEST,DESC,MBTC),icon=ICON_SUCCESS).show() PAYMENT = stub.SendPaymentSync(ln.SendRequest(payment_request=LN_INVOICE)) if PAYMENT.payment_error: notify2.Notification("Lightning Pay", "Transaction to \n{}\nfailed with \n{}".format(DEST,PAYMENT.payment_error),icon=ICON_FAILURE).show() sys.exit(1) else: notify2.Notification("Lightning Pay","Transaction to \n{}\nis successful".format(DEST),icon=ICON_SUCCESS).show() sys.exit(0) else: notify2.Notification("Lightning Pay","Your notification server doesn't support actions\nUse CLI interface only").show() sys.exit(1)
def advanced_handler(self, *args, **kwargs): #self.__set_urgency(kwargs['urgency']) print('advanced handler') print(('ARGS', args)) #print('KWARGS',kwargs) """Send advanced messages to notification-daemon. Format see https://developer.gnome.org/notification-spec/ convert arguments from dbus.String to normal string with str() to avoid errors all parameters are packed in one dictionary - sent over dbus""" par = dict() par['sender'] = 'System Notification' par['header'] = 'Unconfigured Summary' par['body'] = 'Unconfigured Body' par['actions'] = '' par['hints'] = '' par['exptimeout'] = -1 par['icon'] = '/usr/share/icons/gnome/48x48/categories/preferences-system.png' par['urgency'] = 'URGENCY_' + str(kwargs['urgency']).upper() #print(args) #print("ARGS: ", args[0]) if 'sender' in args[0]: par['sender'] = str(args[0]['sender']) if 'msgid' in args[0]: par['msgid'] = int(args[0]['msgid']) if 'icon' in args[0]: par['icon'] = str(args[0]['icon']) if 'header' in args[0]: par['header'] = str(args[0]['header']) if 'body' in args[0]: par['body'] = str(args[0]['body']) if 'actions' in args[0]: par['actions'] = args[0]['actions'].split(',') if 'hints' in args[0]: par['hints'] = dict(args[0]['hints']) if 'expiration_timeout' in args[0]: par['exptimeout'] = int(args[0]['expiration_timeout']) if 'hints' not in vars() or 'hints' not in globals(): par['hints'] = dict() print("PAR", par) #Notify.init(par['sender'],mainloop='glib') server_capabilities = Notify.get_server_caps() self.notification = Notify.Notification(par['header'], message=par['body'], icon=par['icon']) i = 0 ap = dict() print("Server_capabilities", server_capabilities) if ('actions' in server_capabilities): for a in par['actions']: if i == 0: ap[i] = uuid.uuid4().hex if i == 0: ap[i + 1] = a if i == 1: ap[i + 1] = self.callbacks[a] if a in self.callbacks else None if i == 2: ap[i + 1] = a i += 1 if i >= 3: #notification.add_action( # "uniq short summary", # "Title shown on button", # my_callback_func, # 'action argument' # Arguments #) self.notification.add_action(ap[0], ap[1], ap[2], ap[3]) i = 0 self.notification.set_timeout(par['exptimeout']) self.notification.set_urgency(urgencylevels[par['urgency']]) self.notification.connect('closed', self.closed_cb) if not self.notification.show(): print("Failed to send notification") sys.exit(1)
## Simple python notification using notify2 package # OS - Oracle Linux 7 # Display - Gnome # yum install dbus-python # yum install dbus-python-devel # pip install dbus-python # pip install notify2 ## Documentation : https://notify2.readthedocs.io/en/latest/index.html import notify2 notify2.init('Take Break - Get up') print(notify2.get_server_caps()) print(notify2.get_server_info()) n = notify2.Notification('Take a break and reenergize', 'Sip of water or stretch', '') n.set_timeout(notify2.EXPIRES_NEVER) # This depends on the server n.show()
def __init__(self, tray_icon): if sys.platform in ['win32', 'cygwin', 'win64']: self._tray_icon = tray_icon elif sys.platform != 'darwin': notify2.init('Bajoo') self._need_escape = 'body-markup' in notify2.get_server_caps()
n.close() def empty_cb(n, action): assert action == "empty" print("You clicked Empty Trash") n.close() def closed_cb(n): print("Notification closed") Gtk.main_quit() if __name__ == '__main__': if not notify2.init("Multi Action Test", mainloop='glib'): sys.exit(1) server_capabilities = notify2.get_server_caps() n = notify2.Notification("Low disk space", "You can free up some disk space by " + "emptying the trash can.") n.set_urgency(notify2.URGENCY_CRITICAL) n.set_category("device") if ('actions' in server_capabilities) or OVERRIDE_NO_ACTIONS: n.add_action("help", "Help", help_cb) n.add_action("ignore", "Ignore", ignore_cb) n.add_action("empty", "Empty Trash", empty_cb) n.connect('closed', closed_cb) if not n.show(): print("Failed to send notification") sys.exit(1)