def main(): parser = ArgumentParser() parser.add_argument('-c', '--config', help='A path to config file', default="~/.pyvpn") args = parser.parse_args() Notify.init('SofToken') try: config = get_config(expanduser(args.config)) token = SoftToken(config['tuser'], config['consoleui'], config['wine']) password = token.get_password(config['tpassword']) copy_to_clipboard(password) notification = Notify.Notification.new( "SoftToken", "VPN password copied to clipboard", "dialog-information" ) notification.show() except Exception as e: notification = Notify.Notification.new( "SoftToken", str(e), "dialog-information" ) notification.show()
def notifiersystem(last_comm): Notify.init("Football score") notification = Notify.Notification.new(last_comm) notification.show()
def main(argv): reload(sys); sys.setdefaultencoding('utf-8'); #타겟 준비 targets = argv[1:] #알림 메시지 초기화 Notify.init("make_comic_book") title = u'그림책 만들기' if not targets: msg = u'대상을 선택해 주세요!' Notify.Notification.new(title, msg, '').show() sys.exit(1) #변환 for target in targets: try: cbz = MakeCbz().make(target, u'.') except Exception, err: Notify.Notification.new(title, unicode(err), '').show() raise SystemExit() ufp.trashPut(target) #메시지 작성 msg = u"<b>%(target)s</b>를 <b>%(cbz)s</b>로 묶었습니다." % locals() #알림 메시지 보이기 Notify.Notification.new(title, msg, '').show()
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")
def __init__(self, controls): FControl.__init__(self, controls) Gtk.Window.__init__(self, Gtk.WindowType.POPUP) self.set_position(Gtk.WindowPosition.MOUSE) self.connect("leave-notify-event", self.on_leave_window) Notify.init('Foobnix')
def func(): #Enter your Twilio accountSid and authToken accountSid = "" authToken = "" #Parser for the Cricbuzz XML Page in cricbuzz library cric = CricbuzzParser() #Connecting to the Twilio API twilioClient = TwilioRestClient(accountSid, authToken) myTwilioNumber = "" destCellPhone = "" #Getting the XML File and extracting the matches from it match = cric.getXml() details = cric.handleMatches(match) #Filtering out the NoneType Objects in 'details' details = filter(None,details) message = 'No Match Available' for i in details: #Traversing the list if 'Match State' in i: #If the match state key is present in the dict if i['Match State'] == 'inprogress': #If the match is in progress message = i['Team']+ " "+ i['Match Format'] + ' Match at ' + i['Venue']+ "\n" +i['Batting team'] + ' ' + i['Batting Team Runs'] + '/'+i['Batting Team Wickets'] + ' Overs: ' + i['Batting Team Overs'] #Generates the message Notify.init("Live Scores") #Shows Notification on the desktop Notify.Notification.new("Match currently in progress:",message).show() #Sends message to the phone number myMessage = twilioClient.messages.create(body = "Match Currently in progress: " + message, from_=myTwilioNumber, to=destCellPhone) #Defines an interval of 60 seconds time.sleep(60)
def _main(): parser = ArgumentParser() parser.add_argument( '-n','--name', help='name', default="notify-pipe") parser.add_argument( '-i','--icon', help='icon ', default="") args = parser.parse_args() Notify.init("notify-pipe") name = args.name Hello = Notify.Notification.new (name) Hello.show() lines_iterator = iter(sys.stdin.readline, b"") try: for line in lines_iterator: if line: print(line,end="") sys.stdout.flush() Hello.update(name, line, args.icon) Hello.show() else: break except KeyboardInterrupt: sys.exit(0)
def enable(self): self._max_mails = int(self.get_config()['max_visible_mails']) self._notification_server_wait_event.clear() self._notification_server_ready = False self._notifications = {} # initialize Notification if not self._initialized: Notify.init("Mailnag") self._is_gnome = os.environ.has_key('GDMSESSION') and \ (os.environ['GDMSESSION'] == 'gnome') self._initialized = True def mails_added_hook(new_mails, all_mails): self._notify_async(new_mails, all_mails) def mails_removed_hook(remaining_mails): if remaining_mails == 0: # no mails (e.g. email client has been launched) -> close notifications self._close_notifications() self._mails_added_hook = mails_added_hook self._mails_removed_hook = mails_removed_hook controller = self.get_mailnag_controller() hooks = controller.get_hooks() hooks.register_hook_func(HookTypes.MAILS_ADDED, self._mails_added_hook) hooks.register_hook_func(HookTypes.MAILS_REMOVED, self._mails_removed_hook)
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 = []
def notification(self): while(True): live_scores, valid = Fixtures().fixture() for score in live_scores: match_time = score['time'] status = score['status'] team = score['team'] score = score['score'] score_time = score + ' (Time:' + match_time + ')' if status != 1: if status == 3: score_time = score + ' (FT)' elif status == 4: score_time = score + ' (HT)' Notify.init("Live Score") send_notification = Notify.Notification.new(team, score_time, ) send_notification.set_icon_from_pixbuf(self._icon) send_notification.show() time.sleep(3) send_notification.close() Notify.uninit() if not valid: break time.sleep(300)
def status(project, args): try: import gi gi.require_version('Notify','0.7') from gi.repository import Notify from gi.repository import GLib except: return global inited if not inited: Notify.init("sgmake") inited = True try: #if not "step" in args and not "start" in args: if "success" == args: Notify.Notification.new( "sgmake", "Build Complete", 'dialog-information' ).show() if "failure" == args: Notify.Notification.new( "sgmake", "Build Failure", 'dialog-error' ).show() except GLib.Error: pass # notifications disabled
def main(): setup_logging() logging.info('Starting 60 min notifier') Notify.init('Check Tasks') notify_body = "eventually this will pull from org agenda" # Hello = Notify.Notification.new('Task Check', notify_body, 'alert.xpm') # show for 5 minutes # Hello.set_timeout(100000) while True: logging.info('Start of while true loop') to_sleep = 3600 - time.time() % 3600 logging.debug('Sleep time is ' + str(to_sleep)) # sleep for the remaining seconds until the half hour time.sleep(to_sleep) logging.info('Showing notification') args = ['uclock'] out_bytes = subprocess.check_output(args) out_text = out_bytes.decode('utf-8') logging.debug(out_text) # alert_window() # Hello.show() logging.error('Somehow left while true loop')
def __init__(self): Notify.init("A3KTorrent") self.filename = 'path' self.filepath = 'folder' #default values to check! self.builder = Gtk.Builder() self.builder.add_from_file("layout.glade") self.builder.get_object('window1').connect('delete-event',Gtk.main_quit) self.dialog=self.builder.get_object('dialog1') self.dialog.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dialog2=self.builder.get_object('dialog2') self.dialog2.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dialog3 = self.builder.get_object("dialog3") self.dialog3.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.window = self.builder.get_object("window1") self.window.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.progressbar= self.builder.get_object("progressbar1") #PROGRESSBAR self.progressbar.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.aboutdialog = self.builder.get_object("aboutdialog1") self.aboutdialog.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.label = self.builder.get_object("label1") self.builder.get_object("filechooserbutton2").set_action(Gtk.FileChooserAction.SELECT_FOLDER) #filechooser 2 self.search_field = self.builder.get_object("search_field") self.search_field.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dow_label = self.builder.get_object("dow_speed")
def on_module_selected(self): if self.loaded: return print("Loading Notifications module") Notify.init("cinnamon-settings-notifications-test") page = SettingsPage() self.sidePage.add_widget(page) settings = page.add_section(_("Notification settings")) switch = GSettingsSwitch(_("Enable notifications"), "org.cinnamon.desktop.notifications", "display-notifications") settings.add_row(switch) switch = GSettingsSwitch(_("Remove notifications after their timeout is reached"), "org.cinnamon.desktop.notifications", "remove-old") settings.add_reveal_row(switch, "org.cinnamon.desktop.notifications", "display-notifications") switch = GSettingsSwitch(_("Show notifications on the bottom side of the screen"), "org.cinnamon.desktop.notifications", "bottom-notifications") settings.add_reveal_row(switch, "org.cinnamon.desktop.notifications", "display-notifications") button = Button(_("Display a test notification"), self.send_test) settings.add_row(button) settings = page.add_section(_("Media keys OSD")) combo = GSettingsComboBox(_("Media keys OSD size"), "org.cinnamon", "show-media-keys-osd", MEDIA_KEYS_OSD_SIZES) settings.add_row(combo)
def get_cpu_speeds(self): message = '' try: r = requests.post('https://www-wohnheim.uni-regensburg.de/utils/login.py/checkAuthentication', data=payload) soup = BeautifulSoup(r.text) title = soup.findAll('title')[0].get_text() login_page = title.find('Login')>0 if(login_page): notify.init('indicator-cpuspeed') notify.Notification.new("<b>Login failed</b>", "<b>Change password?</b>", None).show() notify.uninit() rzdatatable = soup.find("table", {"id": "rzdatatable"}) data = rzdatatable.findAll('tr')[1] wohnheim = data.findAll('td')[0].get_text() zimmer = data.findAll('td')[1].get_text() status = data.findAll('td')[2].span.get_text() empfangen = data.findAll('td')[3].get_text() gesendet = data.findAll('td')[4].get_text() summe = data.findAll('td')[5].get_text() limit = data.findAll('td')[6].get_text() # print(wohnheim + "(" + zimmer + "), status: " + status) # print("Volumen: " + str(summe) + "mb von " + str(limit) + "mb (" + str(round(100*float(summe)/float(limit),2)) + "%), davon " + gesendet + "mb gesendet und " + empfangen + "mb empfangen.") message = str(summe) except requests.ConnectionError: message = 'No Connection' return message
def __init__(self, colors): super().__init__() # Save config self.__colors = colors # Start lemonbar in a subprocess self.__bar = subprocess.Popen(['lemonbar', '-B', colors['bg'], '-F', colors['fg'], '-f', "Terminesspowerline-8", '-f', "Ionicons-10", '-f', 'Icons-8', '-f', 'FontAwesome-10', '-f', "Serif-9", '-a', '30' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Init notifier for displaying volume stats with dunst Notify.init('bar') # Panel variables to save intermediate states self.__calendar = None self.__volume = None self.__vpn = None self.__state = None self.__spotify = None self.spotify_callback_value = None self.keyboard_callback_value = None self.status = {'date':'', 'spotify':'', 'vol':'', 'wlan':'', 'eth':'', 'vpn':'', 'bat':''} self.workspaces = '' self.title = '' self.current_power = '' self.old_power = '' # Status toggles self.__show_eth = False self.__show_wlan = False self.__show_battery = False self.__show_spotify = False self.__run = True
def prepare_notify(self): try: from gi.repository import Notify self.has_notifications = True except ImportError: logging.warning ("libnotify not found.") return "libnotify not found" # Work-around Ubuntu's incompatible workaround for Gnome's API breaking mistake. # https://bugzilla.gnome.org/show_bug.cgi?id=702390 old_add_action = Notify.Notification.add_action def new_add_action(*args): try: old_add_action(*args) except TypeError: old_add_action(*(args + (None,))) Notify.Notification.add_action = new_add_action Notify.init('Pithos') self.notification = Notify.Notification() self.notification.set_category('x-gnome.music') self.notification.set_hint_string('desktop-icon', 'pithos') caps = Notify.get_server_caps() if 'actions' in caps: logging.info('Notify supports actions') self.supports_actions = True if 'body-markup' in caps: self.escape_markup = True if 'action-icons' in caps: self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True))
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()
def somethingFinished(self, subject, body, soundfile): timerSound = os.path.join(os.path.dirname(__file__), soundfile) Notify.init("Timer finished") notification = Notify.Notification.new (subject, body, NOTIFICATION_ICON) notification.set_urgency(Notify.Urgency.CRITICAL) notification.show() subprocess.Popen(["paplay", timerSound])
def notify_bat_low(): print '\nBattery is at ' + str(bat_percentage()) + '%\n' Notify.init('Battery low!') message=Notify.Notification.new('Battery low!', 'Battery is at ' + str(bat_percentage()) + '%', '/usr/share/icons/gnome/32x32/status/battery-empty.png') message.show()
def __init__(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) self.bus = dbus.SessionBus() self.bus.add_signal_receiver( self.notify, signal_name="IrssiNotify", dbus_interface="org.irssi.Irssi", path="/org/irssi/Irssi" ) Notify.init("irssi")
def process_selection(self, filelist): self.conf.read(self.configfile) # Run in Preview Mode if self.conf.get(c, "preview_mode") == "True": if filelist != []: prelist = os.getenv('HOME') + '/.fileorganizer-preview.log' FILE = open(prelist, "w") FILE.close() damlist = os.getenv('HOME') + '/.fileorganizer-damaged.log' FILE = open(damlist, "w") FILE.close() for item in filelist: item = fileops.MusicFile(self, item) item.preview() Notify.init('Fileorganizer') title = 'Fileorganizer' note = 'Preview Has Completed' notification = Notify.Notification.new(title, note, None) Notify.Notification.show(notification) # Show Results of preview self.results(prelist, damlist) else: # Run Normally self.organize(filelist) Notify.init('Fileorganizer') title = 'Fileorganizer' note = 'Your selection is organised' notification = Notify.Notification.new(title, note, None) Notify.Notification.show(notification)
def fire_notify(self, msg="", title="GitPushNotify", add_callback=None, path=None): # raise Exception(999) Notify.init("New commit") self.log.info("Called fireNotify()") try: # n = notify2.Notification(title, msg, '') n = Notify.Notification.new(title, msg) if len(self.nn) > 10: self.nn = [] self.nn.append(n) self.log.info("append data") n.set_urgency(1) self.log.info("set_urgency") if add_callback: self.log.info("add callback ") n.connect("closed", self.empty_cb) n.add_action("clicked", " pull all branches ", self.call_back_fire, path) self.log.info("show") try: n.show() except Exception as e: self.log.info("error while show: %s" % e) else: self.log.info("showed") finally: self.log.info("end show") except Exception as e: self.log.info("error in firenotify: %s" % e) traceback.print_exc() else: self.log.info("ok firenotify")
def time_manager(work_seconds, sleep_seconds): mm = MouseManager() km = KeyboardManager() Notify.init("time manager") while True: time.sleep(work_seconds) mm.disable_mouse() km.disable_keyboard() message = Notify.Notification.new("主任, 该休息了!", 'Time to sleep!!!', 'dialog-information') message.show() # There's a bug in disabling mouse delta = 5 m_sleep_seconds = sleep_seconds while m_sleep_seconds > 0: mm.disable_mouse() if m_sleep_seconds >= delta: time.sleep(delta) m_sleep_seconds -= delta else: time.sleep(m_sleep_seconds) break mm.enable_mouse() km.enable_keyboard()
def __init__(self, token=None): self.indicator = AppIndicator3.Indicator.new( 'digitalocean-indicator', '', AppIndicator3.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) icon_uri = get_media_file("digitalocean-indicator.svg") icon_path = icon_uri.replace("file:///", '') self.indicator.set_icon(icon_path) Notify.init('DigitalOcean Indicator') self.PreferencesDialog = DoPreferencesDialog self.settings = Gio.Settings( "com.andrewsomething.digitalocean-indicator") self.settings.connect('changed', self.on_preferences_changed) self.preferences_dialog = None self.preferences_changed = False if token: self.do_api_token = token else: self.do_api_token = self.settings.get_string("do-api-token") self.menu = Gtk.Menu() # Add items to Menu and connect signals. self.build_menu() # Refresh menu every 10 min by default self.change_timeout = False self.interval = self.settings.get_int("refresh-interval") GLib.timeout_add_seconds(self.interval * 60, self.timeout_set)
def autoSuspender(self, minPercent=5): # update even full capacity in case the battery has been changed self.full = int(cat("/sys/class/power_supply/BAT0/energy_full")) self.update() # hibernate only if battery is discharging if self.state != "Discharging": return {} # return empty dict, main loop expects it # test if everything is OK for var in (self.full, self.now, self.state, self.percent): if var is None: return {} # return empty dict, main loop expects it # test battery level if self.percent <= minPercent: Notify.init("Hibernation") battLevel = Notify.Notification.new("Warning:", "Battery level at " + str(self.percent) + "%.", "") battLevel.set_urgency(Notify.Urgency.CRITICAL) battLevel.show() warning = Notify.Notification.new("Warning:", "Hibernation in 10 seconds...", "") warning.set_urgency(Notify.Urgency.CRITICAL) warning.show() time.sleep(10) battLevel.close() warning.close() Notify.uninit() subprocess.call("systemctl hibernate", shell=True) return {} # return empty dict, main loop expects it
def __init__(self): # Create variables # See how to define this in a better way # (But for now 0 - ReadyToWork, 1 - Working, 2 - ReadyToBreak, 3 - InBreak) self.state = 0 self.work_value = 0 self.break_value = 0 self.timer_value = 0 self.read_options_file() self.counter_timeout_id = 0 # Define icons and notifications by state self.icon_by_state = {0: 'work_gray', 1: 'work_red', 2: 'break_gray', 3: 'break_green'} self.notification_by_state = {1: 'Your work time is over. You should take a break!', 3: 'Your break is over. Ready to get back to work?'} self.icons_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icons/') # Create the Indicator instance self.ind = appindicator.Indicator.new_with_path( "pTimer", "work_gray", appindicator.IndicatorCategory.APPLICATION_STATUS, self.icons_path) self.ind.set_status(appindicator.IndicatorStatus.ACTIVE) self.ind.set_label(self.get_time_string(), "00:00:00") # Init notifications notify.init('pTimer') # Init menu class self.menu = PMenu(self) self.options_window = None
def __init__(self): cfg = fedmsg.config.load_config(None, []) moksha_options = { self.config_key: True, "zmq_subscribe_endpoints": ','.join( ','.join(bunch) for bunch in cfg['endpoints'].values() ), } cfg.update(moksha_options) moksha.hub.setup_logger(verbose=True) # Despite what fedmsg.config might say about what consumers are enabled # and which are not, we're only going to let the central moksha hub know # about *our* consumer. By specifying this here, it won't even check # the entry-points list. consumers, prods = [self], [] moksha.hub._hub = moksha.hub.CentralMokshaHub(cfg, consumers, prods) fedmsg.consumers.FedmsgConsumer.__init__(self, moksha.hub._hub) self.session_bus = dbus.SessionBus() bus_name = dbus.service.BusName(self.bus_name, bus=self.session_bus) dbus.service.Object.__init__(self, bus_name, self._object_path) Notify.init("fedmsg") Notify.Notification.new("fedmsg", "activated", "").show()
def __init__(self, title=""): Gtk.Window.__init__(self, title=title) self.connect('delete-event', Gtk.main_quit) DBusGMainLoop(set_as_default=True) self._bus = dbus.SessionBus() self._daemon = self._bus.get_object(DBUS_BUS_NAME, DBUS_DAEMON_PATH) self._daemon_i = dbus.Interface(self._daemon, DBUS_BUS_NAME) self._daemon.connect_to_signal('state_changed', self._state_changed_handler) Notify.init("Pymodoro") self.status_icon = Gtk.StatusIcon.new_from_file(self.get_icon()) self.status_icon.connect("popup-menu", self._right_click_handler) self.menu = Gtk.Menu() self.mi_start = Gtk.MenuItem() self.mi_start.set_label("Start") self.mi_stop = Gtk.MenuItem() self.mi_stop.set_label("Interrupt") self.mi_quit = Gtk.MenuItem() self.mi_quit.set_label("Quit") self.mi_start.connect("activate", self._daemon_i.start_pomodoro) self.mi_stop.connect("activate", self._daemon_i.reset_pomodoro) self.mi_quit.connect("activate", Gtk.main_quit) self.menu.append(self.mi_start) self.menu.append(self.mi_stop) self.menu.append(self.mi_quit) self._menu_setup()
def let_it_rain(): GObject.threads_init() Gst.init(None) signal.signal(signal.SIGINT, signal.SIG_DFL) Notify.init("silver-rain") # Create system directories if not os.path.exists(IMG_DIR): os.makedirs(IMG_DIR) # Initialize config config.setup() # Create directory for recordings if not os.path.exists(config.recs_dir): os.makedirs(config.recs_dir) # Load css css_load() # Init translation set_translation() # Init application silver_app = SilverApp() # Setup dbus service service = SilverService(silver_app) # Run loop Gtk.main() # Cleanup silver_app.clean() Notify.uninit()
src = parsing("SRC=", line) dst = parsing("DST=", line) proto = parsing("PROTO=", line) spt = parsing("SPT=", line) dpt = parsing("DPT=", line) commandIptables = "INPUT -p " + proto + " -i " + interface + " -s " + src + " -d " + dst if dpt != None : commandIptables = commandIptables + " --dport " + dpt commandIptables = commandIptables + " -j ACCEPT" commandUfw = "ufw allow from " + interface + " to " + out + " proto " + proto if dpt != None : commandUfw = commandUfw + " port " + dpt Notify.init('Ubuntu Firewall Notification') notif = Notify.Notification.new( _("Ubuntu Firewall Notification"), # title _("A packet has been bloqued by the firewall"), # message 'dialog-information' # icon ) # add the custom notification action notif.add_action( 'permanent', _('Allow traffic permanently'), # Button text callback, # function callback de notre bouton commandUfw, # fonction qui supprime les user_datas 0 ) notif.add_action( 'session',
def quit(_): Notify.uninit() gtk.main_quit()
def onQuit(self, *args): Notify.uninit() Gtk.main_quit()
def onShowOrHide(self, *args): if self.window_is_hidden: window.show() else: window.hide() self.window_is_hidden = not self.window_is_hidden def onQuit(self, *args): Notify.uninit() Gtk.main_quit() # Handle pressing Ctr+C properly, ignored by default signal.signal(signal.SIGINT, signal.SIG_DFL) builder = Gtk.Builder() builder.add_from_file('gtk-example.glade') builder.connect_signals(Handler()) window = builder.get_object('window1') window.set_icon_from_file(ICON) window.show_all() entry = builder.get_object('entry1') menu = builder.get_object('menu1') icon = TrayIcon(APPID, ICON, menu) Notify.init(APPID) Gtk.main()
def run(self): self.config = configparser.ConfigParser( interpolation=configparser.ExtendedInterpolation(), inline_comment_prefixes=('#', ',')) self.config.read(configfile) log_count = self.config['Common'].getint('log-count', logcount) log_size = self.config['Common'].getint('log-size', logsize) log_level = self.config['Common'].get('log-level', loglevel) log_file = os.path.expanduser(self.config['Common'].get( 'log-file', logfile)) log_formatter = logging.Formatter( "%(asctime)s [%(levelname)-5.5s] %(message)s", "%Y-%m-%d %H:%M:%S") log_file_handler = RotatingFileHandler(log_file, maxBytes=log_size, backupCount=log_count) log_file_handler.setFormatter(log_formatter) log_console_handler = logging.StreamHandler() log_console_handler.setFormatter(log_formatter) self.logger = logging.getLogger("borg") self.logger.addHandler(log_file_handler) self.logger.addHandler(log_console_handler) # parse and set log level level = logging.getLevelName(log_level.upper()) if isinstance(level, int): self.logger.setLevel(level) else: self.logger.setLevel(logging.INFO) Notify.init("BorgBackup") self.notifications = [] self.log = {} # instantiate our borg wrapper self.borg = Borg(self.logger, self.json_callback, self) # setup schedule that will regularily execute backups self.sched = sched.scheduler() # extract all sections beginning with 'repo-' self.repos = [ self.config[repo] for repo in self.config.sections() if repo.startswith('repo-') ] for repo in self.repos: # schedule backups now, will reschedule itself self.handle_repo(repo) while True: Gtk.main_iteration_do(False) self.sched.run(blocking=False) time.sleep(1)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help='the nickname used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id note = Notify.Notification.new(Notify.get_app_name(),'Micno with Assistant は動作中です','mic-volume-high') note.set_urgency(Notify.Urgency.NORMAL) note.show() with Assistant(credentials, device_model_id) as assistant: global device_id_global, device_model_id_global events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') device_id_global = device_id device_model_id_global = device_model_id if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) process_event(event)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import subprocess from gi.repository import Notify, Gtk Notify.init('Micno With Assistant') import argparse import json import os.path import pathlib2 as pathlib import google.oauth2.credentials from google.assistant.library import Assistant from google.assistant.library.event import EventType from google.assistant.library.file_helpers import existing_file from google.assistant.library.device_helpers import register_device try: FileNotFoundError
parser.add_argument( '--urgency', help='LOW, NORMAL, CRITICAL', choices=['LOW', 'NORMAL', 'CRITICAL'], default='NORMAL' ) parser.add_argument( '--hints', help='list of comma sep options', action='append', default=[] ) args = parser.parse_args() Notify.init('Interactive Notifications') notification = Notify.Notification.new(args.summary, args.body, args.icon) for hint in args.hints: key, value = hint.split(',', 1) notification.set_hint_string(key, value) for action in args.action: action_id, action_label = action.split(',', 1) notification.add_action( action_id, action_label, action_callback, None )
def __init__(self): Notify.init("mintUpload")
def main(indicator): indicator.set_status(appindicator.IndicatorStatus.ACTIVE) indicator.set_menu(build_menu()) notify.init(APPINDICATOR_ID) gtk.main()
def __init__(self): logger = None if LOGGING: import logging logger = logging.getLogger(APP_NAME) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(ch) self.logger = logger log = log().log Notify.init("Nemo pastebin extension") class PastebinThread(Thread): def __init__(self, settings, filename): self.settings = settings self.filename = filename Thread.__init__(self) def run(self): log("PastebinThread started!") cmdline = ["pastebinit"] options = {} options['-b'] = "http://" + self.settings.get_string("pastebin") options['-a'] = self.settings.get_string("author")
def notify(self, detail): Notify.Notification("mintUpload", detail, ICONFILE).show()
def done(self): self.close() Notify.uninit() Gtk.main_quit()
def quit(self, source=None): # send dead signal to tcp server self.send('dead') notify.uninit() Gtk.main_quit()
def main(): Notify.init("calendar-indicator") CalendarIndicator() Gtk.main()
from gi.repository import Notify Notify.init("App Name") Notify.Notification.new("Hi").show()
#!/usr/bin/env python3 import i3ipc from gi.repository import Notify Notify.init("i3-fullscreen-manager") notify_pause = Notify.Notification.new("DUNST_COMMAND_PAUSE", "", "dialog-information") notify_unpause = Notify.Notification.new("DUNST_COMMAND_RESUME", "", "dialog-information") def on_window(self, e): if e.container.focused: if e.container.fullscreen_mode: notify_pause.show() else: notify_unpause.show() if e.container.floating.endswith("on") \ and e.container.fullscreen_mode == 0 \ and e.container.window_rect.width == 3840 \ and e.container.window_rect.height == 2160: e.container.command("fullscreen enable") conn = i3ipc.Connection() conn.on('window', on_window) conn.main()
from base64 import b64encode from os.path import expanduser import gi gi.require_version('Notify', '0.7') gi.require_version('Gtk', '3.0') from gi.repository import Notify from gi.repository import Gtk from .Base import Base # One time initialization of libnotify Notify.init('Screenshot clip and upload') class ScreenshotNotification(Base, Notify.Notification): def __init__(self, **kwargs): super().__init__() """ :param kwargs: """ Notify.Notification.__init__(self, summary=kwargs['summary'], body=kwargs['body']) # icon = dialog-information, dialog-warn, dialog-error kwargs['icon'] = 'dialog-information'
def __init__(self): self.update_watched() Notify.init('Terminator') return None
def throwNotification(self): Notify.init("Book My Show Tracker") Notify.Notification.new("Tickets at " + self.name + " are open now").show()
""" return False class DesktopNotification(BaseDesktopNotification): pass try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify except (ImportError, ValueError): pass else: if not Notify.init("i3pystatus"): raise ImportError("Couldn't initialize libnotify") # List of some useful icon names: # battery, battery-caution, battery-low # … class DesktopNotification(DesktopNotification): URGENCY_LUT = ( Notify.Urgency.LOW, Notify.Urgency.NORMAL, Notify.Urgency.CRITICAL, ) def display(self): notification = Notify.Notification.new(self.title, self.body,
#!/usr/bin/python3 ## -*- coding: utf-8 -*- import sys, os, json, pyperclip, socketserver, socket, threading from gi.repository import Notify Notify.init("Cross Clip") class Config: def __init__(self): self.readFile() def readFile(self): f = open('config.json') lines = f.readlines() self.json = json.loads("\n".join(lines)) f.close() def save(self): f = open('config.json', 'w') json.dump(self.json, f) f.close() config = Config() #gCn bridge connectedClients = [] class ClientThread(socketserver.BaseRequestHandler): stopnow = False
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 try: if Notify.init("Hello world"): alert = Notify.Notification.new("ARP poisoning detector", "Start", "dialog-information") alert.show() bash_notif = False else: commands.getoutput( "su - {} -c 'notify-send \"ARP poisoning detector\" \"Start\" --icon=dialog-information'" .format(user)) bash_notif = True except: commands.getoutput( "su - {} -c 'notify-send \"ARP poisoning detector\" \"Start\" --icon=dialog-information'" .format(user)) bash_notif = True
def __init__(self): super(PVPNApplet, self).__init__() self.country_codes = country_codes # Keep a list of country codes # Init QSystemTrayIcon self.tray_icon = QSystemTrayIcon(self) self.tray_icon.setIcon(QIcon('icons/16x16/protonvpn-disconnected.png')) # Init libnotify Notify.init('ProtonVPN') # Refresh server list, store the resulting servers so we can populate the menu self.servers = self.update_available_servers() # Menu actions connect_fastest_action = QAction('Connect fastest', self) reconnect_action = QAction('Reconnect', self) disconnect_action = QAction('Disconnect', self) status_action = QAction('Status', self) connect_fastest_sc_action = QAction('Secure Core', self) connect_fastest_p2p_action = QAction('P2P', self) connect_fastest_tor_action = QAction('Tor', self) connect_random_action = QAction('Random', self) show_protonvpn_applet_version_action = QAction('About ProtonVPN-Applet', self) show_protonvpn_version_action = QAction('About ProtonVPN', self) quit_action = QAction('Exit', self) self.show_notifications_action = QAction('Show Notifications') self.show_notifications_action.setCheckable(True) self.show_notifications_action.setChecked(False) # Triggers quit_action.triggered.connect(qApp.quit) connect_fastest_action.triggered.connect(self.connect_fastest) disconnect_action.triggered.connect(self.disconnect_vpn) status_action.triggered.connect(self.status_vpn) show_protonvpn_applet_version_action.triggered.connect(self.show_protonvpn_applet_version) show_protonvpn_version_action.triggered.connect(self.get_protonvpn_version) connect_fastest_sc_action.triggered.connect(self.connect_fastest_sc) connect_fastest_p2p_action.triggered.connect(self.connect_fastest_p2p) connect_fastest_tor_action.triggered.connect(self.connect_fastest_tor) connect_random_action.triggered.connect(self.connect_random) reconnect_action.triggered.connect(self.reconnect_vpn) # Generate connection menu for specific countries connect_country_actions = [] for country_name in self.get_available_countries(self.servers): # Get the ISO-3166 Alpha-2 country code country_name_to_code = {v: k for k, v in country_codes.country_codes.items()} country_code = country_name_to_code[country_name] # Dynamically create functions for connecting to each country; each function just passes its respective # country code to `self.connect_fastest_cc()` setattr(self, f'connect_fastest_{country_code}', functools.partial(self.connect_fastest_cc, country_code)) # Generate an action for each country; set up the trigger; append to actions list country_action = QAction(f'{country_name}', self) country_action.triggered.connect(getattr(self, f'connect_fastest_{country_code}')) connect_country_actions.append(country_action) # Create a scrollable country connection menu connect_country_menu = QMenu("Country...", self) connect_country_menu.setStyleSheet('QMenu { menu-scrollable: 1; }') connect_country_menu.addActions(connect_country_actions) # Generate connection menu connection_menu = QMenu("Other connections...", self) connection_menu.addMenu(connect_country_menu) connection_menu.addAction(connect_fastest_sc_action) connection_menu.addAction(connect_fastest_p2p_action) connection_menu.addAction(connect_fastest_tor_action) connection_menu.addAction(connect_random_action) # Draw menu tray_menu = QMenu() tray_menu.addAction(connect_fastest_action) tray_menu.addAction(reconnect_action) tray_menu.addMenu(connection_menu) tray_menu.addAction(disconnect_action) tray_menu.addAction(status_action) tray_menu.addSeparator() tray_menu.addAction(self.show_notifications_action) tray_menu.addAction(show_protonvpn_applet_version_action) tray_menu.addAction(show_protonvpn_version_action) tray_menu.addAction(quit_action) self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() # Polling thread self.start_polling()
def test_notification(): Notify.init("Test") notification = Notify.Notification.new(summary="foo", body="Cool") notification.show() notification.close()
# Accept and parse notify arguments parser = argparse.ArgumentParser() parser.add_argument('--notify', action='store', \ choices=['GNOME'], \ help='Select notify mode') parser.add_argument("-i", help="Define IP-address of machine ", type=str) try: command_line = parser.parse_args() except: sys.exit(2) if command_line.notify == 'GNOME': from gi.repository import Notify Notify.init("Gnome") incommingCommandSecond = "" incommingCommandFirst = "" host = '192.168.1.2' port = 2081 statusMessageType = { '0x4': "Filter, ?", '0x5': "Filter, OK to start", '0x6': "Filter, OK to start", '0x7': "Beans, OK to start", '0xb': "Grinding", '0x20': "Filter, No carafe", '0x22': "Beans, No carafe", '0x23': "Beans, Not enough water",
def main(): """ given an optional parameter of a valid mailto url, open an appropriate gmail web page """ global config args = parse_args() header = textwrap.dedent("""\ # GNOME Gmail Configuration # # suppress_preferred # If True ('1', 'yes'...) don't ask if GNOME Gmail should be made # the default mail program. # suppress_account_selection # If True ('1', 'yes'...) don't ask account to use, if you have # only one. # new_browser # If True ('1', 'yes'...) forcedly open Gmail in a new browser # window. # last_email # The email account used for the last run. It is used to populate # the account selection dialog. This is updated automatically. # # use_browser # What browser to use. If unspecified, uses system default browser. # Examples: firefox | google-chrome # # browser_options # Replace the command line arguments used to call the browser. Note # that these options are not portable acrosss browsers. '%%s' is # replaced with the url. Default options are: # Chrome - "--app=%%s" # Mozilla - "-new-window %%s" # ... # """) config = GgConfig( fpath="~/.config/gnome-gmail/gnome-gmail.conf", section='gnome-gmail', initvals={ 'suppress_preferred': '0', 'suppress_account_selection': '0', 'new_browser': '1', 'last_email': '', 'use_browser': '', 'browser_options': '', }, header=header, ) # anyone know how to do this right? glade_suffix = "share/gnome-gmail/gnomegmail.glade" glade_file = os.path.join('/usr', glade_suffix) for gpath in [os.path.join(x, glade_suffix) for x in ['/usr/local']]: if os.path.isfile(gpath): glade_file = gpath if not is_default_mailer() \ and not config.get_bool('suppress_preferred'): do_preferred(glade_file, config) # quiet mode, to set preferred app in postinstall if args.quiet: sys.exit(0) Notify.init("GNOME Gmail") from_address = None message = None if args.rfc822: message = open(args.rfc822, 'r').read() from_address = fromFromMessage(message) else: last_from = config.get_str('last_email') from_address = getGoogleFromAddress(last_from, config, glade_file) if from_address: config.set_str('last_email', from_address) try: gm_url = GMailURL(args.mailto, from_address, message) gmailurl = gm_url.gmail_url(args.send) except GGError as gerr: notice = Notify.Notification.new("GNOME GMail", gerr.value, "dialog-information") notice.show() time.sleep(5) else: if not args.send: new_browser = config.get_bool('new_browser') browser().open(gmailurl, new_browser, True)
count = markup_cnt.format(count) lc = len(count) if lc > mlc: mlc = lc from_ = markup_from.format(from_) subj_ = markup_subj.format(subj_) tags = markup_tags.format(tags) tab.append((count, from_, subj_, tags, lc, lf, ls)) if len(tab) == 0 and threads_total == 0: sys.exit(0) # Format a table txt = [] for c, f, s, t, lc, lf, ls in tab: c += " " * (mlc-lc) f += " " * (mlf-lf) s += " " * (mls-ls) line = "{0} {1} {2} {3}".format(c, f, s, t) txt.append(line) txt = '<span font_desc="DejaVu Sans Mono 7.5">' + "\n".join(txt) + '</span>' # Display a notification Notify.init("notmuch notify") summary = "{0} threads, including {1} unread threads ({2} messages)".format(threads_total, threads_unread, msgs) n = Notify.Notification.new(summary, txt, "/usr/share/emacs/site-lisp/notmuch-logo.png") n.set_timeout(10000) n.set_category("email.arrived") n.show()
for Line in myDatei: Line = Line.rstrip() #Line = Line.decode('utf8') myList.append(Line) myDatei.close() return (myList) def writeFile(path, myList): #self.filename myDatei = open(path, "w") #Liste aus Datei erstelle myDatei.writelines(myList) myDatei.close() status = readFile(os.path.join(path, 'status.txt')) if status[0] == "on": writeFile(os.path.join(path, 'status.txt'), ["off"]) Notify.init("Rotation-ON") RotationOFF = Notify.Notification.new("Rotation", "Screenrotation is now turned OFF", "dialog-information") RotationOFF.show() if status[0] == "off": writeFile(os.path.join(path, 'status.txt'), ["on"]) Notify.init("Rotation-OFF") RotationON = Notify.Notification.new("Rotation", "Screenrotation is now turned ON", "dialog-information") RotationON.show()
def do_startup(self): Gtk.Application.do_startup(self) Notify.init(_("Music")) self.build_app_menu()