Python Desktop News Notifier in 20 lines

Python Methods and Functions

To start using Desktop News Notifier, we need two libraries: feedparser and notify2. 
Issue the following command to install feedparser:

 sudo pip3 install feedparser 

To install notify2 in your terminal:

 sudo pip3 install notify2  

Feedparser will parse the feed we receive from the URL. We will be using notify2 for desktop notifications. Apart from these two libraries, we will be using the OS and the temp library. After the installation is complete, import both libraries into the program. Here in this example I analyzed news from BBC UK, you can use any news feed url. Let`s take a look at the program:


# Python program for illustration
# desktop news

import feedparser

import notify2

import os

import time

def parseFeed ():

f = feedparser.parse ( " " )

  ICON_PATH = os.getcwd () + "/ icon.ico"

  notify2.init ( `News Notify` )

for newsitem in f [ `items` ]: 

n = notify2.Notification (newsitem [ `title` ], 

newsitem [ `summary` ], 

  icon = ICON_PATH 


  n.set_urgency (notify2.URGENCY_NORMAL)

n .show ()

n.set_timeout ( 15000 )

  time. sleep ( 1200 )


if _ name_ = `_main_` :

  parseFeed ()

Screenshot of news notification toast

Step by step / br >

  1.  f = feedparser.parse ("") 

    Here feedparser will parse the news data from the feed url. The parsed data will be in the form of a dictionary.

  2.  ICON_PATH = os.getcwd () + "/icon.ico" 

    If you want to set any icon in the notification , then here we set the path to the icon. This is optional.

  3.  notify2.init (`News Notify`) 

    Here we initialize notify2 using the init method of notify2. Initialize the D-Bus connection. Must be called before you send any notifications or receive information or server capabilities.

  4.  for newsitem in f [`items`]: n = notify2.Notification ( newsitem [`title`], newsitem [` summary`], icon = ICON_PATH) 

    Cycle through the parsed data to retrieve relevant information such as news title, brief summary, and setting a notification icon using the Notification2 method in lib notify2.

  5.  n.set_urgency (notify2.URGENCY_NORMAL) 


  6. () 

    This method will show a desktop notification

  7.  n.set_timeout (15000) 

    Sets the time to save the notification on the desktop (in milliseconds). I set it here as 15 seconds.

  8.  time.sleep (1200) 

    Usually this will display a news notification every 20 minutes. You can set the time as per your requirement. You can find the full source code at GitHub

This article is courtesy of Srce Cde . If you like Python.Engineering and would like to contribute, you can also write an article using, 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`d like to share more information on the topic discussed above.

Get Solution for free from DataCamp guru