Example #1
0
      def process_IN_CLOSE_WRITE(self, event):
        pathname = event.pathname
        for key in dict_compiled_regex_and_path:
          if key.match(pathname):
            new_path = dict_compiled_regex_and_path[key][2]
            suffix_regex = dict_compiled_regex_and_path[key][1]
            suffix = dict_compiled_regex_and_path[key][0]

            log.debug(_("new_path = {new_path:s}").format(new_path=new_path))
            log.debug(_("suffix_regex = {suffix_regex:s}").format(suffix_regex=suffix_regex))
            log.debug(_("suffix = {suffix:s}").format(suffix=suffix))
            filename = re.sub(os.path.join(".*","(.*") + suffix_regex + ")",
              "\g<1>",pathname)
            filename_without_suffix = re.sub("(.*)" + suffix_regex,"\g<1>",
                                             filename)
            log.debug(_("filename = {filename:s}").format(filename=filename))
            log.debug(_("filename_without_suffix = {filename_without_suffix:s}").format(filename_without_suffix=filename_without_suffix))

            try:
              #os.rename(pathname, os.path.join(new_path,new_filename))
              if suffix == "ps":
                log.debug(_("suffix ist ps"))
                new_pathname = "/tmp/{filename:s}".format(filename=filename_without_suffix + ".pdf")
                log.debug(_("new_pathname = {new_pathname:s}").format(new_pathname=new_pathname))
                log.debug(_("pathname = {pathname:s}").format(pathname=pathname))
                os.system("ps2pdf -sPAPERSIZE=a4 {pathname:s} {new_pathname:s}".format(pathname=pathname,new_pathname=new_pathname))
                os.remove(pathname)
                pathname = new_pathname
                
              os.system("lpr -P{printer:s} {pathname:s}".format(printer=printer,pathname=pathname))
              os.remove(pathname)
              message = _("Printed {filename:s} on {printer:s}").format(filename=filename,printer=printer)
              log.info(message)
              if hat_display:
                n = pynotify.Notification(_("Active-Print"), message)
                if not n.show():
                  log.error(_("Failed to send notification"))
                break;
            except OSError:
              log.error(_("Can't print file {filename:s}").format(filename=filename))
def mainNotify(uploader, title, dur, url):
    global ytUrl  # a global var to be passed to web browser
    ytUrl = url
    upload = 'New video from ' + uploader
    titledur = title + '  ' + '[' + dur + ']'
    pynotify.init('YouTube Feed Notifier')

    global loop
    loop = gobject.MainLoop()
    notify = pynotify.Notification(upload, titledur,
                                   '/usr/share/pixmaps/youtube.png')

    notify.set_urgency(pynotify.URGENCY_LOW)

    notify.set_timeout(pynotify.EXPIRES_NEVER)

    notify.add_action('text', 'View on YouTube', OnClicked)
    notify.connect("closed", OnClosed)

    notify.show()

    loop.run()
Example #3
0
        def _show_notification(self, title, details, image=None):
            if self.should_notify:
                try:
                    if not self._last_bubble:
                        self._last_bubble = pynotify.Notification(
                            title, details, image)
                        self._last_bubble.show()
                    else:
                        self._last_bubble.clear_actions()
                        self._last_bubble.clear_hints()
                        self._last_bubble.update(title, details, image)
                        self._last_bubble.show()
                except Exception as e:
                    if hasattr(e, 'message') and e.message != '':
                        msg = e.message
                    elif hasattr(e, 'args') and len(e.args) > 0:
                        msg = e.args[-1]
                    else:
                        msg = str(e)
                    print(("Exception during notification: %s" % msg))

                self.should_notify = False
Example #4
0
  def notify(title, text, icon = None, timeout = None, iconsize = 48):
    if icon is None:
      icon = resources.get_ui_asset("gwibber.svg")
    
    caps = pynotify.get_server_caps()
    
    notification = pynotify.Notification(title, text)

    try:
      pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icon, iconsize, iconsize)
      notification.set_icon_from_pixbuf(pixbuf)
    except glib.GError as e:
      log.logger.error("Avatar failure - %s - %s", icon, e.message)
      resources.del_avatar(icon)

    if timeout:
      notification.set_timeout(timeout)

    if "x-canonical-append" in caps:
      notification.set_hint('x-canonical-append', 'allowed')

    return notification.show()
Example #5
0
    def libnotify(self, text, channel=None):
        global host
        try:
            import pynotify
        except:
            return 'Failed to import pynotify, is the module installed in %s?' % host

        try:
            if pynotify.init('WeeChat notification'):
                notify = pynotify.Notification(channel or 'notification', text)
                notify.set_timeout(self._timeout(text))
                notify.show()
                return 'OK'
            else:
                raise Exception
        except:
            try:
                address = self._getDBUSSession()
            except NotifyError, e:
                print >> sys.stderr, str(e)
                return 'Failed to connect with the dbus daemon in %s.' % host
            return self._updateDBUS(address)
Example #6
0
def a_notify(notification, title, description, priority=pynotify.URGENCY_LOW):
    '''Assemble and show the notification'''
    is_away = STATE['is_away']
    if STATE['is_muted']:
        weechat.prnt(
            '', 'alibnotify is currently muted, '
            'not showing notification. Unmute with: /alibnotify mute')
        return
    icon = STATE['icon']
    time_out = 5000
    if weechat.config_get_plugin('sticky') == 'on':
        time_out = 0
    if weechat.config_get_plugin('sticky_away') == 'on' and is_away:
        time_out = 0
    try:
        pynotify.init("wee-notifier")
        wn = pynotify.Notification(title, description, icon)
        wn.set_urgency(priority)
        wn.set_timeout(time_out)
        wn.show()
    except Exception as error:
        weechat.prnt('', 'alibnotify: {0}'.format(error))
def menuitem_response(w, item):
    if item == '_about':
        show_help_dlg(_ABOUT_TXT)
    elif item == '_refresh':
        newmenu = build_menu()
        ind.set_menu(newmenu)
        pynotify.init("sshplus")
        pynotify.Notification(
            "SSHplus refreshed",
            "Menu list was refreshed from %s" % _SETTINGS_FILE).show()
    elif item == '_quit':
        show_help_dlg(_ABOUT_TXT)


#        exit durch about ersetzt, sonst kann sshplus einfach beendet werden
#        sys.exit(0)
    elif item == 'folder':
        pass
    else:
        print item
        os.spawnvp(os.P_NOWAIT, item['cmd'], [item['cmd']] + item['args'])
        os.wait3(os.WNOHANG)
Example #8
0
def menuitem_response(w, buf):
    if buf == "_about":
        md = gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK)
        md.set_markup("<b>sshlist v%s</b>" % ver)
        md.format_secondary_markup(
            """A simple sshmenu like replacement for appindicator menu.

To add items to menu, simple edit the file <i>.sshlist</i> in your home directory (one host per line). The line is directly appended to the ssh command.

Author: [email protected]
http://www.gulecha.org""")
        md.run()
        md.destroy()
    elif buf == "_refresh":
        newmenu = build_menu()
        ind.set_menu(newmenu)
        pynotify.Notification(
            "sshlist refreshed",
            "Menu list was refreshed from ~/.sshlist").show()
    else:
        print "gnome-terminal -x ssh " + buf
        run_program("gnome-terminal -x ssh " + buf)
Example #9
0
        def notify(self):
            # We always update the indicator status with the latest
            # notification.
            if 'notification' in self.items:
                self.items['notification'].set_label(message)

            # Popups!
            if popup:
                popup_icon = 'dialog-warning'
                if 'app_icon' in self.config:
                    popup_icon = self._theme_image(self.config['app_icon'])
                popup_appname = self.config.get('app_name', 'gui-o-matic')
                if pynotify is not None:
                    if self.popup is None:
                        self.popup = pynotify.Notification(
                            popup_appname, message, popup_icon)
                        self.popup.set_urgency(pynotify.URGENCY_NORMAL)
                    self.popup.update(popup_appname, message, popup_icon)
                    self.popup.show()
                    return
                elif not self.config.get('disable-popup-fallback'):
                    try:
                        if self._spawn([
                                'notify-send', '-i', popup_icon, popup_appname,
                                message
                        ],
                                       report_errors=False):
                            return
                    except:
                        print('FIXME: Should popup: %s' % message)

            # Note: popups also fall through to here if we can't pop up
            if self.splash:
                self.update_splash_screen(message=message, _now=True)
            elif self.main_window:
                msg = message.replace('<', '&lt;')
                self.main_window['notification'].set_markup(msg)
            else:
                print('FIXME: Notify: %s' % message)
Example #10
0
 def send_notify_osd(title, message):
     """ Send a message to NotifyOSD
     """
     global _NTFOSD
     error = 'NotifyOSD not working'
     if sabnzbd.cfg.ntfosd_enable():
         icon = os.path.join(sabnzbd.DIR_PROG, 'sabnzbd.ico')
         _NTFOSD = _NTFOSD or pynotify.init('icon-summary-body')
         if _NTFOSD:
             logging.info('Send to NotifyOSD: %s / %s', latin1(title), latin1(message))
             try:
                 note = pynotify.Notification(title, message, icon)
                 note.show()
             except:
                 # Apparently not implemented on this system
                 logging.info(error)
                 return error
             return None
         else:
             return error
     else:
         return 'Not enabled'
Example #11
0
def main():
    while 1:
        state_err = info_err = 0

        # state -> remaining battery
        if os.path.exists('/proc/acpi/battery/BAT0/state') == False:
            state_err = 1
        else:
            state_f = open('/proc/acpi/battery/BAT0/state')
            state_str = state_f.read()
            state_f.close()
            state_pat = re.compile('(remaining\D+)(\d+)(\sm[A|W]h)')
            state_res = state_pat.search(state_str)
            state_num = int(state_res.groups()[1])

        # info -> last full capacity
        if os.path.exists('/proc/acpi/battery/BAT0/info') == False:
            info_err = 1
        else:
            info_f = open('/proc/acpi/battery/BAT0/info', 'r')
            info_str = info_f.read()
            info_f.close()
            info_pat = re.compile('(last\D+)(\d+)(\sm[A|W]h)')
            info_res = info_pat.search(info_str)
            info_num = int(info_res.groups()[1])
        if state_err == 1:
            message = "state not found"
        elif info_err == 1:
            message = "info  not found"
        else:
            percent = state_num * 100 / info_num
            if (percent >= 80 or percent <= 20):
                message = str(percent) + " %"
                pynotify.init("Battery Status")
                notif = pynotify.Notification("Battery Status", message,
                                              "dialog-information")
                notif.show()
                os.popen('aplay -q /home/rkmathi/opt/battery/mikutter.wav')
            time.sleep(INTERVAL_TIME)
Example #12
0
def function():
	browser = mechanize.Browser()
	browser.set_handle_robots(False)
	cookies = mechanize.CookieJar()
	browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7')]
	browser.open('https://www.facebook.com')
	browser.select_form(nr=0)
	browser.form['email'] = ''
	browser.form['pass'] = ''
	response = browser.submit()

	html = response.read()
	soup = BeautifulSoup(html)

	#facebook comments ticker, trending-posts and newsfeed
	#in the html source code
	commentSoup =  soup.find(text = re.compile("_5v9v"))

	#made a html out of the commentSoup
	soup = BeautifulSoup(commentSoup)

	spanContents = soup.findAll('span', {'class' : '_5v9v'})
	spanHeads = soup.findAll('span', {'class' : '_5v0s'})

	l = len(spanHeads)

	text_file = open("Trends.txt", "w")

	span = spanHeads + spanContents

	for i in range(l):
		pynotify.init("Basic")
		n = pynotify.Notification(span[i].get_text(), span[i+l].get_text())
		n.show()

		text_file.write(span[i].get_text())

	text_file.close()
Example #13
0
def PyNotification(title,
                   text,
                   picture_path=None,
                   const=None,
                   callback=None,
                   tooltip=None):
    if const == 'message-im':
        #In this case title is contact nick
        if title is None:
            title = ""

        title = Plus.msnplus_strip(title)
    notification = pynotify.Notification(title, text, picture_path)
    pix = utils.safe_gtk_pixbuf_load(picture_path[7:], (96, 96))
    if pix is not None:
        notification.set_icon_from_pixbuf(pix)
    notification.set_hint_string("append", "allowed")

    try:
        notification.show()
    except Exception, err:
        log.warning('An error occurred while showing a notification: %s' %
                    str(err))
Example #14
0
def notify(frame, msg="", title=u"消息"):

    if os.name == "posix" and sys.platform != "darwin":
        # linux 系统

        pynotify.Notification(title, msg).show()

        return

    import ToasterBox as TB

    sw, sh = wx.GetDisplaySize()
    width, height = 210, 50
    px = sw - 230
    py = sh - 100

    tb = TB.ToasterBox(frame)
    tb.SetPopupText(msg)
    tb.SetPopupSize((width, height))
    tb.SetPopupPosition((px, py))
    tb.Play()

    frame.SetFocus()
Example #15
0
def main():
    lang = get_language()
    if is_lang_available(lang) and not is_lang_installed(lang):

        n = pynotify.Notification(
            _("Additional Translations"),
            _("Your system \
support some additional translations but they are not yet installed."))
        n.connect("closed", quit_notify)
        n.set_urgency(pynotify.URGENCY_NORMAL)
        n.set_timeout(pynotify.EXPIRES_NEVER)
        n.add_action("install", _("Install Now"), install, lang)

        try:
            helper = gtk.Button()
            icon = helper.render_icon(gtk.STOCK_DIALOG_INFO,
                                      gtk.ICON_SIZE_DIALOG)
            n.set_icon_from_pixbuf(icon)
        except:
            print _("Can't load the icon for notification")

        n.show()
        MAIN_LOOP.run()
def score():
    while True:
        time.sleep(30)
        try:
            ur = "http://cricapi.com/api/cricket/"
            response = urllib2.urlopen(ur)
            datas = json.load(response)
            j = 0
            while (datas['data'] != None):
                uid = datas['data'][j]['unique_id']
                ur2 = "http://cricapi.com/api/cricketScore/?unique_id=" + uid
                resp = urllib2.urlopen(ur2)
                result = json.load(resp)
                pynotify.init("Display")
                notice = pynotify.Notification("cricket Live", result['score'])
                notice.show()
                j = j + 1
                if j == 4:
                    notice.close()
                    break
        except Exception:
            print 'No Internet'
            return
Example #17
0
    def __init__(self):
        pynotify.init("ibus")
        self.__bus = ibus.Bus()
        self.__bus.connect("disconnected", gtk.main_quit)
        self.__bus.connect("registry-changed", self.__registry_changed_cb)

        match_rule = "type='signal',\
                      sender='org.freedesktop.IBus',\
                      path='/org/freedesktop/IBus'"

        self.__bus.add_match(match_rule)

        self.__panel = panel.Panel(self.__bus)
        self.__bus.request_name(ibus.IBUS_SERVICE_PANEL, 0)
        self.__notify = pynotify.Notification("IBus", \
                            _("Some input methods have been installed, removed or updated. " \
                            "Please restart ibus input platform."), \
                            "ibus")
        self.__notify.set_timeout(10 * 1000)
        self.__notify.add_action("restart", _("Restart Now"),
                                 self.__restart_cb, None)
        self.__notify.add_action("ignore", _("Later"), lambda *args: None,
                                 None)
Example #18
0
def do_notify(request):
    do_print("Creating notification ...")

    subject = request.find("subject").text
    message = request.find("message").text
    image = fetch_image("/tray.png")

    try:
        gtk.gdk.threads_enter()
        pynotify.init("Syncany")
        notification = pynotify.Notification(subject, message, image)
        notification.show()
        gtk.gdk.threads_leave()
    except:
        do_print(sys.exc_info())
        do_print(
            "Displaying notification via pynotify failed; trying notify-send ..."
        )

        os.system("notify-send -t 2000 -i '{0}' '{1}' '{2}'".format(
            image, request["summary"], request["body"]))

    return None
Example #19
0
def notify(title, message, sound=False):
    global has_pynotify

    if has_pynotify:
        if not pynotify.init("icon-summary-body"):
            has_pynotify = False

        n = pynotify.Notification(title, message)
        n.set_urgency(pynotify.URGENCY_CRITICAL)

        try:
            n.show()
        except:
            has_pynotify = False

    if not has_pynotify:
        print "\n\n" + "*" * 50
        print title
        print message
        print "*" * 50 + "\n\n"

    if sound:
        player(SOUND_DONE)
Example #20
0
    def __init__(self, download):
        self.download = download

        self.config = config.Configuration()
        self.status_icon = TrayIcon()

        pynotify.init(NAME)

        self.notification = pynotify.Notification(
            _("Download Completed"),
            _("%s has been downloaded successfully.") %
            self.download.file_name)

        if self.download.pixbuf:
            self.notification.set_icon_from_pixbuf(self.download.pixbuf)
        else:
            pixbuf = gui.load_icon(NAME.lower(), 32, 32)
            self.notification.set_icon_from_pixbuf(pixbuf)

        # Position notification at status icon if its shown
        if self.config.show_status_icon:
            # self.notification.attach_to_status_icon(self.status_icon.icon)
            (x, y) = self.__get_position()
            self.notification.set_hint_int32("x", x)
            self.notification.set_hint_int32("y", y)

        self.notification.set_timeout(TIMEOUT)  # One minute

        if not download.is_metalink:
            self.notification.add_action("file", _("Open"),
                                         self.__action_invoked)
        self.notification.add_action("folder", _("Open folder"),
                                     self.__action_invoked)
        self.notification.connect("closed", self.__closed)

        if not self.notification.show():
            print "Failed to show notification."
Example #21
0
    def notify(
        self,
        title,
        message,
        category='khweeteur-new-tweets',
        icon='khweeteur',
        count=1,
        ):
        '''Create a notification in the style of email one'''

        if not noDBUS:
            try:
                self.m_id = self.iface.Notify(
                    'Khweeteur',
                    self.m_id,
                    icon,
                    title,
                    message,
                    ['default', 'call'],
                    {
                        'category': category,
                        'desktop-entry': 'khweeteur',
                        'dbus-callback-default'
                            : 'net.khertan.khweeteur /net/khertan/khweeteur net.khertan.khweeteur show_now'
                            ,
                        'count': count,
                        'amount': count,
                        },
                    -1,
                    )
            except:
                pass
        else:

            if pynotify.init('Khweeteur'):
                n = pynotify.Notification(title, message)
                n.show()
Example #22
0
def show_notification():
    time_counter = 0
    if not pynotify.init(my_app_name):
        sys.exit(1)
    while True:
        global notifications_to_be_shown, notifications_already_shown, notification_queue
        time_counter += 1
        if time_counter % 10 == 0:
            if len(notification_queue) != 0:
                trigger_cost_analysis("Notification Queue Manager")
        icon, body, title = '','',''
        #logger.debug("Checking for new notifications .... %s" % str(user_has_been_inactive))
        if len(notifications_to_be_shown) != 0:
            logger.debug("New notification found... will process it now")
            notification = notifications_to_be_shown[0]
            if "summary" in notification:
                title = notification['summary']
            if "body" in notification:
                body = notification['body']
            if 'app_icon' in notification:
                icon = notification['app_icon']
            #sender = my_app_name
            n = pynotify.Notification(title, body, icon)
            logger.debug("Going to show notification with summary: %s" %title)
            n.add_action(discard_notification_action, discard_notification_action, reject_notification)
            n.add_action(accept_notification_action,accept_notification_action, accept_notification)
                #logging.debug("Actions in the notification are: %s" % str(actions))
                #time.sleep(5)
            n.show()
            notifications_to_be_shown.remove(notification)
            notifications_already_shown.append(notification)
            time.sleep(notification_showing_interval)
        else:
            if len(feedback_list) != 0:
                logger.debug("Item found in feedback list as: %s" % str(feedback_list[0]))
            time.sleep(notification_showing_interval)
Example #23
0
    def notify(self, found, notfound):
        ''' Use pynotify to warn the user that subtitles have been downloaded'''
        if pynotify:
            title = "periscope found %s out of %s subtitles" % (
                len(found), len(found) + len(notfound))
            if len(notfound) > 0:
                msg = _("Could not find: \n")
                filenames = [os.path.basename(f["filename"]) for f in notfound]
                msg += "\n".join(filenames)
                msg += "\n"

            if len(found) > 0:
                msg = _("Found: \n")
                filenames = [
                    os.path.basename(f["filename"]) + " (" + f['lang'] + ")"
                    for f in found
                ]
                msg += "\n".join(filenames)

            n = pynotify.Notification(title, msg, gtk.STOCK_FIND_AND_REPLACE)
            n.set_timeout(pynotify.EXPIRES_DEFAULT)
            n.show()
        else:
            pass
Example #24
0
def main(argv):
    if len(argv) != 2:
        print "tea brewing time?:"
        print
        print path.basename(argv[0]) + " 5"
        print
        print "(5 minutes)"
        return 1

    if not pynotify.init("Teatime"):
        print "Error!"
        return 1

    try:
        time.sleep(int(argv[1]) * 60)
    except ValueError:
        print "'" + argv[1] + "' Try again."
        return 1

    n = pynotify.Notification("Teatime!", "Time for tea.")

    if not n.show():
        print "Error!"
        return 1
Example #25
0
    def _init_environment(self):
        _graphic_pid, _graphic_process = utils.get_graphic_pid()
        logging.debug('Graphic pid: %s', _graphic_pid)
        logging.debug('Graphic process: %s', _graphic_process)

        if not _graphic_pid:
            self._graphic_user = os.environ.get('USER')
            print(_('No detected graphic process'))
        else:
            self._graphic_user = utils.get_graphic_user(_graphic_pid)
            _user_display = utils.get_user_display_graphic(_graphic_pid)
            logging.debug('Graphic display: %s', _user_display)

            try:
                import pygtk
                pygtk.require('2.0')
                import pynotify

                pynotify.init(self.APP_NAME)
                self._notify = pynotify.Notification(self.APP_NAME)
            except ImportError:
                pass  # graphical notifications no available

        logging.debug('Graphic user: %s', self._graphic_user)
Example #26
0
    def __init__(self):
        '''Constructor para inicializar las variables.'''
        try:
            # Leemos el archivo de configuración
            self.wallpapers, self.tiempo, self.aleatorio, self.estilo, self.accion = confhandler.leer_configuracion(
            )
        except confhandler.ConfigError:
            # Creamos un nuevo archivo de configuración
            self.wallpapers, self.tiempo, self.aleatorio, self.estilo, self.accion = confhandler.crear_configuracion(
            )

        # Cargamos del archivo glade el menú
        self.glade = gtk.glade.XML(os.path.join(PATH, "pywallchanger.glade"),
                                   root="menu")
        # Conectamos todas las señales
        self.glade.signal_autoconnect(self)
        # Creamos un statusicon a partir de una imagen
        self.tray = gtk.status_icon_new_from_file(
            os.path.join(PIX_PATH, "pywallchanger.svg"))
        # Conectamos sus señales
        self.tray.connect("popup-menu", self.on_tray_popup_event)
        self.tray.connect("activate", self.on_tray_activate_event)
        self.tray.set_tooltip("pyWallChanger")
        # Y la hacemos visible
        self.tray.set_visible(True)
        # Indicamos que elprograma ha comenzado a funcionar
        if pynotify.init("pyWallChanger"):
            n = pynotify.Notification(
                "pyWallChanger",
                "pyWallChanger se está ejecutando en la barra de tareas.",
                "file://" + os.path.join(PIX_PATH, "pywallchanger.svg"))
            n.show()
        # Y iniciamos la hebra que cambia los wallpapers
        self.changer = Changer(self.wallpapers, self.tiempo, self.aleatorio,
                               self.estilo)
        self.changer.start()
Example #27
0
    def __init__(self, params):
        self._notification = None

        if params["notify"]:
            if using_gi_notify:
                logger.debug("Initializing GObject.Notify")
                if Notify.init(identity):
                    self._notification = Notify.Notification()
                    self._notification.set_hint("desktop-entry",
                                                GLib.Variant("s", "mpdris2"))
                    self._notification.set_hint("transient",
                                                GLib.Variant("b", True))
                else:
                    logger.error(
                        "Failed to init libnotify; disabling notifications")
            elif using_old_notify:
                logger.debug("Initializing old pynotify")
                if pynotify.init(identity):
                    self._notification = pynotify.Notification("", "", "")
                    self._notification.set_hint("desktop-entry", "mpdris2")
                    self._notification.set_hint("transient", True)
                else:
                    logger.error(
                        "Failed to init libnotify; disabling notifications")
Example #28
0
def make_notification(title: str, message: str="", name: str="",
                      icon: str="", timeout: int=3_000) -> bool:
    """Notification message with information,based on D-Bus,with Fallbacks."""
    if dbus:  # Theorically the standard universal way.
        log.debug(f"Sending Notification message using the API of {dbus}.")
        return bool(dbus.Interface(dbus.SessionBus().get_object(
            "org.freedesktop.Notifications", "/org/freedesktop/Notifications"),
            "org.freedesktop.Notifications").Notify(
                name, 0, icon, title, message, [], [], timeout))
    elif pynotify:  # The non-standard non-universal way.
        log.debug(f"Sending Notification message using the API of {pynotify}.")
        pynotify.init(name.lower() if name else title.lower())
        return pynotify.Notification(title, message).show()
    elif which("notify-send"):   # The non-standard non-universal sucky ways.
        log.debug("Sending Notification message via notify-send command.")
        comand = (which("notify-send"), f"--app-name={name}",
                  f"--expire-time={timeout}", title, message)
        return not bool(
            run(comand, timeout=timeout // 1_000 + 1, shell=True).returncode)
    elif which("kdialog"):
        log.debug("Sending Notification message via KDialog command.")
        comand = (which("kdialog"), f"--name={name}", f"--title={title}",
                  f"--icon={icon}", f"--caption={name}", "--passivepopup",
                  title + message, str(timeout // 1_000))
        return not bool(
            run(comand, timeout=timeout // 1_000 + 1, shell=True).returncode)
    elif which("zenity"):
        log.debug("Sending Notification message via Zenity command.")
        comand = (which("zenity"), f"--name={name}", f"--title={title}",
                  "--notification", f"--timeout={timeout // 1_000}",
                  f"--text={title + message}")
        return not bool(
            run(comand, timeout=timeout // 1_000 + 1, shell=True).returncode)
    else:  # Windows and Mac dont have API for that, complain to them.
        log.warning("Sending Notifications not supported by this OS.")
        return False
Example #29
0
 def _trigger_alert(self, title, body):
     if PYNOTIFY_AVAILABLE:
         pynotify.Notification(title, body).show()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Edilson Alzemand

import pynotify
pynotify.init("Aplicativo")
notify = pynotify.Notification(
    "Kefir After Install ", "Installation Complete",
    "/opt/kefir-after-install/lib/icons/kefir_icon.png")
notify.show()