Python gi.repository.Notify.init() Examples

The following are 28 code examples of gi.repository.Notify.init(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.Notify , or try the search function .
Example #1
Source File: prayertime.py    From Silaty with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self):
        GLib.threads_init()
        Gst.init(None)

        self.options = Options()

        year  = datetime.datetime.now().year
        month = datetime.datetime.now().month
        day   = datetime.datetime.now().day
        self.date = date(year, month, day)

        self._shrouk = None
        self._fajr = None
        self._zuhr = None
        self._asr = None
        self._maghrib = None
        self._isha = None
        self._nextprayer = ""
        self._tnprayer = 0
        self.dec = 0 
Example #2
Source File: Notification.py    From battery-monitor with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, type: str) -> None:
        # initiating notification
        Notify.init("Battery Monitor")
        message = MESSAGES[type]
        head = message[0]
        body = message[1]
        icon = ICONS[type]
        self.last_percentage = 0
        self.last_notification = ''
        self.notifier = Notify.Notification.new(head, body, icon)
        self.notifier.set_urgency(Notify.Urgency.CRITICAL)
        try:
            self.notifier.show()
        except GLib.GError as e:
            # fixing GLib.GError: g-dbus-error-quark blindly
            pass
        self.config = configparser.ConfigParser()
        self.load_config() 
Example #3
Source File: utils.py    From AutomaThemely with GNU General Public License v3.0 6 votes vote down vote up
def notify(message, title='AutomaThemely'):
    import gi
    gi.require_version('Notify', '0.7')
    from gi.repository import Notify, GLib

    if not Notify.is_initted():
        Notify.init('AutomaThemely')

    n = Notify.Notification.new(title, message, get_resource('automathemely.svg'))
    try:  # I don't even know... https://bugzilla.redhat.com/show_bug.cgi?id=1582833
        n.show()
    except GLib.GError as e:
        if str(e) != 'g-dbus-error-quark: Unexpected reply type (16)' \
                and str(e) != 'g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message recipient ' \
                              'disconnected from message bus without replying (4)':
            raise e 
Example #4
Source File: arp_poisoning_detector.py    From ARP_poisoning_detector with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def check_attack(x):
	if ARP in x and x[ARP].op == 2:
		hwsrc= x.sprintf("%ARP.hwsrc%")
		psrc= x.sprintf("%ARP.psrc%")
		hwdst= x.sprintf("%ARP.hwdst%")
		pdst= x.sprintf("%ARP.pdst%")
		if psrc in arp:
			if arp[psrc]!=hwsrc:
				if bash_notif:
					commands.getoutput("su - {} -c 'notify-send \"ARP poisoning risk!\" \"{} want {}\nBut {} is {}\n\nTarget {} ({})\" --icon=dialog-error'".format(user,hwsrc, psrc, psrc, arp[psrc], hwdst, pdst))
				else:
					if Notify.init ("Hello world"):
						alert=Notify.Notification.new("ARP poisoning risk!","{} want {}\nBut {} is {}\n\nTarget {} ({})".format(hwsrc, psrc, psrc, arp[psrc], hwdst, pdst),"dialog-error")
						alert.show ()
				print("{} ; {} want {} ; But {} is {} ; Target {} ({})".format(strftime("%Y/%m/%d %H:%M:%S", gmtime()), hwsrc, psrc, psrc, arp[psrc], hwdst, pdst))
		else:
			arp[psrc]=hwsrc 
Example #5
Source File: cric_indicator.py    From cricket-score-applet with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):

        Notify.init("cricket score indicator")
        self.notification = Notify.Notification.new("")
        self.notification.set_app_name("Cricket Score")
        """
        Initialize appindicator and other menus
        """
        self.indicator = appindicator.Indicator.new("cricket-indicator",
                            ICON_PREFIX + DEFAULT_ICON+ ICON_SUFFIX ,
                            appindicator.IndicatorCategory.APPLICATION_STATUS)
        # if DEBUG:
        #     self.indicator.set_icon_theme_path(DARK_ICONS)

        self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
        self.indicator.set_label("Loading", "")
        self.indicator.connect("scroll-event", self.scroll_event_cb)
        self.menu_setup()

        # the 'id' of match selected for display as indicator label
        self.label_match_id = None

        self.open_scorecard = set()
        self.intl_menu = []
        self.dom_menu = [] 
Example #6
Source File: shell.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
def __init__(self, shell):
        self.shell = shell
        self.ind = appindicator.Indicator.new(
            "EAvatar-indicator",
            resource_path(os.path.join(base.AVARES_PATH, "icon.png")),
            appindicator.IndicatorCategory.APPLICATION_STATUS)
        self.ind.set_icon_theme_path(resource_path(base.AVARES_PATH))

        self.ind.set_status(appindicator.IndicatorStatus.ACTIVE)
        self.ind.set_attention_icon("icon.png")

        self.notices_menu = None
        self.status_menu = None
        self.old_status_item = None
        self.menu_setup()
        self.ind.set_menu(self.menu)
        self.notification = None
        Notify.init("EAvatar") 
Example #7
Source File: notifier.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, autokeyApp):
        Notify.init("AutoKey")
        # Used to rate-limit error notifications to 1 per second. Without this, two notifications per second cause the
        # following exception, which in turn completely locks up the GUI:
        # gi.repository.GLib.GError: g-io-error-quark:
        # GDBus.Error:org.freedesktop.Notifications.Error.ExcessNotificationGeneration:
        # Created too many similar notifications in quick succession (36)
        self.last_notification_timestamp = datetime.datetime.now()
        self.app = autokeyApp
        self.configManager = autokeyApp.service.configManager

        self.indicator = AppIndicator3.Indicator.new("AutoKey", cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON],
                                                AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
                                                
        self.indicator.set_attention_icon(common.ICON_FILE_NOTIFICATION_ERROR)
        self.update_visible_status()           
        self.rebuild_menu() 
Example #8
Source File: run.py    From twitch-indicator with zlib License 6 votes vote down vote up
def push_notifications(self, streams):
    """Pushes notifications of every stream, passed as a list of dictionaries."""
    try:
      for stream in streams:
        self.image = gtk.Image()
        # Show default if channel owner has not set his avatar
        if (stream["image"] == None):
          self.response = urllib.urlopen("http://static-cdn.jtvnw.net/jtv_user_pictures/xarth/404_user_150x150.png")
        else:
          self.response = urllib.urlopen(stream["image"])
        self.loader = GdkPixbuf.PixbufLoader.new()
        self.loader.write(self.response.read())
        self.loader.close()

        Notify.init("image")
        self.n = Notify.Notification.new("%s just went LIVE!" % stream["name"],
          stream["status"],
          "",
        )

        self.n.set_icon_from_pixbuf(self.loader.get_pixbuf())
        self.n.show()
    except IOError:
      return 
Example #9
Source File: dwdownloader.py    From daily-wallpaper with MIT License 6 votes vote down vote up
def notify_photo_caption(title, caption=None, credit=None):
    if caption:
        caption = max_length(caption, 60) if len(caption) > 60 else caption
        for m in ['<p>', '</p>', '<br>', '<br />']:
            caption = caption.replace(m, '')
        if credit:
            caption = '\n{}\n\n<i>{}</i>: {}'.format(caption,
                                                     _('Photo credit'),
                                                     credit)
    else:
        caption = ''
    try:
        Notify.init(title)
        info = Notify.Notification.new(title, caption, 'dialog-information')
        info.set_timeout(Notify.EXPIRES_DEFAULT)
        info.set_urgency(Notify.Urgency.LOW)
        info.show()
    except Exception as e:
        print(e) 
Example #10
Source File: linuxnotify.py    From mqttwarn with Eclipse Public License 2.0 6 votes vote down vote up
def plugin(srv, item):
    """Send a message to the user's desktop notification system."""

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
            item.service, item.target)

    title = item.addrs[0]
    text = item.message

    try:
        srv.logging.debug("Sending notification to the user's desktop")
        Notify.init('mqttwarn')
        n = Notify.Notification.new(
            title,
            text,
            '/usr/share/icons/gnome/32x32/places/network-server.png')
        n.show()
        srv.logging.debug("Successfully sent notification")
    except Exception as e:
        srv.logging.warning("Cannot invoke notification to linux: %s" % e)
        return False

    return True 
Example #11
Source File: prayertime.py    From Silaty with GNU General Public License v3.0 5 votes vote down vote up
def notify(self, title, message, play_audio = False, current_prayer = ''):
        Notify.init("Silaty")
        notif = Notify.Notification.new(title, message)
        icon = GdkPixbuf.Pixbuf.new_from_file(os.path.dirname(os.path.realpath(__file__)) + "/icons/hicolor/128x128/apps/silaty.svg")
        notif.set_icon_from_pixbuf(icon)

        if play_audio:
            if current_prayer == 'Fajr':
                uri = "file://" + os.path.dirname(os.path.realpath(__file__)) + "/audio/Fajr/" + self.options.fajr_adhan + ".ogg"
                self.fajrplayer = Gst.ElementFactory.make("playbin", "player")
                fakesink = Gst.ElementFactory.make("fakesink", "fakesink")
                self.fajrplayer.set_property('uri', uri)
                self.fajrplayer.set_property("video-sink", fakesink)
                self.fajrplayer.set_state(Gst.State.PLAYING)
            else:
                uri = "file://" + os.path.dirname(os.path.realpath(__file__)) + "/audio/Normal/" + self.options.normal_adhan + ".ogg"
                self.normalplayer = Gst.ElementFactory.make("playbin", "player")
                fakesink = Gst.ElementFactory.make("fakesink", "fakesink")
                self.normalplayer.set_property('uri', uri)
                self.normalplayer.set_property("video-sink", fakesink)
                self.normalplayer.set_state(Gst.State.PLAYING)

        notif.set_app_name('Silaty')
        notif.show() 
Example #12
Source File: notify.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def init_notify(lets_connect):  # type: (bool) -> Notify
    icon, name = get_brand(lets_connect)
    Notify.init(name + " client")
    image_path = path.join(icon)
    image = GdkPixbuf.Pixbuf.new_from_file(image_path)
    notification = Notify.Notification.new(name)
    notification.set_icon_from_pixbuf(image)
    notification.set_app_name(name)
    return notification 
Example #13
Source File: indicator.py    From yandex-disk-indicator with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, title):
        """ Initialize notification engine """
        if not Notify.is_initted():
            Notify.init(APPNAME)
        self.title = title
        self.note = None 
Example #14
Source File: vpn_indicator.py    From vpngate-with-proxy with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, q_info, sender):
        signal.signal(signal.SIGINT, self.handler)
        signal.signal(signal.SIGTERM, self.handler)

        # pipe for send/recv data to tcp server
        self.q_info = q_info
        self.send = sender

        self.APPINDICATOR_ID = 'myappindicator'
        self.icon1 = os.path.abspath('icon/connected.svg')
        self.icon2 = os.path.abspath('icon/connectnot.svg')
        self.icon345 = [os.path.abspath(icon) for icon in
                        ['icon/connecting1.svg', 'icon/connecting2.svg', 'icon/connecting3.svg']]
        self.hang = False
        self.is_connecting = False
        self.icon_th = 0

        self.last_recv = ['']
        self.indicator = appindicator.Indicator.new(self.APPINDICATOR_ID, self.icon2,
                                                    appindicator.IndicatorCategory.APPLICATION_STATUS)

        self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)

        # Add menu to indicator
        self.indicator.set_menu(self.build_menu())

        self.notifier = notify.Notification.new('', '', None)
        self.notifier.set_timeout(2)

        notify.init(self.APPINDICATOR_ID) 
Example #15
Source File: App.py    From bcloud with GNU General Public License v3.0 5 votes vote down vote up
def init_notify(self):
        self.notify = None
        if self.profile['use-notify']:
            status = Notify.init(Config.APPNAME)
            if not status:
                return
            self.notify = Notify.Notification.new(Config.APPNAME, '',
                                                  Config.NAME)

    # Open API 
Example #16
Source File: myweatherindicator.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def main():
    print(machine_information.get_information())
    print('My-Weather-Indicator version: %s' % comun.VERSION)
    print('#####################################################')
    Notify.init("my-weather-indicator")
    mwi = MWI()
    Gtk.main() 
Example #17
Source File: notifications.py    From epoptes with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, summary, icon):
        """Initialize Notify and local variables."""
        if not NotifyQueue.initialized:
            NotifyQueue.initialized = True
            if not Notify.init("Epoptes"):
                raise ImportError(_('Could not initialize notifications!'))
        self.summary = summary
        self.icon = icon
        self.items = []
        # The heading of the last item enqueued
        self.last_heading = ''
        self.last_time = time.time()
        self.notification = None
        self.shown_error = False 
Example #18
Source File: notifier.py    From scudcloud with MIT License 5 votes vote down vote up
def __init__(self, app_name, icon):
        self.icon = icon
        try:
            if Notify is not None:
                Notify.init(app_name)
                self.notifier = Notify
            else:
                notify2.init(app_name)
                self.notifier = notify2
            self.enabled = True
        except DBusException:
            print("WARNING: No notification daemon found! "
                  "Notifications will be ignored.")
            self.enabled = False 
Example #19
Source File: lplayer.py    From lplayer with MIT License 5 votes vote down vote up
def main(args):
    Notify.init('lplayer')
    app = MainApplication()
    app.run(args) 
Example #20
Source File: notification.py    From gtg with GNU General Public License v3.0 5 votes vote down vote up
def _notify_via_notify(title, message):
    Notify.init(APP_NAME)
    nt = Notify.Notification.new(title, message)
    nt.set_timeout(TIMEOUT)
    try:
        nt.show()
    except:
        # Keep quiet here when notification service is not avialable currently
        # sometime. For example, if user is using LXDE, no notifyd by default.
        pass
    Notify.uninit() 
Example #21
Source File: plugin.py    From SafeEyes with GNU General Public License v3.0 5 votes vote down vote up
def init(ctx, safeeyes_config, plugin_config):
    """
    Initialize the plugin.
    """
    global context
    global warning_time
    logging.debug('Initialize Notification plugin')
    context = ctx
    warning_time = safeeyes_config.get('pre_break_warning_time') 
Example #22
Source File: angrysearch_update_database.py    From ANGRYsearch with GNU General Public License v2.0 5 votes vote down vote up
def show_notification(text):
    global NOTIFY_AVAILABLE
    global NOTIFICATIONS_ENABLED

    if NOTIFY_AVAILABLE is False or NOTIFICATIONS_ENABLED is False:
        print('angrysearch: Desktop notifications disabled or unavailable')
        return

    Notify.init('angrysearch')
    n = Notify.Notification.new('ANGRYsearch:', text)

    possible_image_locations = [
        'angrysearch.svg',
        '/usr/share/pixmaps/angrysearch.svg',
        '/usr/share/angrysearch/angrysearch.svg',
        '/opt/angrysearch/angrysearch.svg'
    ]
    for x in possible_image_locations:
        if os.path.exists(x):
            icon = GdkPixbuf.Pixbuf.new_from_file(x)
            n.set_image_from_pixbuf(icon)
            break
    else:
        n.set_property('icon-name', 'drive-harddisk')

    n.show() 
Example #23
Source File: notification.py    From software-boutique with GNU General Public License v3.0 5 votes vote down vote up
def send_desktop_notification(self, app_obj, operation, successful):
    """
    Shows a notification on the user's desktop.

    app_obj     obj     ApplicationData() object
    operation   str     Operation name
                          - "install"
                          - "remove"
    successful  bln     True/False
    """
    def notify_send(title, subtitle):
        title = title.replace("{0}", app_obj.name)
        subtitle = subtitle.replace("{0}", app_obj.name)
        icon_path = os.path.join(data_source, app_obj.icon_path)
        try:
            Notify.init(title)
            notification = Notify.Notification.new(title, subtitle, icon_path)
            notification.show()
        except Exception as e:
            dbg.stdout("Could not send notification: " + str(e), dbg.error, 1)

    if operation == "install":
        if successful:
            notify_send(_("{0} successfully installed"), _("This application is ready to use."))
        else:
            notify_send(_("{0} failed to install"), _("There was a problem installing this application."))

    elif operation == "remove":
        if successful:
            notify_send(_("{0} removed"), _("This application has been uninstalled."))
        else:
            notify_send(_("{0} failed to remove"), _("There was a problem removing this application.")) 
Example #24
Source File: pomodoro_indicator.py    From pomodoro-indicator with GNU General Public License v3.0 5 votes vote down vote up
def main():
    if dbus.SessionBus().request_name(
        'es.atareao.PomodoroIndicator') !=\
            dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
        print("application already running")
        exit(0)
    GObject.threads_init()
    Gst.init(None)
    Gst.init_check(None)
    Notify.init('pomodoro-indicator')
    Pomodoro_Indicator()
    Gtk.main() 
Example #25
Source File: run.py    From twitch-indicator with zlib License 5 votes vote down vote up
def abort_refresh(self, message, description):
    """Updates menu with failure state message."""
    # Remove previous message if already exists
    if (len(self.menuItems) > 4):
      self.menuItems.pop(2)
      self.menuItems.pop(1)

    self.menuItems.insert(2, gtk.MenuItem(message))
    self.menuItems.insert(3, gtk.SeparatorMenuItem())
    self.menuItems[2].set_sensitive(False)

    # Re-enable "Check now" button
    self.menuItems[0].set_sensitive(True)
    self.menuItems[0].set_label("Check now")

    # Refresh all menu items 
    for i in self.menu.get_children():
      self.menu.remove(i)

    for i in self.menuItems:
      self.menu.append(i)

    self.menu.show_all()

    # Push notification
    Notify.init("image")
    self.n = Notify.Notification.new(message,
      description,
      "error"
    ).show() 
Example #26
Source File: notifications.py    From syncthing-gtk with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, app, daemon):
			Notify.init("Syncthing GTK")
			# Prepare stuff
			self.app = app
			self.daemon = daemon
			self.notify_folders = {}
			self.notify_devices = {}

			# Make deep connection with daemon
			self.signals = [
				self.daemon.connect("connected", self.cb_syncthing_connected)
			]
			if self.app.config["notification_for_error"]:
				self.signals += [
					self.daemon.connect("error", self.cb_syncthing_error),
					self.daemon.connect("folder-rejected", self.cb_syncthing_folder_rejected),
					self.daemon.connect("device-rejected", self.cb_syncthing_device_rejected)
				]
				log.verbose("Error notifications enabled")
			if self.app.config["notification_for_update"]:
				self.signals += [
					self.daemon.connect('item-started', self.cb_syncthing_item_started),
					self.daemon.connect('item-updated', self.cb_syncthing_item_updated),
				]
				log.verbose("File update notifications enabled")
			if self.app.config["notification_for_folder"]:
				self.signals += [
					self.daemon.connect('folder-sync-progress', self.cb_syncthing_folder_progress),
					self.daemon.connect('folder-sync-finished', self.cb_syncthing_folder_finished)
				]
				log.verbose("Folder notifications enabled") 
Example #27
Source File: NotifyGnome.py    From bazarr with GNU General Public License v3.0 4 votes vote down vote up
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
        """
        Perform Gnome Notification
        """

        if not self._enabled:
            self.logger.warning(
                "Gnome Notifications are not supported by this system.")
            return False

        try:
            # App initialization
            Notify.init(self.app_id)

            # image path
            icon_path = None if not self.include_image \
                else self.image_path(notify_type, extension='.ico')

            # Build message body
            notification = Notify.Notification.new(body)

            # Assign urgency
            notification.set_urgency(self.urgency)

            # Always call throttle before any remote server i/o is made
            self.throttle()

            if icon_path:
                try:
                    # Use Pixbuf to create the proper image type
                    image = GdkPixbuf.Pixbuf.new_from_file(icon_path)

                    # Associate our image to our notification
                    notification.set_icon_from_pixbuf(image)
                    notification.set_image_from_pixbuf(image)

                except Exception as e:
                    self.logger.warning(
                        "Could not load Gnome notification icon ({}): {}"
                        .format(icon_path, e))

            notification.show()
            self.logger.info('Sent Gnome notification.')

        except Exception:
            self.logger.warning('Failed to send Gnome notification.')
            self.logger.exception('Gnome Exception')
            return False

        return True 
Example #28
Source File: NotifyGnome.py    From apprise with MIT License 4 votes vote down vote up
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
        """
        Perform Gnome Notification
        """

        if not self._enabled:
            self.logger.warning(
                "Gnome Notifications are not supported by this system.")
            return False

        try:
            # App initialization
            Notify.init(self.app_id)

            # image path
            icon_path = None if not self.include_image \
                else self.image_path(notify_type, extension='.ico')

            # Build message body
            notification = Notify.Notification.new(body)

            # Assign urgency
            notification.set_urgency(self.urgency)

            # Always call throttle before any remote server i/o is made
            self.throttle()

            if icon_path:
                try:
                    # Use Pixbuf to create the proper image type
                    image = GdkPixbuf.Pixbuf.new_from_file(icon_path)

                    # Associate our image to our notification
                    notification.set_icon_from_pixbuf(image)
                    notification.set_image_from_pixbuf(image)

                except Exception as e:
                    self.logger.warning(
                        "Could not load Gnome notification icon ({}): {}"
                        .format(icon_path, e))

            notification.show()
            self.logger.info('Sent Gnome notification.')

        except Exception:
            self.logger.warning('Failed to send Gnome notification.')
            self.logger.exception('Gnome Exception')
            return False

        return True