Desktop Notifier in Python (original) (raw)

This article demonstrates how to create a simple Desktop Notifier application using Python.

A desktop notifier is a simple application which produces a notification message in form of a pop-up message on desktop.

In the example we use in this article, the content that will appear as notification on desktop is the top news headlines of the day.

So, in order to fetch the top headlines, we will be using this Python script to scrape news headlines:

It is a simple Python script which parses the news headlines available in XML format.

Note: To understand how XML parsing works, please refer this article: XML parsing in Python

A sample news item generated by above Python script looks like this:

{'description': 'Months after it was first reported, the feud between Dwayne Johnson and 
                 Vin Diesel continues to rage on, with a new report saying that the two are 
                 being kept apart during the promotions of The Fate of the Furious.',
 'link': 'http://www.hindustantimes.com/hollywood/vin-diesel-dwayne-johnson-feud-rages-
on-they-re-being-kept-apart-for-fast-8-tour/story-Bwl2Nx8gja9T15aMvcrcvL.html',
 'media': 'http://www.hindustantimes.com/rf/image_size_630x354/HT/p2/2017/04/01/Pictures
/_fbcbdc10-1697-11e7-9d7a-cd3db232b835.jpg',
 'pubDate': b'Sat, 01 Apr 2017 05:22:51 GMT ',
 'title': "Vin Diesel, Dwayne Johnson feud rages on; they're being deliberately kept apart"}

Save this Python script as topnews.py (as we import it by this name in our desktop notifier app).

Installations

Now, in order to create a desktop notifier, you need to install a third party Python module, notify2.

You can install notify2 using a simple pip command:

pip install notify2

Desktop notifier app

Now, we write the Python script for our desktop notifier.

Consider the code below:

import time

import notify2

from topnews import topStories

ICON_PATH = "put full path to icon image here"

newsitems = topStories()

notify2.init( "News Notifier" )

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

n.set_urgency(notify2.URGENCY_NORMAL)

n.set_timeout( 10000 )

for newsitem in newsitems:

`` n.update(newsitem[ 'title' ], newsitem[ 'description' ])

`` n.show()

`` time.sleep( 15 )

Let us try to analyze above code step by step:

notify2.init("News Notifier")  

Here, the only argument we passed is the app name. You can set any arbitrary app name.

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

The general syntax for above method is:

notify2.Notification(summary, message='', icon='')  

Here,

n.set_urgency(notify2.URGENCY_NORMAL)  

The available constants are:

n.set_timeout(10000)  
n.update(newsitem['title'], newsitem['description'])  
n.show()  

A sample screen shot of desktop when you run above Python script:

topnews1

Github repository for this desktop notifier application: Desktop-Notifier-Example

This blog is contributed by Nikhil Kumar.