Desktop notifier in Python

Python Methods and Functions

Desktop Notifier — it is a simple application that creates a popup message notification on the desktop.

Notification content

In the example we are using in this article, the content that will appear as a desktop notification is breaking news of the day.

So, to get the top headlines, we'll use this Python script to clean up the news headlines:

import requests

import xml.etree.ElementTree as ET

 
# rss feed address

RSS_FEED_URL = " http:// www.hindustantimes.com/rss/topnews/rssfeed.xml " 

  

def loadRSS ():

"" "

  utility function for loading an RSS feed

"" "

  # create a response object for the HTTP request

  resp = requests.get (RSS_FEED_URL)

 

# return from obsessed response

return resp.content

 

def parseXML (rss):

  " ""

XML parsing utility function

"" "

  # create root element of the element tree

root = ET.fromstring (rss)

 

# create empty news list

  newsitems = []

 

# repeat news

for item in root.findall ( '. / channel / item' ):

news = {}

 

# iterate through child elements of the element

  for child in item:

 

# special validation of the namespace object content: media

if child.tag = = '{ http://search.yahoo.com/mrss/ } content' :

news [ 'media' ] = child.attrib [ 'url' ]

  else :

news [child.tag] = child.text.encode ( 'utf8' )

  newsitems. append (news)

 

# return news list

return newsitems

 

def topStories ():

"" "

Main function for generating and returning news

"" "

  # download rss feed

  rss = loadRSS ()

  

# parse XML

newsitems = parseXML (rss)

return newsitems

This is a simple Python script that parses news headlines available in XML format.

Note. To understand how XML parsing works, refer to this article:

Save this Python script as topnews.py (since we are importing it under this name into our desktop notifications app).

structures

Now, to create a desktop alert, you need to install the third-party Python module notify2 .

You you can install notify2 with a simple pip command:

  pip install notify2 

Desktop Notification App

We are now writing a Python script for our desktop notifier.

Consider the code below:

< tbody>

import time

import notify2

from topnews import topStories

  
# path to the notification window icon

ICON_PATH = "put full path to icon image here"

 
# receive news

newsitems = topStories ()

 
# initialize d-bus connection

notify2.init ( "News Not ifier " )

  
# create notification object

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

 
# set urgency
n.set_urgency (notify2.URGENCY_NORMAL)

 
# set notification timeout

n.set_timeout ( 10000 )

 

for newsitem in newsi tems:

 

# update the notification data for the Notification object

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

 

# show notification on screen

n. show ()

 

# small delay between notifications

time.sleep ( 15 )

 

Let's try to parse the above code step by step:

  • Before we can send any notifications, we need to initialize the connection D- Bus. D-Bus — it is a message bus system, an easy way for applications to communicate with each other. So the D-Bus connection for notify2 in the current Python script is initialized with:
      notify2.init ("News Notifier") 

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

  • Now we create a notification object, n with:
      n = notify2.Notification (None, icon = ICON_PATH) 

    General syntax for the above method:

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

    Here,

    • summary: title text
    • message: body text
    • icon: path to icon image

    Currently time we set summary to None and passed ICON_PATH to as the icon argument.

    Note. You need to specify the full path to image icon.

  • Optionally, you can set the urgency level of notifications using the set_urgency method:
      n.set_urgency (notify2.URGENCY_NORMAL)  

    Available constants:

    • notify2.URGENCY_LOW
    • notify2.URGENCY_NORMAL
    • notify2.URGENCY_CRITICAL
  • Another optional utility is the set_timeout, method with which you can explicitly set the display duration in milliseconds, as shown below:
      n.set_timeout ( 10000) 
  • Now as we iterate over each news item one by one, we need to update the notification object with new bulletins and messages, using the update method:
      n.update (newsitem ['title'], newsitem [' description'])  
  • To display a notification, simply call the show () method of the notification object, like this:
      n.show () 

Example desktop screenshot when run over Python script:

Github repository for this app for desktop notifications: Desktop-Notifier-Example

This blog is provided by Nikhil Kumar . If you like Python.Engineering and would like to contribute, you can also write an article using contrib.python.engineering, or email your article to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.