def __init__(self): pynotify.init("Init") self.ind = appindicator.Indicator("nagios-checker", NAGIOS_ICON, appindicator.CATEGORY_APPLICATION_STATUS, ICONS_PATH) self.check_interval = CHECK_INTERVAL
def show_notification(self): pynotify.init("Uploading file...") notification = pynotify.Notification("FTP Upload", "Uploading files...", "dialog-info") notification.show() notification.set_urgency(pynotify.URGENCY_NORMAL) notification.set_timeout(pynotify.EXPIRES_NEVER)
def __init__ (self, replace): 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) flag = ibus.BUS_NAME_FLAG_ALLOW_REPLACEMENT if replace: flag = flag | ibus.BUS_NAME_FLAG_REPLACE_EXISTING self.__bus.request_name(ibus.IBUS_SERVICE_PANEL, flag) self.__bus.get_dbusconn().add_signal_receiver(self.__name_acquired_cb, signal_name="NameAcquired") self.__bus.get_dbusconn().add_signal_receiver(self.__name_lost_cb, signal_name="NameLost") 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)
def activate(self, text=None): self.user = GconfStore.get_instance().get_client().get_string(GCONF_TWITTER_USER) self.password = GconfStore.get_instance().get_client().get_string(GCONF_TWITTER_PASSWORD) api = twitter.Api() pynotify.init("Deskbar Twitter Plugin") message = "Your post to Twitter might have had a problem" try: results = api.PostUpdate(self.user, self.password, self._name) if self._name == results.text: message = "Your post to Twitter was successful" n = pynotify.Notification("Twitter Results", message) n.set_icon_from_pixbuf(ICON) n.show() except URLError, e: if e.code == 401: message = "Incorrect Twitter Username and/or Password" if e.code == 403: message = "Your request Twitter was forbidden" if e.code == 404: message = "The URL for Twitter was not found" if e.code == 408: message = "The request to Twitter timed out. Try again later." n = pynotify.Notification("Twitter Results", message) n.set_icon_from_pixbuf(ICON) n.show()
def _setup_notification (self): """Creates the pynotify object""" pynotify.init ("Brightness Notifications") self._notification = pynotify.Notification ("Brightness") self._notification.set_timeout (self._config.show_for)
def sendmessage(self,title, message): try: pynotify.init("Init") notice = pynotify.Notification(title, message,"jn-notify") notice.show() except pynotify.Error as e: print ('Error: %s' % e)
def show_command_results(self, status, output): """ Shows the output to the users. For now, it will write the output to stdout, change the icon depending on the status (green if the tests are passing, red otherwise) and, if pynotify is installed, show a notification. If you use this in Ubuntu, I'm sorry for you. Canonical just decided to break libnotify in so many ways that it is *impossible* to use it sanely. """ sys.stdout.write(output) self.current_status = status if self.timer.running: self._set_icon() if pynotify is not None: pynotify.init('dojotools') message = pynotify.Notification('Dojotools', self.html_escape(output)) message.attach_to_status_icon(self.status_icon) message.set_urgency( pynotify.URGENCY_NORMAL if status == 0 else pynotify.URGENCY_CRITICAL ) message.show()
def my_init(self): self.extensions = ('scss', 'sass') pynotify.init('SassWatcher') self.happy = 'file://' + os.path.abspath(os.path.curdir) + '/happysass.png' self.sad = 'file://' + os.path.abspath(os.path.curdir) + '/sadsass.png' self.lastMessage = '' self.lastTime = time.time()
def sendmessage(title, message): pynotify.init("Steam players notification") n = pynotify.Notification(title, message) n.set_urgency(pynotify.URGENCY_NORMAL) n.show() return
def notify(title, msg, icon=None, wrap=None): """Send notification icon messages through libnotify. Parameters: (str) title -- The notification title (str) msg -- The message to display into notification (str / uri) icon -- Type of icon (ok|info|error|warm|ask|sync) or icon file """ if NOT_NOTIFY: return if not pynotify.is_initted(): pynotify.init(title) gtk_icon = {'ok': gtk.STOCK_YES, 'info': gtk.STOCK_DIALOG_INFO, 'error': gtk.STOCK_DIALOG_ERROR, 'warm': gtk.STOCK_DIALOG_WARNING, 'ask': gtk.STOCK_DIALOG_QUESTION, 'sync': gtk.STOCK_JUMP_TO} if wrap: msg = os.linesep.join(textwrap.wrap(msg, wrap)) try: note = pynotify.Notification(title, msg) helper = gtk.Button() gtk_icon = helper.render_icon(gtk_icon[icon], gtk.ICON_SIZE_BUTTON) note.set_icon_from_pixbuf(gtk_icon) except KeyError: note = pynotify.Notification(title, msg, icon) note.show()
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, simply edit the file <i>.sshlist</i> in your home directory (one host per line). Author: [email protected] http://www.gulecha.org""") md.run() md.destroy() elif buf == "_refresh": newmenu = build_menu() ind.set_menu(newmenu) # Initialize pynotify, without this it crashes on "Refresh" pynotify.init("SSHList Notification") pynotify.Notification("sshlist refreshed","Menu list was refreshed from ~/.sshlist").show() elif buf == "_quit": newmenu = build_menu() ind.set_menu(newmenu) gtk.mainquit() else: print "gnome-terminal -x ssh " + buf + " &" run_program("gnome-terminal -x ssh " + buf + " &")
def notify_show(self): pynotify.init('batt') self.notify = pynotify.Notification('Подключите питание!','Ваш заряд' + str(self.real_state()) + '%') self.notify.show() time.sleep(5) self.notify.close() return True
def __init__(self): wx.Frame.__init__(self, id=-1, parent=None, name=u'RCWatchFrame', size=wx.Size(WIDTH, HEIGHT), title=u'RC Status') self.Bind(wx.EVT_CLOSE, self.OnClose) self.rc_statusText = wx.StaticText(self, -1, "UNKWN") pygame.mixer.init() self.alertSound = pygame.mixer.Sound("crossing.wav") self.alertChannel = pygame.mixer.Channel(False) self.setFont(self.rc_statusText) self.notification = pynotify.Notification("RC Link Warning!", "RC Link status not OK!", "dialog-warning") self.rc_status = -1 pynotify.init("RC Status") sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.rc_statusText, 1, wx.EXPAND) self.SetSizer(sizer) sizer.Layout() self.interface = IvyMessagesInterface("radiowatchframe") self.interface.subscribe(self.message_recv) self.update_timer = wx.CallLater(UPDATE_INTERVAL, self.gui_update)
def jaiku(self): print "Trying Jaiku update" jaiku_account = Account ("jaiku.com", "Jaiku API") user, password, key = jaiku_account.get_credentials() url = "http://api.jaiku.com/json?user=%s&personal_key=%s" % (user, key) pynotify.init("Deskbar Wayd Plugin - Jaiku") message = "Your post to Jaiku might have had a problem" data = urlencode({"method": "presence.send", "message": self.text}) try: result = simplejson.load(urlopen(url,data)) if result['status'] == 'ok': message = "Your post to Jaiku was successful" else: message = result['message'] n = pynotify.Notification("Jaiku Results", message, "stock_internet") n.show() except urllib2.URLError, e: if e.code == 401: message = "Incorrect Jaiku Username and/or Password" if e.code == 403: message = "Your Jaiku request was forbidden" if e.code == 404: message = "The URL for Jaiku was not found" if e.code == 408: message = "The request to Jaiku timed out. Try again later." n = pynotify.Notification("Jaiku Results", message, "stock_internet") n.show()
def pownce(self): print "Trying Pownce update" pownce_account = Account ("pownce.com", "Pownce API") user, password, key = pownce_account.get_credentials() url = "http://%s:%[email protected]/2.0/send/message.json" % (user, password) pynotify.init("Deskbar Wayd Plugin - Pownce") message = "Your post to Pownce might have had a problem" data = urlencode({"app_key" : "4d7p84417z5u1871edn578j300t14c4s", "note_body" : self.text, "note_to" : "public"}) try: result = simplejson.load(urlopen(url,data)) if result.has_key("error"): message = result['error']['message'] else: if result['body'] == self.text: message = "Your post to Pownce was successful" n = pynotify.Notification("Pownce Results", message, "stock_internet") n.show() except urllib.URLError, e: if e.code == 401: message = "Incorrect Pownce Username and/or Password" if e.code == 403: message = "Your Pownce request was forbidden" if e.code == 404: message = "The URL for Pownce was not found" if e.code == 408: message = "The request to Pownce timed out. Try again later." n = pynotify.Notification("Pownce Results", message, "stock_internet") n.show()
def notify(self, title, message): pynotify.init("Cricket Score Applet") n = pynotify.Notification(title, message) logging.log(logging.WARNING,"Time Out %s", self.notificationTimeOut) n.set_timeout(self.notificationTimeOut) n.set_urgency(pynotify.URGENCY_NORMAL) n.show()
def twitter(self): print "Trying Twitter update" twit_account = Account ("twitter.com", "Twitter API") user, password, key = twit_account.get_credentials() api = twitter.Api(user, password) pynotify.init("Deskbar Wayd Plugin - Twitter") message = "Your post to Twitter might have had a problem" if len(self.text) > 140: message="Your post is too long for Twitter." n = pynotify.Notification("Twitter Results", message, "stock_internet") n.show() return try: results = api.PostUpdate(self.text) if self.text == results.text: message = "Your post to Twitter was successful" n = pynotify.Notification("Twitter Results", message, "stock_internet") n.show() except urllib2.URLError, e: if e.code == 401: message = "Incorrect Twitter Username and/or Password" if e.code == 403: message = "Your request Twitter was forbidden" if e.code == 404: message = "The URL for Twitter was not found" if e.code == 408: message = "The request to Twitter timed out. Try again later." n = pynotify.Notification("Twitter Results", message, "stock_internet") n.show()
def __init__(self): # choosing glade file for gui self.gladefile = dir+"/alter.glade" self.wTree = gtk.glade.XML(self.gladefile) # getting main window self.window = self.wTree.get_widget("window1") self.window.show() if (self.window): self.window.connect("destroy",self.mainquit) #assign notifies var as class var self.notifies=notifies #loading widgets name: assignwidgets(self) #set language multilang.setlang(self) createstatusicon(self,dir) self.bar.push(0,self.string_ready) self.entry1.set_sensitive(0) self.entry2.set_sensitive(0) self.minuty = 0 self.sekundy = 0 #load preferences self.gcprefs=gcpreferences() self.gcprefs.loaduserdata(self) self.gcprefs.loadprefs(self) #few control vars self.countdown=False self.quit=False #if pynotify importet successful - init notifies. if notifies:pynotify.init("GCounter Notify")
def __notify_adjust_privacy(): ''' Notify the user she should adjust privacy settings via the web user interface ''' try: pynotify.init('Neubot 0.4.12-rc2') notification = pynotify.Notification( PRIVACY_TITLE, PRIVACY_EXPLANATION, NEUBOT_ICON ) notification.set_urgency(pynotify.URGENCY_CRITICAL) notification.set_timeout(15) notification.show() except: syslog.syslog(syslog.LOG_ERR, '%s' % str(asyncore.compact_traceback())) # # Reraise the exception because each login spawns a new instance # of this script. Old instances will fail because pynotify cannot # connect to the session dbus. So, reraising the exception here # is a cheap and dirty way to enforce the singleton pattern. # raise
def activate(self, shell): gtk.gdk.threads_init() pynotify.init('Rhythmbox') self.shell=shell self.pl=shell.get_property('shell-player') self.db=shell.get_property('db') self.config_dialog=ConfigDialog(self) self.settings=Settings() self.post=Post(self) self.get_conf=self.settings.get_conf self.uim = shell.get_ui_manager() self._register_icons() self.add_ui() self._attach_box() self.sending=False threading.Thread(target=self._check_4_update).start()
def main(): '''Sets up WeeChat notifications.''' # Initialize options. for option, value in SETTINGS.items(): if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value) # Initialize. name = "WeeChat" icon = "/usr/share/pixmaps/weechat.xpm" notifications = [ 'Public', 'Private', 'Action', 'Notice', 'Invite', 'Highlight', 'Server', 'Channel', 'DCC', 'WeeChat' ] STATE['icon'] = icon # Register hooks. weechat.hook_signal( 'irc_server_connected', 'cb_irc_server_connected', '') weechat.hook_signal( 'irc_server_disconnected', 'cb_irc_server_disconnected', '') weechat.hook_signal('upgrade_ended', 'cb_upgrade_ended', '') weechat.hook_print('', '', '', 1, 'cb_process_message', '') weechat.hook_timer(1000, 1, 65535, "cb_buffer_tick", "") pynotify.init(name)
def __exit__(self, typ, val, traceback): if self.task_process is not None: try: self.task_process.kill() except (OSError, AttributeError): pass if self.pid is not None: if self.current_run < self.num_repeats: self.task_process = self.spawnProcess(logging_target=self.logging_target) self.task_process.communicate() return self.__exit__(typ, val, traceback) self.logfile.close() # clean up the log file (remove backspace characters) logfile = open(self.log_filename) logfile_content_old = logfile.readlines() logfile.close() logfile = open(self.log_filename,"w+") for line in logfile_content_old: line = line.replace("\010","") logfile.write(line) logfile.close() try: import pynotify pynotify.init("Basic") n = pynotify.Notification("%s has finished running" % str(self.task), self.output_directory) n.show() except ImportError: pass
def __init__(self): self._statusicon = gtk.StatusIcon() pynotify.init('Snappy screen capture') self._statusicon.connect('activate', self._emit_proxy, 'activate') self._statusicon.connect('popup_menu', self._emit_proxy, 'popup_menu') self._statusicon.set_visible(True) super(SimpleGTKStatusIcon, self).__init__()
def __init__(self, config, verbose=False): """ initialized the logging and notification """ self.statusIcon = None self.indicator = None self.status_button = None self.status_text = None self.config = config #init logging self.log = logging.getLogger("") os.popen("touch %s"%self.config.getAttribute('LOGFILE')) hdlr = logging.handlers.RotatingFileHandler(self.config.getAttribute('LOGFILE'), "a", 1000000, 3) fmt = logging.Formatter("%(asctime)s %(levelname)-5s %(message)s", "%x %X") hdlr.setFormatter(fmt) self.log.addHandler(hdlr) self.verbose = verbose #init notify self.notifyid = "Persy" try: pynotify.init(self.notifyid) except Exception as e: self.log.warn(str(e)) self.resetError()
def __init__(self, event, tray_icon, config): AlertDisplay.__init__(self, event, config) import pynotify pynotify.init('wuja') title = event.entry.title + " - Wuja" start_time = event.time.strftime("%a %b %d %Y - %I:%M%P") duration = str(timedelta(seconds=event.entry.duration)) calendar = str(event.entry.calendar.title) where = str(event.entry.location) description = event.entry.description body = start_time + "\n" + \ "Duration - " + duration + "\n" + \ "Calendar - " + calendar + "\n" + \ "Location - " + where if description != None: body += "\n" + description pynotify.init(title) notif = pynotify.Notification(title, body) notif.attach_to_widget(tray_icon) notif.set_timeout(0) notif.add_action('accept', 'Accept', self.accept_event) notif.add_action('snooze', 'Snooze', self.snooze_event) notif.show()
def __init__(self): self.logger = logging.getLogger(__name__) self.logger.debug('Initializing notify object') if sys.platform == 'linux2': self.user = '' who = Popen(['/usr/bin/who'], stdout=PIPE).stdout.read() for line in who.splitlines(): if 'tty7' in line: self.user = line.split()[0] if '(' in line.split()[-1]: self.display = line.split()[-1].replace('(','').replace(')','') else: self.display = ':0' break if not self.user: self.logger.error('User not found in tty7. Probably no one logged in or in other terminal') raise Exception('No user found.') self.logger.debug('Set user : {0}'.format(self.user)) self.logger.debug('Set display : {0}'.format(self.display)) self.logger.debug('Initializing pynotify') pynotify.init('Summary') self.__notifier = pynotify.Notification self.message = self.__message if sys.platform == 'win32': self.logger.debug('Initializing WindowsBalloonTip') self.__notifier = WindowsBalloonTip() self.message = self.__message
def sendmessage(title, message): pynotify.init("image") notice = pynotify.Notification( title, message, "/usr/share/icons/gnome/48x48/status/appointment-missed.png").show() return notice
def display_notification(self, return_code=None): if return_code is None and settings.aborted.show: description = settings.aborted.description % self.string_duration() timeout = settings.aborted.timeout elif return_code == 0 and settings.success.show: description = settings.success.description % self.string_duration() timeout = settings.success.timeout elif return_code is not None and settings.failed.show: description = settings.failed.description % (return_code, self.string_duration()) timeout = settings.failed.timeout else: return if hasattr(notify, "GrowlNotifier"): g = notify.GrowlNotifier(u"naf", notifications=["command_finished"]) g.register() g.notify("command_finished", self.command, description) elif hasattr(notify, "Notification"): if return_code == 0: icon = gtk.STOCK_DIALOG_INFO else: icon = gtk.STOCK_DIALOG_ERROR notify.init("Notify At Finish") notification = notify.Notification(self.command, description, icon) notification.set_timeout(timeout) notification.show()
def run_command(directory, test_cmd): """ As the name says, runs a command and wait for it to finish """ process = subprocess.Popen( test_cmd, shell = True, cwd = directory, stdout = subprocess.PIPE, stderr = subprocess.PIPE, ) output = process.stdout.read() output += process.stderr.read() status = process.wait() sys.stdout.write(output) if pynotify: pynotify.init('dojotools') message = pynotify.Notification('Dojotools', output) message.set_urgency(pynotify.URGENCY_NORMAL if status == 0 else pynotify.URGENCY_CRITICAL) message.show()
def msg(self,mstr): #mstr='The scoreis 102/3' title="SCORE" #os.environ.setdefault('DISPLAY', ':0.0') #os.system('notify-send -i "notification-message-IM" "'+title+'" "'+mstr+'"') pynotify.init('my apps') pynotify.Notification(''+title+'',''+mstr+'').show()
# always comes first! n.add_action("ok", "Ok", action_ok) n.add_action("snooze", "Snooze", action_snooze) n.add_action("view", "View", action_view) # indicate to the notification-daemon, that we want to use snap-decisions n.set_hint_string("x-canonical-snap-decisions", "true") n.set_hint_string("x-canonical-non-shaped-icon", "true") n.set_hint_string("x-canonical-private-affirmative-tint", "true") n.show() return n if __name__ == '__main__': if not pynotify.init("sd-example-event-reminder"): sys.exit(1) # call this so we can savely use capabilities dictionary later example.initCaps() # show what's supported example.printCaps() # be nice and check for required capabilities if not example.capabilities['x-canonical-snap-decisions'] \ and example.capabilities['x-canonical-non-shaped-icon'] \ and example.capabilities['x-canonical-private-affirmative-tint']: sys.exit(2) loop = gobject.MainLoop()
def UnityIndicator(): import gobject import gtk import appindicator try: import pynotify pynotify.init("Mailpile") except ImportError: pynotify = None ICON_THEME = 'light' gobject.threads_init() class MailpileIndicator(Indicator): def _menu_setup(self): self.items = {} self.menu = gtk.Menu() self._create_menu_from_config() def _add_menu_item(self, item='item', label='Menu item', sensitive=False, op=None, args=None, **ignored_kwarg): menu_item = gtk.MenuItem(label) menu_item.set_sensitive(sensitive) if op: def activate(o, a): return lambda d: self._do(o, a) menu_item.connect("activate", activate(op, args or [])) menu_item.show() self.items[item] = menu_item self.menu.append(menu_item) def _ind_setup(self): self.ind = appindicator.Indicator( self.config.get('app_name', 'app').lower() + "-indicator", # FIXME: Make these two configurable... "indicator-messages", appindicator.CATEGORY_COMMUNICATIONS) self._set_status('startup', now=True) self.ind.set_menu(self.menu) def notify_user(self, message): if pynotify: notification = pynotify.Notification( "Mailpile", message, "dialog-warning") notification.set_urgency(pynotify.URGENCY_NORMAL) notification.show() else: print 'FIXME: Notify: %s' % message _STATUS_MODES = { 'startup': appindicator.STATUS_ACTIVE, 'normal': appindicator.STATUS_ACTIVE, 'working': appindicator.STATUS_ACTIVE, 'attention': appindicator.STATUS_ATTENTION, 'shutdown': appindicator.STATUS_ATTENTION, } def _set_status(self, mode, now=False): if now: do = lambda o, a: o(a) else: do = gobject.idle_add if 'indicator_icons' in self.config: icon = self.config['indicator_icons'].get(mode) if not icon: icon = self.config['indicator_icons'].get('normal') if icon: do(self.ind.set_icon, self._theme_icon(icon)) do(self.ind.set_status, self._STATUS_MODES[mode]) def set_menu_label(self, item=None, label=None): if item and item in self.items: gobject.idle_add(self.items[item].set_label, label) def set_menu_sensitive(self, item=None, sensitive=True): if item and item in self.items: gobject.idle_add(self.items[item].set_sensitive, sensitive) def run(self): self._menu_setup() self._ind_setup() self.ready = True try: gtk.main() except: traceback.print_exc() return MailpileIndicator
def __init__(self): icon = gtk.status_icon_new_from_stock(gtk.STOCK_PASTE) icon.connect('popup-menu', self.on_right_click) icon.connect('activate', self.on_left_click) pynotify.init(self.APP_NAME)
def sendmessage(title, message): pynotify.init("Test") notice = pynotify.Notification(title, message) notice.show() return
def show_notification(text): if use_pynotify: if not pynotify.is_initted(): pynotify.init("avahi-tray") n = pynotify.Notification(text) n.show()
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pynotify pynotify.init("deepin-system-settings") from events import EventManager event_manager = EventManager(use_logger=False) ''' theme-detail : theme detail information. apply-theme : apply current theme. ''' def notify_message(summary, body): noti = pynotify.Notification( summary, body, "/usr/share/icons/Deepin/apps/48/preferences-system-bluetooth.png") noti.show()
if capabilities['append']: print "\tappend" if capabilities['private-icon-only']: print "\tprivate-icon-only" print "Notes:" if info["name"] == "notify-osd": print "\tx- and y-coordinates hints are ignored" print "\texpire-timeout is ignored" print "\tbody-markup is accepted but filtered" else: print "\tnone" if __name__ == '__main__': if not pynotify.init("icon-summary-body"): sys.exit(1) # call this so we can savely use capabilities dictionary later initCaps() # show what's supported printCaps() # try the icon-summary-body case n = pynotify.Notification( "Cole Raby", "Hey pal, what's up with the party " "next weekend? Will you join me " "and Anna?", "notification-message-im") n.show()
def __init__(self): if pynotify: pynotify.init("periscope subtitles downloader")
#!/usr/bin/env python import pynotify import pyinotify from os.path import expanduser, join from mailbox import MaildirMessage maildir = expanduser('~/Mail') pynotify.init('offlineimap_notify') with open(expanduser('~/.mutt/mailboxes')) as f: mailboxes = f.read() boxes = [] for m in mailboxes.strip('\n').split(" "): if not m == 'mailboxes': boxes.append(m.replace('"', '').replace('+', '')) def new_mail(event): with open(event.pathname, 'r') as f: mail = MaildirMessage(message=f) efrom = 'From: ' + mail['From'] esubject = 'Subject: ' + mail['Subject'] n = pynotify.Notification( "New mail in " + '/'.join(event.path.split('/')[-3:-1]), efrom + "\n" + esubject) n.set_timeout(8000) n.show()
if platform.mac_ver()[0] > '10.': sys.exit(os.system( 'osascript -e \'display dialog "Please use goproxy-macos rather than goproxy-gtk" buttons {"OK"} default button 1 with icon caution with title "GoProxy GTK"\'')) try: import pygtk pygtk.require('2.0') import gtk # gtk.gdk.threads_init() except Exception: sys.exit(os.system( 'gdialog --title "GoProxy GTK" --msgbox "Please install python-gtk2" 15 60')) try: import pynotify pynotify.init('GoProxy Notify') except ImportError: pynotify = None try: import appindicator except ImportError: if os.getenv('XDG_CURRENT_DESKTOP', '').lower() == 'unity': sys.exit(gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, u'Please install python-appindicator').run()) appindicator = None try: import vte except ImportError: sys.exit(gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, u'Please install python-vte').run())
def align(self): id = True ppservers = () job_server = pp.Server(ppservers=ppservers) while id: # this should test to make sure there are still alignments to do print 'getting clustalw_work_unit' try: clustalw_work_unit = self.phamServer.request_seqs(self.client) if not clustalw_work_unit.query_id: print 'no clustalw alignments available...sleeping' logo = os.path.join(os.path.dirname(__file__),"pixmaps/phamerator.png") #print "logo: %s" % logo try: import pynotify if pynotify.init("Phamerator"): n = pynotify.Notification("Phamerator Update", "No Clustalw alignments left to do...sleeping", "file:///%s" % logo) n.show() else: pass #print "there was a problem initializing the pynotify module" except: pass time.sleep(30) continue except Exception, x: print ''.join(Pyro.util.getPyroTraceback(x)) server, db = self.phamServer.request_db_info() #c = db_conf(username=self.username, password=self.password, server=server, db=db) #clustalw_work_unit.set_cursor(c) print 'got it' try: import pynotify if pynotify.init("Phamerator"): logo = os.path.join(os.path.dirname(__file__),"pixmaps/phamerator.png") #print "logo: %s" % logo n = pynotify.Notification("Phamerator Update", "Clustalw alignments in progress for id %s" % clustalw_work_unit.query_id, "file:///%s" % logo) n.show() else: pass #print "there was a problem initializing the pynotify module" except: pass self._logger.log('aligning sequences') ########################################################################### # BEGIN MATT'S ALTERATIONS # # # ########################################################################### results = [] open_files = [] # tuple of all parallel python servers to connect with # Creates jobserver with automatically detected number of workers #grab number of processors numcpus = job_server.get_ncpus() print "numcpus =",numcpus #for n, person in enumerate(people): #for seq in seqs: jobs = [] #for i,currentseq in enumerate(seqs): query_id = clustalw_work_unit.query_id query_translation = clustalw_work_unit.query_translation counter = 0 for record in clustalw_work_unit.database: subject_id, subject_translation = record.id, record.translation fname = os.path.join(self.rootdir, 'temp' + query_id + '_' + subject_id + '.fasta') f = open(fname, 'w') open_files.append(fname) open_files.append(fname.replace('.fasta','.dnd')) open_files.append(fname.replace('.fasta','.aln')) f.write('>%s\n%s\n>%s\n%s\n' % (query_id, query_translation, subject_id, subject_translation)) f.close() clustalw_infile = os.path.join(self.rootdir, 'temp' + str(query_id) + '_' + str(subject_id) + '.fasta') if float(Bio.__version__) >= 1.56: # pass the query id (qid) and the subject id (sid) to run_clustalw jobs.append(job_server.submit(clustalwAligner.run_clustalw, (clustalw_infile, query_id, subject_id), (), ())) else: cline = MultipleAlignCL(clustalw_infile) cline.set_output(os.path.join(self.rootdir, 'temp' + str(query_id) + '_' + str(subject_id) + '.aln')) # pass the query id (qid) and the subject id (sid) to run_clustalw jobs.append(job_server.submit(clustalwAligner.run_clustalw_old, (query_id, subject_id,cline), (), ("Bio.Clustalw",))) counter = counter + 3 if counter > 50: results = self.process_jobs(jobs, results, open_files) jobs = [] open_files = [] counter = 0 results = self.process_jobs(jobs, results, open_files) jobs = [] open_files = [] counter = 0 # must report everything back in atomic transaction print 'reporting scores back to server' try: self.phamServer.report_scores(clustalw_work_unit, results, self.client) except Exception, x: print ''.join(Pyro.util.getPyroTraceback(x)) print 'exiting on pyro traceback' sys.exit()
import os, sys, cookielib, urllib2, csv, pynotify, time from os.path import * from urlparse import urlparse from ConfigParser import RawConfigParser from zipfile import ZipFile from bs4 import BeautifulSoup from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork SETTINGS_FILE = '~/.lcurse/settings.cfg' ADDONS_FILE = '~/.lcurse/addons.csv' addons = [] pynotify.init('Basics') cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # default User-Agent ('Python-urllib/2.6') will *not* work opener.addheaders = [('User-Agent', 'Mozilla/5.0'),] config = RawConfigParser() appfolder = os.path.dirname(sys.argv[0]) windowIcon = appfolder + "/media/icon.png" try: if not os.path.exists(os.path.expanduser('~/.lcurse')): os.mkdir(os.path.expanduser('~/.lcurse')) config.read(os.path.expanduser(SETTINGS_FILE)) prefix = config.get('Settings', 'Prefix')
import platform try: import pygtk pygtk.require('2.0') import gtk gtk.gdk.threads_init() except Exception: sys.exit( os.system( u'gdialog --title "GoAgent GTK" --msgbox "\u8bf7\u5b89\u88c5 python-gtk2" 15 60' .encode(sys.getfilesystemencoding() or sys.getdefaultencoding(), 'replace'))) try: import pynotify pynotify.init('GoAgent Notify') except ImportError: pynotify = None try: import appindicator except ImportError: appindicator = None try: import vte except ImportError: sys.exit( gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, u'请安装 python-vte').run()) def spawn_later(seconds, target, *args, **kwargs):
All results, in addition to being displayed to the terminal, are sent as notifications to the desktop GUI. """ import os import sys from subprocess import call import gtk import pynotify # Display notifications import pyinotify # Filesystem event monitoring import coverage app_name = 'Yardbird' pynotify.init("%s Tests" % app_name) def run_tests(): num_failed = call(['./manage.py', 'test'], cwd='example') if num_failed: notify_tests_failed(num_failed) return False return True def generate_coverage(): try: os.unlink('./example/.coverage') except OSError: pass
print "\tx- and y-coordinates hints are ignored" print "\texpire-timeout is ignored" print "\tbody-markup is accepted but filtered" else: print "\tnone" def pushNotification(title, body, icon): n = pynotify.Notification(title, body, icon) n.set_hint_string("x-canonical-append", "") n.show() time.sleep(3) # simulate a user typing if __name__ == '__main__': if not pynotify.init("append-hint-example"): sys.exit(1) # call this so we can savely use capabilities dictionary later initCaps() # show what's supported printCaps() # try the append-hint if capabilities['x-canonical-append']: pushNotification("Cole Raby", "Hey Bro Coly!", "notification-message-im") pushNotification("Cole Raby", "What's up dude?", "notification-message-im")
#!/usr/bin/env python # enable/disable wifi device # author Kobelkov Sergey # license GPL, 2010 try: import gtk, pygtk, os, os.path, pynotify pygtk.require('2.0') except: print "Error: need python-notify, python-gtk2 and gtk" if __name__ == '__main__': if not pynotify.init("Timekpr notification"): sys.exit(1) if os.path.exists('/proc/easy_wifi_kill')==False: print("Easy slow down manager kernel module is not installed. Please, visit http://code.google.com/p/easy-slow-down-manager/ for mode details") sys.exit(1) f = open('/proc/easy_wifi_kill') s = int(f.read()) f.close s = 1-s g = open('/proc/easy_wifi_kill','w') g.write(str(s)) g.close if s==0: msg = "off" else: msg = "on" n = pynotify.Notification("Wifi state notification", "Wifi is "+msg+" now")
import gtk import gobject import getopt import os import pango import time import atexit from dbus import DBusException import pygtk pygtk.require('2.0') HAS_NOTIFY = True try: import pynotify if not pynotify.init("Wicd"): HAS_NOTIFY = False except ImportError: HAS_NOTIFY = False # Wicd specific imports from wicd import wpath from wicd import misc from wicd import dbusmanager import gui from guiutil import error, can_use_notify from wicd.translations import language ICON_AVAIL = True USE_EGG = False
#!/usr/bin/env python import dbus, gobject, time, re, pynotify, dbus from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject") purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface") gs = bus.get_object('org.gnome.ScreenSaver', '/org/gnome/ScreenSaver') pynotify.init('Chattd') isIdle = False chattd = [] def notify(sender, message): alert = pynotify.Notification( "Chat from " + sender[0:30], "You've been chatted by " + sender + " at " + time.strftime('%H:%M'), re.sub('/<.*>/', '', message)) alert.set_urgency(pynotify.URGENCY_NORMAL) alert.set_timeout(pynotify.EXPIRES_NEVER) alert.set_hint('x', (150 * ((len(chattd) // 10) + 1))) alert.set_hint('y', (120 * (len(chattd) % 10))) alert.show() def msg_recieved(account, sender, message, conversation, flags): if gs.GetSessionIdle() is 1: if sender not in chattd:
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> #----------------------------------------------------------------------------- import sys, os, time, atexit, urllib, urllib2, json, io, ConfigParser, csv from signal import SIGTERM from datetime import datetime, timedelta try: import pynotify if not pynotify.init("AA"): print("there was a problem initializing the pynotify module") except: print("you don't seem to have pynotify installed") guide = """ _.__o_oOoOo[ AA ]oOoOo_o__._ Usage: aa config <config> <value> ... sets the config value aa start ... starts the work session of the day aa stop ... stops the work session aa shout <message> ... alerts what he is doing now (online) aa post <message> ... alerts what he is doing now (offline)
from plover import log, __name__ as __software_name__ import pynotify import logging pynotify.init(__software_name__.capitalize()) class DbusNotificationHandler(logging.Handler): """ Handler using DBus notifications to show messages. """ def __init__(self): super(DbusNotificationHandler, self).__init__() self.setLevel(log.WARNING) self.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) def emit(self, record): level = record.levelno message = self.format(record) if level <= log.INFO: timeout = 10 urgency = 0 elif level <= log.WARNING: timeout = 15 urgency = 1 else: timeout = 0 urgency = 2 n = pynotify.Notification(__software_name__.capitalize(), message) n.set_timeout(timeout * 1000) n.set_urgency(urgency) n.show()
if opt == '-u': username = arg if opt == '-P': password = arg # Set server web port. www_port = 9000 for opt, arg in opts: if opt == '-w': try: www_port = int(arg) except ValueError: print_help() # Initialise notifications. pynotify.init('squeezebox-notify') notification = pynotify.Notification('Squeezebox Notify', 'Connecting to %s' % (server if port == 9090 else ('%s:%i' % (server, port,))), '/home/mmm/kode/squeezebox-notify/resources/squeezebox.jpg') notification.show() # Compile a regex for player related notifications, which are identified by a MAC address and then some. player_pattern = re.compile('^(([0-9a-f]{2}%3A){5}[0-9a-f]{2}) (.+)') # Start telnet clients (one a as listener, another to fetch info). listener = Telnet() listener.open(server, port) fetcher = Telnet() fetcher.open(server, port) # Authenticate, if necessary. if username and password:
else: event, arg1, arg2 = sys.argv[1:4] filename = None if event == 'MSG' and arg1 == 'IN': import pynotify, os, locale encoding = (locale.getdefaultlocale())[1] msg = 'sent you a message.' if SHORT_NICK and '@' in arg2: arg2 = arg2[0:arg2.index('@')] if filename is not None: f = file(filename) msg = f.read() pynotify.init('mcnotify') msgbox = pynotify.Notification(unicode(arg2, encoding), unicode(msg, encoding)) msgbox.set_timeout(3000) msgbox.set_urgency(pynotify.URGENCY_LOW) msgbox.show() if (CMD_MSG_IN): os.system(CMD_MSG_IN + '> /dev/null 2>&1') if filename is not None and os.path.exists(filename): os.remove(filename) pynotify.uninit() # vim:set noet sts=8 sw=8:
#-*- encoding: utf-8 -*- """ GUI front end for qrencode based on the work of David Green: <*****@*****.**> https://launchpad.net/qr-code-creator/ and inspired by http://www.omgubuntu.co.uk/2011/03/how-to-create-qr-codes-in-ubuntu/ uses python-zbar for decoding from files and webcam """ import sys, os from math import ceil from PyQt5 import QtCore, QtGui, QtWidgets from qrtools import QR try: import pynotify if not pynotify.init("QtQR"): print("DEBUG: There was a problem initializing the pynotify module") NOTIFY = True except: NOTIFY = False __author__ = "Ramiro Algozino" __email__ = "*****@*****.**" __copyright__ = "copyright (C) 2011 Ramiro Algozino" __credits__ = "David Green" __license__ = "GPLv3" __version__ = "1.1" class MainWindow(QtWidgets.QMainWindow): def __init__(self):
import pynotify from xl import covers, event, common, player, settings from xl.nls import gettext as _ from xlgui import icons from xlgui.preferences import widgets import notifyprefs logger = logging.getLogger(__name__) # This breaks stuff. if you want to enable it, set this to True and uncomment # the commented section in the UI designer file ATTACH_COVERS_OPTION_ALLOWED = False pynotify.init('exailenotify') class ExaileNotification(object): def __init__(self): self.notification_id = None self.exaile = None def __inner_preference(klass): """Function will make a property for a given subclass of Preference""" def getter(self): return settings.get_option(klass.name, klass.default or None) def setter(self, val): settings.set_option(klass.name, val)
1in1 show Hikma and exit 1 show Hikma every 1mn 5 show Hikma every 5mn 10 show Hikma every 10mn 15 show Hikma every 15mn 30 show Hikma every 30mn 60 show Hikma every 1h 120 show Hikma every 2h""" print help if Par == "--h" or Par == 'Help' or Par == 'help' or Par == '--help' : help() elif Par == "1in1" : while a : pynotify.init("Hikma") hikam1 = random.randrange(876) hikam = Data.database[hikam1] hikamfinal = str(hikam) notification = pynotify.Notification("حكمة", hikamfinal, "icons/hikma.png") notification.show() a = 0 elif Par == "1" : while a : pynotify.init("Hikma") hikam1 = random.randrange(876) hikam = Data.database[hikam1] hikamfinal = str(hikam) notification = pynotify.Notification("حكمة", hikamfinal, "icons/hikma.png") notification.show()
def __init__(self): pynotify.init("Init") self.ind = appindicator.Indicator( "nagios-checker", NAGIOS_ICON, appindicator.CATEGORY_APPLICATION_STATUS, ICONS_PATH) self.check_interval = CHECK_INTERVAL
def __init__(self, appname): self.appname = appname if not pynotify.init(appname): log("PyNotify failed to initialize with appname: %s" % appname, LEVEL_DEBUG)
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM: import gtknotification class Notification(object): def do_notify(self, summary, body, icon_file = None): if (icon_file == None or not os.path.isfile(icon_file) or os.path.getsize(icon_file) == 0): icon_file = utils.get_ui_object(os.path.join('image','ic64_hotot.png')); icon_file = 'file://' + icon_file title = _("Hotot Notification") text = summary + '\n' + body gobject.idle_add(gtknotification.gtknotification, title, text, icon_file) update = do_notify show = str notify = Notification() else: import pynotify pynotify.init(_("Hotot Notification")) notify = pynotify.Notification('Init', '') webv = None app = None http_code_msg_table = { 404: 'The URL you request does not exist. Please check your API Base/OAuth Base/Search Base.' , 401: 'Server cannot authenticate you. Please check your username/password and API base.' , 500: 'Server is broken. Please try again later.' , 502: 'Server is down or being upgraded. Please try again later.' , 503: 'Server is overcapacity. Please try again later.' } def init_notify(): if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM: return
# -*- coding: utf-8 -*- """ Created on Mon Apr 25 23:25:11 2016 @author: Prateek """ #PNR checking, Indian Railway import requests from bs4 import BeautifulSoup import pynotify from time import sleep try: pnr = input('Enter pnr ') url = 'http://www.railyatri.in/pnr-status/' + pnr sc = requests.get(url) soup = BeautifulSoup(sc.text, 'lxml') cs = soup.findAll('span', {'class': 'arrival_span'}) bs = soup.findAll('span', {'class': 'departure'}) pynotify.init('test') n = pynotify.Notification( 'PNR Status', 'Booking Satus: ' + bs[1].text + '\n' + 'Curent Satus: ' + cs[2].text) n.show() except requests.exceptions.ConnectionError: pynotify.init('test') n = pynotify.Notification('Connection Issue', 'No internet found') n.show()
from logger import * import sys import pynotify from sqlalchemy import create_engine, func, desc from sqlalchemy.orm import sessionmaker from models import * dmenu = Dmenu( font='Inconsolata for Powerline:pixelsize=16:antialias=true:hinting=true', lines=10).dmenu engine = create_engine(db_connect_string, echo=True) Session = sessionmaker(engine) session = Session() logopen() pynotify.init("ETR") if sys.argv[1] == 'get_current_event': log(3, 'Getting running tasks') tasks = session.query(Task).filter(Task.started == True).all() if tasks: if len(tasks) > 1: log(3, 'ERROR, should be only one task running.', started_tasks=map(lambda task: task.id, tasks)) for started_task in tasks: if started_task.started: log(3, 'Stopped working on previously started task', task_id=started_task.id) events = session.query(Event).filter(