def notify(): icon_path = "/home/dushyant/Desktop/Github/Weather-Notifier/weathernotifier/Weather-icon.png" place = get_location() resp = get_weather(place) print resp result = '' result += "Place : " + str(resp[0]["Place"]) result += "\nStatus : " + str(resp[6]) result += "\nCurrent Temperature (Celcius) : " + str(resp[1]["temp"]) result += "\nMax Temperature (Celcius) : " + str(resp[1]["temp_max"]) result += "\nMin Temperature (Celcius) : " + str(resp[1]["temp_min"]) result += "\nWind Speed (m/s) : " + str(resp[2]["speed"]) result += "\nHumidity (%) : " + str(resp[3]) result += "\nPressure (hpa) : " + str(resp[4]["press"]) result += "\nCloud Cover (%) : " + str(resp[5]) # print result # Notification Tool notify2.init("Weather Notifier") n = notify2.Notification("Weather Details", icon=icon_path) n.update("Weather Details", result) n.show()
def main(): notify2.init('git-watcher') n = notify2.Notification("Git watcher started", os.getcwd(), "notification-message-im") n.show() while True: run_check() time.sleep(600)
def __init__(self, parent=None): super(ScudCloud, self).__init__(parent) self.setWindowTitle('ScudCloud') notify2.init(self.APP_NAME) self.settings = QSettings(expanduser("~")+"/.scudcloud", QSettings.IniFormat) self.identifier = self.settings.value("Domain") if Unity is not None: self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop") else: self.launcher = DummyLauncher(self) self.leftPane = LeftPane(self) self.cookiesjar = PersistentCookieJar(self) webView = Wrapper(self) webView.page().networkAccessManager().setCookieJar(self.cookiesjar) self.stackedWidget = QtGui.QStackedWidget() self.stackedWidget.addWidget(webView) centralWidget = QtGui.QWidget(self) layout = QtGui.QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(self.leftPane) layout.addWidget(self.stackedWidget) centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) self.addMenu() self.tray = Systray(self) self.systray() self.installEventFilter(self) self.zoom() if self.identifier is None: webView.load(QtCore.QUrl(self.SIGNIN_URL)) else: webView.load(QtCore.QUrl(self.domain())) webView.show()
def view_notify(data): """ Notify for Informer service. """ n = notify2.Notification("Incoming call", data) n.set_hint("x", 200) n.set_hint("y", 400) notify2.init("informer") n.show()
def main(): notify2.init ('kremote') signal.signal(signal.SIGINT,terminate) parser = argparse.ArgumentParser(description='kremote daemon.') parser.add_argument('-D','--daemon', dest='cmdline', required=True, help='Command line to start the remote daemon') parser.add_argument('-v','--version', action='version', version='kremote daemon 1') args = parser.parse_args() print args.cmdline fd = launch_daemon(args.cmdline.split(' ')) shift = False while True: buf = read(fd,1) if len(buf)==0: break if buf == 's': shift = not shift print '->', buf action(buf, shift) notify('Device listener failure',1) exit(2)
def process(self, message: Message): """Displays desktop notification about specified message. :param message: E-Mail message object. """ print(" - {}: {}.process()".format(self.name, self.__class__.__name__)) notify2.init("Sendmail") title = self.title_template.format( subject=message.get("Subject"), from_email=message.get("From"), appname="Sendmail", name=self.name ) text = self.text_template.format( subject=message.get("Subject"), from_email=message.get("From"), text=message.as_string(), appname="Sendmail", name=self.name ) n = notify2.Notification(title, text, self.icon_name ) n.show()
def display_song(self): """Display the song data using notify-send.""" if self.get_data("status") == "playing": # Create our temporary file if it doesn't exist yet. open("/tmp/cmus_desktop_last_track", "a").write("4") # Check to see when we got our last track from cmus. last_notice = open("/tmp/cmus_desktop_last_track", "r").read() # Write time stamp for current track from cmus. last_notice_time = str(time.time()) open("/tmp/cmus_desktop_last_track", "w").write(last_notice_time) # Calculate seconds between track changes. track_change_duration = round(time.time() - float(last_notice)) # Display current track notification only if 5 seconds have # elapsed since last track was chosen. if track_change_duration > 5: # Execute notify2 to create the notification notify2.init("cmus-display") text_body = self.format_notification_body() # Check if we have a notify_body to avoid # putting a "by" at the end if text_body: notification = notify2.Notification( "Cmustify - current song", text_body, "") notification.set_urgency(notify2.URGENCY_LOW) notification.show() return True else: return False
def display(title, msg): logging.debug("NOTIFY DISPLAY") if sys.platform == "linux": import notify2 import dbus if not notify2.is_initted(): logging.debug("Initialising notify2") notify2.init("cutecoin") n = notify2.Notification(title, msg) # fixme: https://bugs.python.org/issue11587 # # Not working... Empty icon at the moment. # icon = QPixmap(":/icons/cutecoin_logo/").toImage() # if icon.isNull(): # logging.debug("Error converting logo") # else: # icon.convertToFormat(QImage.Format_ARGB32) # icon_bytes = icon.bits().asstring(icon.byteCount()) # icon_struct = ( # icon.width(), # icon.height(), # icon.bytesPerLine(), # icon.hasAlphaChannel(), # 32, # 4, # dbus.ByteArray(icon_bytes) # ) # n.set_hint('icon_data', icon_struct) # n.set_timeout(5000) n.show() else: _Toast(title, msg)
def __init__(self, appname, icon, urgency=None, timeout=None): self._appname = appname self._icon = icon self._urgency = urgency if urgency else notify2.URGENCY_NORMAL self._timeout = timeout if timeout else 1000 notify2.init(self._appname) self._nobj = notify2.Notification(appname, icon=ICON)
def display_notification(title, message): notify2.init("Init") notice = notify2.Notification(title, message) notice.show() sleep(4) notice.close() return
def daemon(args=None, daemon=None): """ Execute udiskie as a daemon. """ import gobject import udiskie.automount import udiskie.mount import udiskie.prompt parser = mount_program_options() parser.add_option('-s', '--suppress', action='store_true', dest='suppress_notify', default=False, help='suppress popup notifications') parser.add_option('-t', '--tray', action='store_true', dest='tray', default=False, help='show tray icon') options, posargs = parser.parse_args(args) logging.basicConfig(level=options.log_level, format='%(message)s') mainloop = gobject.MainLoop() # connect udisks if daemon is None: daemon = udisks_service(options.udisks_version).Daemon() # create a mounter prompt = udiskie.prompt.password(options.password_prompt) filter = load_filter(options.filters) mounter = udiskie.mount.Mounter(filter=filter, prompt=prompt, udisks=daemon) # notifications (optional): if not options.suppress_notify: import udiskie.notify try: import notify2 as notify_service except ImportError: import pynotify as notify_service notify_service.init('udiskie.mount') notify = udiskie.notify.Notify(notify_service) daemon.connect(notify) # tray icon (optional): if options.tray: import udiskie.tray create_menu = partial(udiskie.tray.create_menu, udisks=daemon, mounter=mounter, actions={'quit': mainloop.quit}) statusicon = udiskie.tray.create_statusicon() connection = udiskie.tray.connect_statusicon(statusicon, create_menu) # automounter automount = udiskie.automount.AutoMounter(mounter) daemon.connect(automount) mounter.mount_all() try: return mainloop.run() except KeyboardInterrupt: return 0
def show(content): try: import notify2 notify2.init('Slx7hS3ns3on') notify = notify2.Notification('Slx7hS3ns3on', content, "dialog-information") notify.show() except: print("**** Requires notify. sudo pip install notify2.")
def __init__(self, appName, timeout, guiApp): super(MessengerLinux, self).__init__(timeout) notify2.init(appName, guiApp.eventLoop) self.notification = None if guiApp.iconPath: self.icon = guiApp.getNotificationIcon()
def initialize(self, context): if sys.platform != 'linux2': raise ResultProcessorError('Notifications are only supported in linux') if not notify2: raise ResultProcessorError('notify2 not installed. Please install the notify2 package') notify2.init("Workload Automation")
def notify(summary, message): if not notify2_available: return try: notify2.init('commit-gate-cli') notify2.Notification(summary, message, os.path.join(os.path.dirname(__file__), 'jenkins.png')).show() except BaseException as e: print "Could not display notification %s" % e.message
def notify(self): ''' Displays a notification via libnotify ''' import notify2 notify2.init (self.title) noti = notify2.Notification (self.title, self.message, "dialog-information") noti.show ()
def stretch(): notify2.init('Stretch') n = notify2.Notification('Get Up !', 'Time to stretch a bit ') n.show() subprocess.call(['espeak', '-g', '5', 'Get Up. Time to Stretch' ]) time.sleep(600) n = notify2.Notification('Enough Rest', 'Get back to work ') n.show(); subprocess.call(['espeak', '-g', '5', 'Get back to work' ])
def send_notify(title, message, speed=300, min_delay=10): notify2.init("yatr") notification = notify2.Notification(title, message) notification.show() time.sleep(max( len(title.split() + message.split()) * 60 / speed, min_delay )) notification.close()
def display_notification(msg_id, msg_from, msg_body): notify2.init("ZipWhip") m = zw_lib.message(msg_id, msg_body, msg_from, msg_from, "qt") n = notify2.Notification("New Text from: %s" % msg_from, msg_body, "notification-message-im" # Icon name) ) #n.add_action("mark_read", "Mark As Read", m.mark_read) n.add_action("reply", "Reply", passs) n.show()
def show_notify(notify_content=""): try: notify2.init('Tickeys') title = 'Tickeys' icon_file_path = os.getcwd() + '/tickeys.png' notify = notify2.Notification(title, notify_content, icon_file_path) notify.show() except Exception, e: logger.exception(e) logger.error("show notify fail")
def __init__(self, username_channel_tuple): username = username_channel_tuple[0] channel = username_channel_tuple[1] self.chat = hackchat.HackChat(username, channel) self.users_list = json.loads(self.chat.ws.recv())["nicks"] # Initialize notify2 notify2.init("hackchat")
def maybe_notify(duration, cmd, success): seconds = duration.total_seconds() if seconds < MINIMUM_SECONDS: return finished = ["Failed", "Succeeded"][success] summary = finished + " after " + str(duration) notify2.init("undistract my fish") n = notify2.Notification(summary, cmd, "face-surprise") n.set_hint_int32("transient", 1) n.show()
def __init__(self, parent=None): super(MainApp, self).__init__(parent) # Init notification notify2.init('webcam-manager') # Init tray icon self.tray_icon = QSystemTrayIcon(QIcon.fromTheme('camera-web'), parent) self.initTrayIcon() self.tray_icon.show()
def notify_this(text): try: notify2.init("grenier") n = notify2.Notification("Grenier", text, "drive-removable-media") n.set_timeout(2000) n.show() except NameError: print(text)
def _pluginRemovePlugin(self,plugin): notify2.init("duck-launcher") n=notify2.Notification("The plugin '{}' is uninstalling".format(plugin), "", "dialog-information") n.show() self.parent.close_it() t = removePlugin(parent=self.parent) t.plugin=plugin t.start()
def send_notification(unread_count): if not int(unread_count): return image = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gmail.jpg') notify2.init(__file__) n = notify2.Notification('Gmail未读邮件', '共{num}封未读'.format(num=unread_count), image ) n.show()
def show_notify(): try: import notify2 notify2.init('Tickeys') title = 'Tickeys' body = '程序“xdotool”尚未安装, 无法隐藏窗口。' iconfile = os.getcwd() + '/tickeys.png' notify = notify2.Notification(title, body, iconfile) notify.show() except Exception: return
def notify(self, data): notify2.init("Pushover-libnotify") title = data['app'] if data['title'] != '': title += ' - '+data['title'] icon = self.geticon(data['icon']) n = notify2.Notification( title, data['message'], icon) n.show()
def pop(title, message): if notifyModule is "pynotify": pynotify.init("Scorer") pynotify.Notification(title, message).show() elif notifyModule is "Notify": Notify.init("Scorer") Notify.Notification.new(title, message).show() else: notify2.init("Scorer") notify2.Notification(title, message).show() return True
def send_notification(title, body): """ This function uses notify2 to send DBUS notifications. Params: title (str) body (str) returns notify2.Notification().show() (boolean) """ notify2.init("Lite Updater") return notify2.Notification(title, body).show()
'''PYTHON 2 Script''' import notify2 import time notify2.init('') def display(): time.sleep(1200) n = notify2.Notification( "Alert", "It has been 20 mins since you last took a break, now look 20ft. away for 20seconds :)", "icon.ico" # Icon name ) n.show() #download any suitable icon of your choice and rename it icon.ico display() if __name__ == '__main__': display()
def __init__(self): self.plugins = [] notify2.init("duck launcher")
def nancy_notify(text): #Desktop Notification notify2.init('Nancy') n = notify2.Notification('Nancy', text, icon=LOGO_PATH) n.show()
for i in scl: data.pop(i) html.append(data) html_ = [] else: print("Connect internet") return html '''Main loop''' while True: html = get_earthquake() if html[0] == "No internet connection": not2.init("Deprem") n = not2.Notification( "Deprem", "Deprem bilgilerini almak için internete bağlanın.") n.show() else: try: if not latest_earthquake == html[0]: not2.init("Deprem") output = html[0][8] + html[0][9] + " bölgesinde " + html[0][ 6] + " şiddetinde deprem." n = not2.Notification("Deprem", output) n.show() except: not2.init("Deprem") output = html[0][8] + html[0][9] + " bölgesinde " + html[0][ 6] + " şiddetinde deprem."
import tensorflow as tf from tensorflow import keras import numpy as np import notify2 notify2.init("Finished?") with open("./NAMES.txt", "r") as i: nameList = i.read().split("\n") ''' Input: First letter Output: Padded name ''' dictionary = {" ": 0} def code(name): return [dictionary[i.lower()] for i in name] def decode(name): reverse = dict((value, key) for (key, value) in dictionary.items()) print(name) return "".join([reverse.get(round(i * 100) / 100, "?") for i in name]) maxlen = len(list(nameList[0])) model = keras.Sequential() for i in range(len(nameList)): nameList[i] = list(nameList[i]) for ii in nameList[i]: if ii.lower() not in dictionary: dictionary[ii.lower()] = len(dictionary.items())
#!/usr/bin/env python3 import time import sys import notify2 from playsound import playsound from beepy import beep notify2.init('foo') print("Start(Y/N):") str = input() mins = 0 if str[0] == 'Y': n = notify2.Notification("Started!") n.show() while mins != 20: time.sleep(60) mins += 1 n = notify2.Notification("Take Break.20 mins up!") n.show() beep(sound=4) sys.exit(0) else: sys.exit(0)
#!/usr/bin/env python3 #coding=utf-8 import time import notify2 notify2.init('python3 notify program') msg = notify2.Notification('text 1', 'text2') msg.set_timeout(3000) msg.show() time.sleep(3) msg.update('title', 'lskadjfiajelkfjsalkdjf ijasdlkfj 中文') msg.show()
def setdarktheme(self): with open('dark.qss', 'r') as theme: self.MainWindow.setStyleSheet(theme.read()) def setlighttheme(self): with open('light.qss', 'r') as theme: self.MainWindow.setStyleSheet(theme.read()) if platform.system == "Linux": import notify2 notify2.init('App Name') def notification(title, text, icon=None): n = notify2.Notification(title, text, icon) if platform.system == "Windows": from win10toast import ToastNotifier toaster = ToastNotifier() def notification(title, text, icon=None): toaster.show_toast(title, text, icon_path=icon, threaded=True) if platform.system() == "Darwin":
def init(options, configuration, plugin): if SUBSCRIBE_NOTIF: notify2.init("lightning-qt") path = os.path.join(plugin.lightning_dir, plugin.rpc_filename) # See above the docstring for rationale plugin.rpc = HackedLightningRpc(path)
from unofficial_graph_api import fetch_json from unofficial_graph_api import basic_functions import random import requests import notify2 import time import sys import os # stores previous timestamp so that new message will not repeat old_timestamp = 0 # initialise the d-bus connection notify2.init("Facebook Desktop Notifier") # uid = 0 online = True # notify2 uses caching images with same name, # so to change the image name everytime to not repeat same # thumbnail in every notifications image_path = 'tmp' + str(random.randint(9939, 9199182)) + '.png' url = 'https://www.facebook.com/messages/' cookies = { 'xs': 'YOUR_ACCESS_TOKEN_HERE', # REPLACE IT WITH YOUR ACCESS TOKEN 'c_user': '******' # REPLACE IT WITH YOUR USER ID }
import power import time import notify2 from notify2 import Notification notify2.init("Charger Warning") n = Notification("WARNING", "Laptop running on battery. Plug in charger!") n.set_urgency(notify2.URGENCY_CRITICAL) while (True): source = power.PowerManagement().get_providing_power_source_type() if source == power.POWER_TYPE_BATTERY: n.show() print('NOT CHARGING!') else: print('CHARGING') time.sleep(300)
def main(): """The main function.""" # Get runtime arguments cli_args = parse_runtime_args() # Set up logger logging.basicConfig(format="%(levelname)s: %(message)s", level=cli_args.loglevel) # Make sure process kills and poweroffs cause atexit registers to # trigger signal.signal(signal.SIGTERM, graceful_exit) signal.signal(signal.SIGINT, graceful_exit) # Read config file try: config_dict = parse_config_file() except ConfigFileNotFound: logging.error("Config file not found. Aborting.") sys.exit(1) except ConfigFileInvalid: logging.error("Config file invalid. Aborting.") sys.exit(1) # Set up the notifier if not cli_args.print_to_terminal: notify2.init(NAME) # Set up app indicator and run it in a separate thread if (not cli_args.one_shot or not cli_args.print_to_terminal or cli_args.no_app_indicator): # Import this here so GTK-incompatible machines are still # supported # fmt: off from twitchgamenotify.app_indicator import AppIndicator # pylint: disable=import-outside-toplevel # fmt: on indicator = AppIndicator() # Kill the indicator when we quit atexit.register(indicator.stop) # Start the indicator in its own thread threading.Thread(target=indicator.start, daemon=True).start() # Connect to the API - keep retrying and be loud if there's a # connection error retry_attempt = 0 while True: try: twitch_api = TwitchApi( client_id=config_dict["twitch-api-client-id"], client_secret=config_dict["twitch-api-client-secret"], ) # Successful connection; reset retry attempts if retry_attempt: retry_attempt = 0 break except AuthenticationFailed: # The auth credentials provided are no good send_authentication_error_notification( send_dbus_notification=not cli_args.print_to_terminal, ) sys.exit(1) except requests.exceptions.ConnectionError: # Internet is probably down. Log an error and notify if we're # notifying retry_attempt += 1 sleep_delta = min(2**retry_attempt, 20) send_connection_error_notification( send_dbus_notification=not cli_args.print_to_terminal, retry_seconds=sleep_delta, ) # Wait a bit before retrying time.sleep(sleep_delta) # Set up arguments to give process_notifications kwargs = dict( print_to_terminal=cli_args.print_to_terminal, streamers=config_dict["streamers"], twitch_api=twitch_api, ) if cli_args.one_shot: kwargs["ignore_502s"] = config_dict["ignore-502-errors-one-shot"] else: kwargs["ignore_502s"] = config_dict["ignore-502-errors-persistant"] if not cli_args.one_shot: # Remember what game a streamer was playing last so we don't # re-notify streamers_last_seen_playing_dict = { streamer: "" for streamer in config_dict["streamers"].keys() } kwargs["streamers_previous_game"] = streamers_last_seen_playing_dict # Query (and possibly notify) only once or periodically if cli_args.one_shot: process_notifications_wrapper(**kwargs) else: # Loop until we get interrupted while True: # Process any notifications threading.Thread( target=process_notifications_wrapper, kwargs=kwargs, daemon=True, ).start() # Wait before querying again time.sleep(config_dict["query-period"])
# Author: Oleg Panasevych <*****@*****.**>, Vladimir Avdeev <*****@*****.**> import gtk import tray_common try: import notify2 as libnotify except ImportError: try: import pynotify as libnotify except: libnotify = None if libnotify: libnotify.init(tray_common.APP_NAME) def show_libnotify_notification(title, body): try: libnotify.Notification(title, body, tray_common.ICON_PATH).show() except: def show_libnotify_notification(title, body): pass else: def show_libnotify_notification(title, body): pass def show_message(data=None): msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, data) msg.run() msg.destroy()
#!/usr/bin/env python import sqlite3 import notify2 from parseBid import parseBid DB_PATH = '/home/feanor/Development/Cosplay_RD/warcraft' tableList = [] display = [] notify2.init("BidMonitor") conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute('select TableName from Main') for tableName in c: tableList.append(tableName[0]) #print(tableList) #Update prices in each subtables for tableName in tableList: c.execute('select ID,URL,Name,Cost from "{}"'.format(tableName)) URLlist = c.fetchall() for tup in URLlist: #print(tup[1]) n = parseBid(tup[1]) if n[1] != tup[3]: app = (tup[2], tup[0], tup[3], n[1]) display.append(app) param = (n[0], n[1], tup[0]) c.execute('update "{}" set Name=?,Cost=? where ID=?'.format(tableName),
import logging import os from watchdog.observers import Observer from watchdog.events import LoggingEventHandler from watchdog.events import FileSystemEventHandler import notify2 import subprocess as sub from datetime import datetime FolderNameToWatchForFileChanges = "/var/www/html/foldername/" dir_path = os.path.dirname(os.path.realpath(__file__)) import random GLOBAL_NOTIFICATION_INSTANCE = notify2.init('foo') n = notify2.Notification("", "", "") def notifiyUser(title, description, IsPassed): if IsPassed: n.update(title, description, os.path.join(dir_path, "success.png")) else: n.update(title, description, os.path.join(dir_path, "failure.png")) n.set_timeout(300) n.set_urgency(2) n.show() def subprocess_cmd(command):
def __init__(self): if NOTIFY2_AVAIL: notify2.init("clipboard") self.timeout = 5000 self.prefer_notify_send = False
def sendNotif(title, message): notify2.init('Test') notice = notify2.Notification(title, message) notice.show() return
import time import notify2 from desktop_news import masaustu_haber_fonksiyonu #Haberin başında gözükmesini stediğimiz icon'un tam adresini atadık. ICON_PATH = ("jamaican-jerk-chicken.svg") #Önceki fonksiyonumuzda return ettiğimiz haberleri değişkene atıyoruz. haber_ogeleri = masaustu_haber_fonksiyonu() #Masaüstü bus'ına bağlandık. notify2.init("Haber Bildirimi") #yeni nesne oluşturduk ve iconu atadık. n = notify2.Notification(None, icon=ICON_PATH) #Aciliyet seviyesi ayarlama yaptık. n.set_urgency(notify2.URGENCY_NORMAL) #Bildirim için zaman aşımını ayarladık. n.set_timeout(10000) #Aldığımız haberlerin içinde gezerek, haberleri düzenliyoruz. for i in range(len(haber_ogeleri)): j = haber_ogeleri[i].text j = j.replace("\n", "") n.update(j.strip()) #Burada ise haberi ekranda gösteriyoruz. n.show()
import json import time import requests import notify2 notify2.init('Scores') base_url = 'http://cricapi.com/api/' def read_api_key(): f = open('apikey', 'r') return f.readline().strip() def get_matches(): api_url = base_url + 'matches/' request_header = {"apikey": api_key} response = requests.get(api_url, headers=request_header) if response.status_code == 200: return json.loads(response.content.decode('utf-8')) def started_matches(data): matches = [] for i in data['matches']: if i['matchStarted']: matches.append(i) return matches def get_score(match_id):
items = file1.readlines() return items def check_for_discount(): items = get_items() for item in items: item = item.strip("\n") #remove newline character from the url doc = session.get(item).text #get html document html = soup(doc, "html.parser") special_price = html.findAll("div", {"class": "e-product-price__special"}) if special_price != []: print("product has discount") n.update("discount!", item) n.show() else: print("no discount") interval = 120 #minutes, change value for shorter time between notifications session = HTMLSession() notify2.init("discount notifier") n = notify2.Notification("", "") check_for_discount() schedule.every(interval).minutes.do(check_for_discount) while True: schedule.run_pending() time.sleep(1)
# Important import import os import sys from GoogleNews import GoogleNews import time import pandas as pd import argparse import notify2 import pylog import pkg_resources logs = pylog.adv_color_log('Googlenews-bot') notify2.init('Googlenews-bot') n = notify2.Notification("Googlenews-bot", "News has been added", "info" # Icon name ) no_data = notify2.Notification("Googlenews-bot", "No news data added", "info" # Icon name ) no_internet_connected = notify2.Notification("Googlenews-bot", "Unable to retrieve data from news.google.com", "error" # Icon name ) installed_pkg = {pkg.key for pkg in pkg_resources.working_set} if 'ipdb' in installed_pkg: import ipdb # noqa: F401 def arg_parser_arguments():
def notify2_init(): notify2.notifications_registry = TimeoutDict(args.action_timeout) notify2.init(args.appname, 'glib')
import time import notify2 from topnews import topStories # path to notification window icon ICON_PATH = "/home/piyush/Downloads/news_icon.png" # fetch news items newsitems = topStories() # initialise the d-bus connection notify2.init("News Notifier") # create Notification object n = notify2.Notification(None, icon = ICON_PATH) # set urgency level n.set_urgency(notify2.URGENCY_NORMAL) # set timeout for a notification n.set_timeout(10000) for newsitem in newsitems: # update notification data for Notification object n.update(newsitem['title'], newsitem['description']) # show notification on screen n.show() # short delay between notifications
def notifierActivated(self, s): m = '' while True: try: r, w, e = select.select([self.read_pipe], [], [self.read_pipe], 1.0) except select.error: log.debug("Error in select()") break if e: log.error("Pipe error: %s" % e) break if r: #m = ''.join([m, os.read(self.read_pipe, self.fmt_size)]) m = os.read(self.read_pipe, self.fmt_size) while len(m) >= self.fmt_size: event = device.Event(*[x.rstrip(b'\x00').decode('utf-8') if isinstance(x, bytes) else x for x in struct.unpack(self.fmt, m[:self.fmt_size])]) m = m[self.fmt_size:] if event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED: self.resetDevice() for d in device.getSupportedCUPSDevices(back_end_filter=['hp', 'hpfax']): self.addDevice(d) self.setMenu() if event.event_code == EVENT_USER_CONFIGURATION_CHANGED: log.debug("Re-reading configuration (EVENT_USER_CONFIGURATION_CHANGED)") self.user_settings.load() self.user_settings.debug() elif event.event_code == EVENT_SYSTEMTRAY_EXIT: self.quit() return if self.user_settings.systray_visible in \ (SYSTRAY_VISIBLE_SHOW_ALWAYS, SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE): log.debug("Showing...") self.tray_icon.setVisible(True) if event.event_code == EVENT_DEVICE_UPDATE_ACTIVE: if not self.active_icon: self.tray_icon.setIcon(self.prop_active_icon) self.active_icon = True continue elif event.event_code == EVENT_DEVICE_UPDATE_INACTIVE: if self.active_icon: self.tray_icon.setIcon(self.prop_icon) self.active_icon = False continue elif event.event_code == EVENT_DEVICE_UPDATE_BLIP: if not self.active_icon: self.tray_icon.setIcon(self.prop_active_icon) self.active_icon = True QTimer.singleShot(BLIP_DELAY, self.blipTimeout) continue if self.user_settings.systray_visible in (SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE, SYSTRAY_VISIBLE_HIDE_ALWAYS): log.debug("Waiting to hide...") QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive) if event.event_code <= EVENT_MAX_USER_EVENT or \ event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED: if event.event_code != EVENT_CUPS_QUEUES_REMOVED: self.addDevice(event.device_uri) self.setMenu() if self.tray_icon.supportsMessages(): log.debug("Tray icon message:") event.debug() error_state = STATUS_TO_ERROR_STATE_MAP.get(event.event_code, ERROR_STATE_CLEAR) desc = device.queryString(event.event_code) show_message = False if self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ALL: # OK, Busy show_message = True elif self.user_settings.systray_messages in (SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS, SYSTRAY_MESSAGES_SHOW_ERRORS_ONLY): if error_state == ERROR_STATE_ERROR: show_message = True elif self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS and \ error_state in (ERROR_STATE_WARNING, ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER): show_message = True if event.printer_name: d = event.printer_name else: back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \ device.parseDeviceURI(event.device_uri) if bus == 'usb': idd = serial elif bus == 'net': idd = host elif bus == 'par': idd = dev_file else: idd = 'unknown' self.model = models.normalizeModelUIName(model) if back_end == 'hp': d = self.__tr("%s Printer (%s)"%(model,idd)) elif back_end == 'hpaio': d = self.__tr("%s Scanner (%s)"%(model,idd)) elif back_end == 'hpfax': d = self.__tr("%s Fax (%s)"%(model,idd)) else: d = self.__tr("%s (%s)"%(model,idd)) if show_message: if have_pynotify and pynotify.init("hplip"): # Use libnotify/pynotify icon, urgency = ERROR_STATE_TO_ICON_AND_URGENCY_PYNOTIFY.get(error_state, (getPynotifyIcon('info'), pynotify.URGENCY_NORMAL)) if event.job_id and event.title: msg = "%s\n%s: %s\n(%s/%s)" % (to_unicode(d), desc, event.title, event.username, event.job_id) log.debug("Notify: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" % (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code)) else: msg = "%s\n%s (%s)" % (to_unicode(d), desc, event.event_code) log.debug("Notify: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code)) n = pynotify.Notification("HPLIP Device Status", msg, icon) # CRID: 11833 Debian Traceback error notification exceeded n.set_hint('transient', True) n.set_urgency(urgency) if error_state == ERROR_STATE_ERROR: n.set_timeout(pynotify.EXPIRES_NEVER) else: n.set_timeout(TRAY_MESSAGE_DELAY) n.show() else: # Use "standard" message bubbles icon = ERROR_STATE_TO_ICON.get(error_state, QSystemTrayIcon.Information) if event.job_id and event.title: log.debug("Bubble: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" % (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code)) self.tray_icon.showMessage(self.__tr("HPLIP Device Status"), "%s\n%s: %s\n(%s/%s)"%(d,desc, event.title,event.username,event.job_id), icon, TRAY_MESSAGE_DELAY) else: log.debug("Bubble: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code)) self.tray_icon.showMessage(self.__tr("HPLIP Device Status"), "%s\n%s (%s)"%(d,desc,event.event_code), icon, TRAY_MESSAGE_DELAY) else: break
time.sleep(5) # Give it time to actually load html_source = driver.page_source # Extract source code # Make it slightly more readable html_text = BeautifulSoup(html_source, "html.parser").text # Store a log for debugging the website content with open(filepaths["website"], "w") as text_file: text_file.write(html_text) match = re.search(r"(\d+)\svon\s\d+\sStellenangebote", html_text) if match: number_of_jobs = int(match.group(1)) base_message = "Found " + str(number_of_jobs) + " jobs for: " + url notify2.init("Job Search Script") notification = notify2.Notification( "Job Search", base_message, # Displayed icon # https://specifications.freedesktop.org/icon-naming-spec/latest/ar01s04.html "applications-science") # The purpose of this try/except block is to see whether a log file exists from previous runs. # If so, get its last line and extract the number of jobs hit we got there. # The end goal is to increase the notification's urgency to CRITICAL if the number increased, aka a new job was listed. if os.path.isfile(filepaths["searches"]): with open(filepaths["searches"], "r") as logfile: current_line = 0 for line in logfile: if line.strip(): # Ignore whitespace/empty lines
import notify2 notify2.init('app name') # n = notify2.Notification('title', 'message') n = notify2.Notification("Icon Test", "Testing stock icon", icon="/static/images/Sad.png") n.show()
import os import pathlib from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename import notify2 import dbus from config import get_config notify2.init("Drop", mainloop='glib') app = Flask(__name__) app.secret_key = "such secret, very wow!" n = None def handle_notifictaion_click(notification, key, user_data=None): os.system('xdg-open ' + get_config().UPLOAD_FOLDER) def allowed_file(filename): return True #return '.' in filename and \ # filename.rsplit('.', 1)[1].lower() in get_config().ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file(): global n if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) files = request.files.getlist('file')
import notify2 as pynotify f = open("xxx", "r") cont = f.read() soup = BeautifulSoup(cont, 'html.parser') save = "" i = 0 for link in soup.find_all('a'): link = str(link.get("href")) if link.startswith("/en/wgzimmer/search/mate/ch/zurich-stad"): save = "\n".join([save, link]) if i > 15: break f2 = open("savedLinks", "r") cont2 = f2.read() pynotify.init("Test") notice = pynotify.Notification("testtt", "Nothing NEW") if cont2 != save: f2.close() f2 = open("savedLinks", "w+") f2.write(save) print("NOT SAME!") notice = pynotify.Notification("testtt", "The WGZIMMER is updated.") notice.set_timeout(pynotify.EXPIRES_NEVER) notice.show()
#!/usr/bin/python import sys import notify2 from pathlib import Path def safe_index(container, element): return container.index(element) if element in container else None notif_id_file = Path("/tmp/notif_id") notif_id = 0 if notif_id_file.exists(): with open(notif_id_file, "r") as f: notif_id = int(f.read()) notify2.init("test") notif = notify2.Notification("") notif.id = notif_id if "-s" in sys.argv: notif.summary = " ".join(sys.argv[sys.argv.index("-s") + 1:safe_index(sys.argv, "-m")]) if "-m" in sys.argv: notif.message = " ".join(sys.argv[sys.argv.index("-m") + 1:safe_index(sys.argv, "-t")]) if "-t" in sys.argv: notif.timeout = int(sys.argv[sys.argv.index("-t") + 1]) notif.show() with open(notif_id_file, "w") as f: f.write(str(notif.id))
import sys import notify2 from notify2 import Notification notify2.init(sys.argv[0]) def send(process=None, subject_format='{executable} process {pid} ended', timeout=notify2.EXPIRES_NEVER): """Display a Desktop Notification via DBUS (notify2) :param process: information about process. (.info() inserted into body) :param subject_format: subject format string. (uses process.__dict__) :param timeout: how long to display notification (milliseconds) default 0 (never expires) """ notif = Notification(subject_format.format(**process.__dict__), process.info()) notif.timeout = timeout notif.show()