In this article, we will discuss two apps and how they can be configured using python to send notifications.
Pushbullet
Pushbullet, a prominent Python package, which connects multiple devices using python code. In this article, we will discuss how to send messages or notifications through it. Using our computer and python code, we will send some messages to the pushbullet app installed on a mobile device, which has the same login id, as the one on the computer. For this first, we’ll need to create an account on Pushbullet.com and sign in to it, from computer and phone both.
Setup:
- Set up a Pushbullet account on your PC and Phone
- For PC
- Go to Pushbullet.com
- Create an account
- For PC
- For Phone
- Install the Pushbullet app on your phone.
- Log in using the same email address that you used to log in to your PC.
Now let us move to the python code part and understand how each requirement has to be planned to realize the functionality.
- Install the following modules listed below
# Used for sending the Push notifications. pip install pushbullet.py==0.9.1 # Used for the interface at the output window. pip install pywebio
- Import all the required modules
- Go to Pushbullet and obtain the access token.
- Get your Access Token and use the PushBullet method to create an instance by providing the Access Token in the PushBullet function.
Syntax:
PushBullet(access_token)
- Use the push_note function to send data and text inside the function. push_note will take two arguments i.e. data and text. the first argument will work as a Heading in the notification where 2nd argument is a text.
Syntax:
pb.push_note(data, text)
Below is the complete implementation.
Python3
# Import the following modules from pushbullet import PushBullet from pywebio. input import * from pywebio.output import * from pywebio.session import * import time # Get the access token from Pushbullet.com access_token = "Your Access Token" # Taking input from the user data = input ( 'Title' ) # Taking large text input from the user text = textarea( "Text" , rows = 3 , placeholder = "Write something..." , required = True ) # Get the instance using access token pb = PushBullet(access_token) # Send the data by passing the main title # and text to be send push = pb.push_note(data, text) # Put a success message after sending # the notification put_success( "Message sent successfully..." ) # Sleep for 3 seconds time.sleep( 3 ) # Clear the screen clear() # Give the pop at last toast( "Thanks for using it :)" ) # hold the session until the whole work finishes hold() |
There is one more way to do the same, discussed below. In this method, a predefined message is sent as a notification.
For this, first import the required modules and get your Access Token.
Syntax:
TOKEN = 'Your Access Token'
Then Make a dictionary with all the information you wish to send in the body.
Syntax:
msg = {“type”: “note”, “title”: title, “body”: body}
Now, to send the posts request, use the posts method specified in the requests module. Push the Pushbullet along the entire path. Now use json.dumps to dump all the data into a data variable.
Now pass the dictionary to the header variable, which includes the sender’s authorization, your access token, and content-types, which is application/json in this case.
Syntax:
requests.post(‘url’, data=json.dumps(msg), headers={‘Authorization’: ‘Bearer ‘ + TOKEN, Content-Type’: ‘application/json’})
Now look at the response status code; if it’s 200, we’ve had an error; otherwise, our message will have been sent properly.
Given below is the complete implementation.
Program:
Python3
# Import the following modules import requests import json # Function to send Push Notification def pushbullet_noti(title, body): TOKEN = 'Your Access Token' # Pass your Access Token here # Make a dictionary that includes, title and body msg = { "type" : "note" , "title" : title, "body" : body} # Sent a posts request data = json.dumps(msg), headers = { 'Authorization' : 'Bearer ' + TOKEN, 'Content-Type' : 'application/json' }) if resp.status_code ! = 200 : # Check if fort message send with the help of status code raise Exception( 'Error' , resp.status_code) else : print ( 'Message sent' ) pushbullet_noti( "Hey" , "How you doing?" ) |
Output:
Slack
In this part we will be dealing with posting messages from python script that will appear in slack. For this, we need to make use of webhooks. You can deliver automatic messages from one app to another using webhooks. When you create an Incoming Webhook, you’ll be given a unique URL to which you may send a JSON payload including the message text and some parameters.
Setup
Create a Slack Workspace here and create your own app.
- go to Browse Slack
- Select Apps
- A new window will appear. From there select App Directory
- Now select Build
- Again a new window will open up, select create an app
- Select from scratch
- Set app name and workspace
- Then create app
- Select Incoming Webhooks
- Turn activate incoming webhooks on and add new webhook to workspace
- select a bot and give it allow access
- Copy the webhook URL as this will be used later
Now that we’ve created the app and obtained the webhook URL, it’s time to start coding.
We first have to import all the required modules. Now, get your webhook URL and save it to the variable. In a variable, save the message and title you want to send.
Now it’s time to make all the slack data we want to send. It consists of your username and in the Attachment section we have:
- The color you want to choose.
- Fields consist of the following things:
- Title of our message.
- The message we want to send.
- Short means, display message should be of sort type or long type.
Now with the use of the sys module, we will get the size of the slack data and store it in a variable. Now for headers, we will define the Content-Type and Content-Length. Use the post method of requests module to post all, the data after dumping it using the dumps function of json module. At last, check whether the response is valid or not with the use of a status code.
Program: Sending notifications via slack
Python3
# Import the following modules import json import sys import requests import base64 if __name__ = = '__main__' : # Webhooks URL # Message you wanna send message = ( "Hi there!, Lazyroar is the Best Learning Platform\ for Computer Science Students") # Title title = (f "Lazyroar Bot :satellite:" ) # All slack data slack_data = { "username" : "Testing" , "attachments" : [ { "color" : "#FF0000" , "fields" : [ { "title" : title, "value" : message, "short" : "false" , } ] } ] } # Size of the slack data byte_length = str (sys.getsizeof(slack_data)) headers = { 'Content-Type' : "application/json" , 'Content-Length' : byte_length} # Posting requests after dumping the slack data response = requests.post(url, data = json.dumps(slack_data), headers = headers) # Post request is valid or not! if response.status_code ! = 200 : raise Exception(response.status_code, response.text) |
Output: