Exemplo n.º 1
0
 def _show_popup(self):
     notify2.init("Ymael")
     notifier = notify2.Notification(
         "{} nouveau(x) post(s) ! {}".format(self._total, self._smiley),
         self._message, self._icon)
     notifier.show()
     return
Exemplo n.º 2
0
def bildirim():
    if platform.machine() == "aarch64":
        return
    elif kullanici_adi == "gitpod":
        return
    elif bellenim_surumu.split('-')[-1] == 'aws':
        return
    elif isletim_sistemi == "Windows" and bellenim_surumu >= "10":
        try:
            from win10toast import ToastNotifier
        except ModuleNotFoundError:
            os.system('pip install win10toast')
            from win10toast import ToastNotifier

        win_baslik()
        bildirim = ToastNotifier()
        bildirim.show_toast(f"{pencere_basligi}",
                            f"{bildirim_metni}",
                            icon_path=None,
                            duration=10,
                            threaded=True)
    elif isletim_sistemi == "Linux":
        try:
            import notify2
        except ModuleNotFoundError:
            os.system('pip install notify2')
            import notify2

        notify2.init(pencere_basligi)
        bildirim = notify2.Notification(f"{pencere_basligi}",
                                        f"{bildirim_metni}",
                                        "notification-message-im")
        bildirim.show()
Exemplo n.º 3
0
    def save(self, widget):
        name = self.nameField.get_text()
        path = self.pathField.get_text()
        print('hey')
        if (name == "" or path == ""):
            self.errorMsg('Error', 'Please fill in all the fields to proceed.')
        elif not (os.path.isdir(path)):
            self.errorMsg('Error', '"' + path + '" is not a directory.')
        elif self.vhostsModel.exists(name):
            self.errorMsg('Error',
                          '"' + name + '" is already an existing virtualHost.')
        else:
            self.name = name
            self.path = path

            cmd = "pkexec " + str(_root) + "/bin/addvhost {} {}".format(
                name, path)
            res = subprocess.call([cmd], shell=True)
            if int(res) == 0:
                self.vhostsModel.add(self.name, self.path)
                n = notify2.Notification(
                    "Successfully created Virtual Host",
                    "You can now access to http://" + name + "/.",
                    os.path.join(_dir_path, 'img', 'logo.png'))
                n.add_action("open", "Open in browser", self.actions)
                n.show()
                self.destroy()
            else:
                self.errorMsg('Error',
                              "An error occured during virtualhost creation")
Exemplo n.º 4
0
 def emit(self, record):
     """
     Send a notification.
     :param record: the LogRecord object
     """
     notification = notify2.Notification(record.getMessage())
     notification.show()
Exemplo n.º 5
0
def notify(title, text):
    notify2.init(APP_NAME)
    notification = notify2.Notification(APP_NAME, None, APP_NAME)
    notification.set_urgency(notify2.URGENCY_NORMAL)
    notification.set_timeout(5000)
    notification.update(title, text)
    notification.show()
Exemplo n.º 6
0
 def channel_opened(plugin, channel_opened):
     n = notify2.Notification(
         "C-lightning", "A channel was opened to you by {}, with an amount"
         " of {} and the following funding transaction id:"
         " {}.".format(channel_opened["id"], channel_opened["amount"],
                       channel_opened["funding_txid"]))
     n.show()
Exemplo n.º 7
0
        def sas_show_notification(self, message):
            emojis = [x[0] for x in message.emoji]

            emoji_str = "   ".join(emojis)

            notificaton = notify2.Notification(
                "Short authentication string",
                message=(
                    f"Short authentication string for the key verification of"
                    f" {message.user_id} via {message.device_id}:\n"
                    f"{emoji_str}"),
            )
            notificaton.set_category("im")

            def confirm_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.ConfirmKeyVerification(message.pan_user,
                                                      message.user_id,
                                                      message.device_id)

            def cancel_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.CancelKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            if "actions" in notify2.get_server_caps():
                notificaton.add_action("confirm", "Confirm", confirm_cb,
                                       message)
                notificaton.add_action("cancel", "Cancel", cancel_cb, message)

            notificaton.show()
def get_topStories():
    # path to notification window icon 
    ICON_PATH = os.getcwd() + "/icon.ico"

    # fetch news items 
    newsitems = topStories() 

    # initialise the d-bus connection 
    notify2.init("News Notifier") 

    # create Notification object 
    n = notify2.Notification(newsitems, 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 
        time.sleep(15) 
Exemplo n.º 9
0
def display(title, msg):
    logging.debug("NOTIFY DISPLAY")
    if sys.platform == "linux":
        try:
            import notify2
            if not notify2.is_initted():
                logging.debug("Initialising notify2")
                notify2.init("sakia")
            n = notify2.Notification(title, msg)
            n.show()
        except ImportError:
            _Toast(title, msg)


# fixme: https://bugs.python.org/issue11587
# # Not working... Empty icon at the moment.
# icon = QPixmap(":/icons/sakia_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)
    else:
        _Toast(title, msg)
Exemplo n.º 10
0
def viewTranslate():
    global pre_word

    result = get_translate_words(pre_word)
    notify2.init("AutoTranslate")
    bubble = notify2.Notification('谷歌翻译', result)
    bubble.show()
Exemplo n.º 11
0
def notify(data):
    """ Method to notify the user through dbus """
    if data['prefix'] != '--':
        try:
            msg = "{} | {}: {}".format(data['buffer'], data['prefix'],
                                       data['message'])
        except UnicodeEncodeError:
            msg = "{} | {}: {}".format(data['buffer'], data['prefix'],
                                       data['message'].encode('utf-8'))
    else:
        try:
            msg = "{} | {}".format(data['buffer'], data['message'])
        except UnicodeEncodeError:
            msg = "{} | {}".format(data['buffer'],
                                   data['message'].encode('utf-8'))
    notification = Notify.Notification(data['type'], msg)
    notification.set_hint("transient", "false")
    notification.set_hint("desktop-entry", "weechat")
    notification.set_category("im.received")
    notification.set_timeout(3000)
    try:
        notification.show()
    except dbus.exceptions.DBusException as e:
        print(e)
        pass
Exemplo n.º 12
0
def main():
    args_parser = argparse.ArgumentParser(description='This is a timer.')
    args_parser.add_argument('time', type=str, help='time can be just seconds, or of the format hh:mm:ss or mm:ss')

    args = args_parser.parse_args()
    
    # If the time is of the format hh:mm:ss
    if re.search(r"^\d\d?:\d\d?:\d\d?$", args.time):
        h, m, s = args.time.split(':')
        timer(int(h)*3600 + int(m)*60 + int(s))
    # If the time is of the format mm:ss
    elif re.search(r"^\d\d?:\d\d?$", args.time):
        m, s = args.time.split(':')
        timer(int(m)*60 + int(s))
    # If the time is just seconds (a number).
    elif re.search(r"^\d+$", args.time):
        timer(int(args.time))
    else:
        print("Unknown time format : {}".format(args.time))
        exit(-1)

    print()
    # Send the notification.
    notify2.init("timer")
    notification = notify2.Notification("timer", message="end of the specified time {}".format(args.time))
    notification.show()
Exemplo n.º 13
0
 def save(self):  # User clicked on save button
     set_chat(self.lineEdit_2.text()
              )  # Setting config values to values in text boxes
     set_token(self.lineEdit.text())  # ^
     self.close()  # Closing pref window
     n = notify2.Notification("clipbot", "Credentials saved!").show()
     print("Saved new credentials.")  # Logging a credentials change
    def __init__(self,
                 host='localhost',
                 port=6600,
                 music_dir=os.path.join('/', 'home', 'davinellulinvega',
                                        'Music')):
        """
        Initialize the required attributes.
        """

        # Initialize the parent class
        super(MpdClt, self).__init__()

        # Notification stuff
        self._notification = notify2.Notification("MPD Notification", "0")
        notify2.init("MPD Notification")

        # Connect to the mpd daemon
        self._host = host
        self._port = port

        # Other stuff
        self._db_updating = False
        self._music_dir = music_dir
        logging.basicConfig(filename='/tmp/mpdNotification.log')
        self._log = logging.getLogger()
Exemplo n.º 15
0
 def receive(self):
     """
     Starts to receiving data...
     """
     while True:
         data = self.conn.recv(1024)
         if not data:
             break
         self.data += data
         if self.cfg.debug:
             self.cfg.logfile.write(data)
     """
     Gets some information.
     """
     self.length, self.command, self.data = re.split(
         r'#(\w+)\s', self.data, maxsplit=1)
     # Retreive more informations.
     self.data_from_command()
     self.sticky.PORT = self.sticky.PORT or STD_PORT
     name = get_name(self.addr[0], self.cfg.friendsfile)
     if name is None:
         name = self.addr[0]
     else:
         name = name[0]
     self.cfg.dest_name = name
     # Let's try to advise the user via notify-send.
     note = notify2.Notification(
         "EtePyStickies: message from {}".format(name),
         self.sticky.TEXT.replace('\n', '\r')[:50],
         'document-send')
     note.show()
     # And call the action if there is one.
     if self.action:
         self.action()
Exemplo n.º 16
0
def main():
    path_config_folder = "/home/quentin/.config/ctrl_email/config.json"
    path_home_folder = "~/.ctrl_email.json"
    if os.path.exists(path_config_folder):
        config_file_path = path_config_folder
    elif os.path.exists(path_home_folder):
        config_file_path = path_home_folder
    else:
        print("Config file must be either in {} or in {}".format(
            path_home_folder, path_config_folder))
        return 1

    cclients = extract_config(config_file_path)

    notify2.init("Ctrl-Email")
    notifyer = notify2.Notification(None, icon="")
    notifyer.set_urgency(notify2.URGENCY_NORMAL)
    notifyer.set_timeout(10000)

    for cclient in cclients:
        cclient.client.extract_data_for_analysis("{}.csv".format(cclient.name))

    while True:
        min_sleep_time = min(map(lambda c: c.sleep_time, cclients))
        time.sleep(min_sleep_time)
        for client in cclients:
            client.sleep_time -= min_sleep_time
            if client.sleep_time == 0:
                client.update()
                client.notify_me(notifyer)
Exemplo n.º 17
0
def Parsefeed():

    # parsing news data from the feed URL
    f = feedparser.parse(
        "http://timesofindia.indiatimes.com/rssfeedstopstories.cms")
    # set any icon for the notification
    ICON_PATH = os.getcwd() + "/icon.ico"
    # initalize the notify2 using init method and initializing the D-bus connection
    notify2.init('News Notify')

    # Looping from the parsed data to get the relevant information and setting the notification icon using notify2 lib

    for newsitem in f['items']:
        print(newsitem['title'])
        print(newsitem['summary'])
        print('\n')

        # create Notification object
        n = notify2.Notification(
            newsitem['title'], newsitem['summary'], icon=ICON_PATH)
        # set urgency level
        n.set_urgency(notify2.URGENCY_NORMAL)
        # show notification on screen
        n.show()

        # set timeout for a notification
        n.set_timeout(100)
        # short delay between notifications
        time.sleep(10)
Exemplo n.º 18
0
def notify(data):
    """ Method to notify the user through dbus """
    if data['prefix'] != '--':
        try:
            msg = "{} => {}: {}".format(data['buffer'],
                                        data['prefix'],
                                        data['message'])
        except UnicodeEncodeError:
            # Yey to python2
            msg = "{} => {}: {}".format(data['buffer'],
                                        data['prefix'],
                                        data['message'].encode('utf-8'))
    else:
        try:
            msg = "{} => {}".format(data['buffer'],
                                    data['message'])
        except UnicodeEncodeError:
            # Woohoo python2
            msg = "{} => {}".format(data['buffer'],
                                    data['message'].encode('utf-8'))
    Notify.init(SCRIPT_NAME)
    notification = Notify.Notification(data['type'], msg)
    try:
        notification.show()
    except dbus.exceptions.DBusException as e:
        print(e)
        pass
Exemplo n.º 19
0
        def sas_invite_notification(self, message):
            notificaton = notify2.Notification(
                "Key verification invite",
                message=(
                    f"{message.user_id} via {message.device_id} has started "
                    f"a key verification process."),
            )
            notificaton.set_category("im")

            def accept_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.AcceptKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            def cancel_cb(notification, action_key, user_data):
                message = user_data
                self.device_if.CancelKeyVerification(message.pan_user,
                                                     message.user_id,
                                                     message.device_id)

            if "actions" in notify2.get_server_caps():
                notificaton.add_action("accept", "Accept", accept_cb, message)
                notificaton.add_action("cancel", "Cancel", cancel_cb, message)

            notificaton.show()
Exemplo n.º 20
0
 def net_notif(self, message):
     try:
         notify2.init("Net Stats")
         n = notify2.Notification("Net Stats", "%s test" % (message))
         n.show()
     except:
         raise net_notif_except()
Exemplo n.º 21
0
def launch_app(**kwargs):
    app = QApplication(sys.argv)
    pomodoro = create_pomodoro_timer(**kwargs)

    # Подключаемся к DBus для уведомлений
    notify2.init('Pomodoro', 'glib')

    tray_icon: QSystemTrayIcon = QSystemTrayIcon(QIcon('static/icon.png'), app)
    tray_icon.setToolTip('Manage your time!')
    tray_icon.show()

    menu = QMenu()
    display_menu: QAction = menu.addAction('00:00')
    display_menu.setEnabled(False)
    pause_menu: QAction = menu.addAction('Pause')
    pause_menu.triggered.connect(pomodoro.pause)
    continue_menu: QAction = menu.addAction('Continue')
    continue_menu.triggered.connect(pomodoro.continue_work)
    exit_menu = menu.addAction('Exit')
    exit_menu.triggered.connect(app.quit)

    tray_icon.setContextMenu(menu)
    tray_icon.contextMenu().aboutToShow.connect(
        lambda: menu_opening_event(pomodoro, display_menu))

    pomodoro.start()

    n = notify2.Notification('Pomodoro запущен')
    n.timeout = 700
    n.show()

    app.exit(app.exec_())
Exemplo n.º 22
0
    def __init__(self, config, nogui=False):
        self._config = config

        # For displaying wx windows
        logging.debug("Creating app")
        self._app = wx.App()

        self._nogui = nogui

        try:
            # Uses Gobject, which works with both GTK2 or GTK3
            import notify2
            notify2.init("Odemis")
            self._notif = notify2.Notification("")
        except ImportError:
            # Warning: wx will crash if Pynotify has been loaded before creating
            # the wx.App (probably due to bad interaction with GTK).
            # That's why we only import it here. It only works if wxPython uses
            # GTK2. If GTK3 is used, chaos will ensue, without explanations.
            logging.debug("Cannot use notify2, falling back to pynotify")
            import pynotify
            pynotify.init("Odemis")
            self._notif = pynotify.Notification("")

        # For listening to component states
        self._mic = None
        self._comp_state = {}  # str -> state
        self._known_comps = []  # str (name of component)
        self._backend_done = threading.Event()

        self._component_frame = None
Exemplo n.º 23
0
    def _init_gui(self):
        """Parts of __init__ that should only run in the single instance."""
        # Check for some deps late enough to display a GUI error message
        dep_err = self._check_deps()
        if dep_err:
            dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                                    gtk.BUTTONS_OK, dep_err)
            dlg.set_title("GOG Downloader")
            dlg.run()
            sys.exit(1)

        self.gtkbuilder_load('lgogd_uri.glade')
        self.data = self.builder.get_object('store_dlqueue')

        # Load the lgogdownloader settings
        self.lgd_conf = get_lgogd_conf()

        # Prepare a libnotify notification we can reuse
        if notify and notify.init("lgogd_uri"):
            self.notification = notify.Notification("GOG Downloads Complete",
                                                    icon='document-save')

        try:
            parent = os.path.dirname(self.save_dir_store)
            if not os.path.exists(parent):
                os.makedirs(parent)
        except OSError, err:
            log.error("Cannot prepare to remember target directory: %s", err)
Exemplo n.º 24
0
def notify():

    icon_path = "/home/dushyant/Desktop/Github/Crypto-Notifier/logo.jpg"

    cryptocurrencies = [
        "bitcoin",
        "ethereum",
        "litecoin",
        "monero",
        "ripple",
    ]

    result = ""

    for coin in cryptocurrencies:
        rate = fetch_coin(coin, "usd")
        result += "{} , {} - {}\n".format(coin, rate[1].encode('utf-8'),
                                          rate[2].encode('utf-8'))

    # print result

    notify2.init("Cryptocurrency rates notifier")
    n = notify2.Notification("Crypto Notifier", icon=icon_path)
    n.set_urgency(notify2.URGENCY_NORMAL)
    n.set_timeout(1000)
    n.update("Current Rates", result)
    n.show()
def handle_pa_message(data):
    if data.startswith(b'Please enter your name> '):
        data = data[len('Please enter your name> '):]
        if not data:
            return
    if data:
        name, text = data.decode().strip().split('> ', 1)
        n = notify2.Notification(name.capitalize(), text)
        n.set_hint("transient", True)
        n.timeout = 2000
        n.show()
    else:
        n = notify2.Notification("PA", "Disconnected")
        n.timeout = 2000
        n.show()
        exit(0)
Exemplo n.º 26
0
    def __init__(self, parent, device_id, device_name):
        super(BatteryNotifier, self).__init__()
        self._logger = logging.getLogger(
            'razer.device{0}.batterynotifier'.format(device_id))
        self._notify2 = notify2 is not None

        self.event = threading.Event()

        if self._notify2:
            try:
                notify2.init('razer_daemon')
            except Exception as err:
                self._logger.warning(
                    "Failed to init notification daemon, err: {0}".format(err))
                self._notify2 = False

        self._shutdown = False
        self._device_name = device_name

        # Could save reference to parent but only need battery level function
        self._get_battery_func = parent.getBattery

        if self._notify2:
            self._notification = notify2.Notification(summary="{0}")
            self._notification.set_timeout(NOTIFY_TIMEOUT)

        self._last_notify_time = datetime.datetime(1970, 1, 1)
Exemplo n.º 27
0
def sendNotification(lst, tipster):
    # logo for notification

    # initiate Notify2 plugin
    notify2.init("BetAlert")

    # create Notification object
    n = notify2.Notification(None)

    # set urgency level
    n.set_urgency(notify2.URGENCY_NORMAL)

    # set timeout for a notification
    n.set_timeout(1000)

    # show notification on screen
    if len(lst) > 1:
        for count, item in enumerate(lst):
            n.update("BetAlert -- {} new tips from {}! ({} / {})".format(
                len(lst), tipster, count + 1, len(lst)),
                     item,
                     icon=ICON_PATH)
            n.show()
            time.sleep(5)  # Cooldown of 5 seconds between tips of same tipster
    else:
        n.update("BetAlert -- New Tip from {}!".format(tipster), lst[0])
        n.show()
Exemplo n.º 28
0
    def showRSS(self):
        RSS_URL = input("Please enter RSS URL: ").strip()
        if ".xml" in RSS_URL.split("/")[-1]:
            article = getStories(RSS_URL)
            try:
                # path to notification window icon
                ICON_PATH = "put full path to icon image here"

                notify2.init("News Notifier")

                notify = notify2.Notification(None, icon=ICON_PATH)

                # set urgency level
                notify.set_urgency(notify2.URGENCY_NORMAL)

                # set timeout for a notification
                notify.set_timeout(10000)
                while True:
                    info = next(article)

                    # update notification data for Notification object
                    notify.update(info['title'], info['description'])

                    # show notification on screen
                    notify.show()

                    # short delay between notifications
                    time.sleep(5)
            except (GeneratorExit, StopIteration):
                print("Caught exit and finished displaying notifications!")
        else:
            print("Not an RSS Page!")
Exemplo n.º 29
0
def desktopNotify(message2):
    print("sending desktop Notification")
    notify2.init("updateNotifier")

    n = notify2.Notification('Updates from aitplacements.com', message2)
    n.show()
    time.sleep(3)
Exemplo n.º 30
0
def notify():

    icon_path = "/home/dushyant/Desktop/Github/Crypto-Notifier/logo.jpg"

    bitcoin = Rates.fetch_bitcoin()
    ethereum = Rates.fetch_ethereum()
    litecoin = Rates.fetch_litecoin()
    monero = Rates.fetch_monero()

    result = ""
    result = result + str(bitcoin[0]) + "  -  " + str(
        bitcoin[2].encode('utf-8')) + "\n"
    result = result + str(ethereum[0]) + "  -  " + str(
        ethereum[2].encode('utf-8')) + "\n"
    result = result + str(litecoin[0]) + "  -  " + str(
        litecoin[2].encode('utf-8')) + "\n"
    result = result + str(monero[0]) + "  -  " + str(
        monero[2].encode('utf-8')) + "\n"

    # Notification Tool

    # print result

    notify2.init("Cryptocurrency rates notifier")
    n = notify2.Notification("Crypto Notifier", icon=icon_path)
    n.update("Current Rates", result)
    n.show()