Android,iOS,Gadgets,Reviews Everything About Technology

Send push notifications to the desktop in Linux using Python

789

A desktop notification is a pop-up message on the desktop that notifies you of an event.

A computer can send you a notification for a variety of reasons, not necessarily related to your current activities: software update, a new message in the messenger, low battery power and much more.

The most suitable option for notifications that do not need immediate user response is not an interactive pop-up notification.

- Advertisement -

Today we will create a program that will send such notifications.

More information about notifications in Linux can be found in the Gnome documentation and in the Arch Linux documentation .

Preparation

To send notifications, we need a package for Python notify2, which can be installed using the command pip install notify2.

Note. trans.This article uses the notify2 library, which is a pure implementation of push notifications in Python. However, there are other Python libraries for push notifications – for example, the django-push-notifications library .

Creating Crypto-Notifier

Let’s write a tool that will report the current bitcoin rate to the dollar.

The whole process of the program can be divided into three steps:

  1. Collection of data for display.
  2. Initialize the notification sending tool.
  3. Display data in a pop-up notification.

Data collection

To get the current bitcoin to dollar rate, we need to extract data from CoinGecko . Since this site does not provide an API, we need to get data from pure HTML. We will do this using the BeautifulSoup library .

The data we need is in the <table> and <tr> tags. The structure of the page is shown in the screenshot below:

Create a file called rates.py and put the following code into it:

from bs4 import BeautifulSoup
import requests

def fetch_bitcoin():
    # URL with current course
    url = "https://www.coingecko.com/en/price_charts/bitcoin/usd"
    headers = {'User-Agent': 'Mozilla/5.0'}
    bitcoin_file = requests.get(url)
    
    # Create a soup object
    soup = BeautifulSoup(bitcoin_file.text, "html.parser")

    bitcoin_li = []

    # Extract the necessary data from the tags
    for table in soup.find_all("table", attrs={"class" : "table table-responsive mt-2"}):
        for td in table.find_all("td"):
            bitcoin_li.append(td.text)

    del bitcoin_li[3:]
    
     # Remove unnecessary characters from list items
    bitcoin_li = map(lambda s : s.strip(), bitcoin_li)
    return bitcoin_li

Here we defined a function that returns the details of the course in the form of a list after retrieving the information according to the specified url.

Initializing the push notification tool

After receiving the information we need to display, we need to initialize the push notification tool, as shown below:

import notify2
import rates

def notify():      ICON_PATH = "full path to the icon"           # Get the current rate      bitcoin = rates.fetch_bitcoin ()           # Initialize the d-bus connection      notify2.init ("Cryptocurrency rates notifier")        # Create a Notification object      n = notify2.Notification ("Crypto Notifier", icon = ICON_PATH)               # Set the urgency level      n.set_urgency (notify2.URGENCY_NORMAL)               # Set the delay      n.set_timeout (1000)

Let’s walk through the code step by step:

Before we can send any notifications, we need to initialize the D-Bus connection. D-Bus is a process-to-process (IPC) mechanism that programs on Linux use to interact with each other. To display a notification, our program must connect via D-Bus to the process controlling the system interface and send it notification information, such as its title, text and icon. More information about how this is arranged can be read on the official website , but in the notify2 library we are using, all this has already been implemented. The only thing we need to do is call the function notify2.init(), passing the name of our program to it so that notify2 can establish and initialize the connection to the D-Bus:

notify2.init ("Crypto currency course notice tool")

Then we create a notification object:

= notify2.Notification("Crypto Notifier", icon = ICON_PATH)

General structure of the notification object:

notify2.Notification(summary, message='body text', icon=ICON_PATH)

If desired, we can set the urgency level using the set_urgency method:

n.set_urgency(notify2.URGENCY_NORMAL)

Other available constants are: notify2.URGENCY_LOWnotify2.URGENCY_CRITICAL.

Also we can set a delay between sending notifications:

n.set_timeout(1000)

Displaying content

With the initialization finished, let’s take care of displaying notifications. The code snippet below shows how to do this:

result = '{0} — {1}'.format(*bitcoin) 

# Update the content
n.update ("Current course", result)

# Show notification
n.show()

Let’s analyze the code:

  1. First, we create the content for display using the list returned by the function fetch_bitcoin.
  2. Then we transfer this content to our tool for sending notifications.
  3. Finally, we show the notification using n.show().

In the end, we should get something like this:

Comments