Mobile and Laptop push notifications over Python

Javier Galvis
5 min readAug 13, 2018

--

The part I really don’t like about training machine learning algorithms is the wait… Let’s face it, it’s like watching paint dry, and there are many things we can spend some time on while those slow scripts take their time. In my case, I could go out for a run, catch up on my reading, and even work on other projects.

On this post, you’ll find a collection of a few simple tricks I use so I don’t have to keep on checking if a model or script are still running. My favorite is the mobile push notification, but choose the one that fits your needs the best. For instance, the Slack API works great when working on teams.

  • Slack: Send a notification (and the file) to Slack
  • Mobile: Send a Push notification to an app in your mobile phone
  • email: Send yourself an email. Not very useful when you have the former two options so I won’t get into that for now

Slack!

Send a notification (and the file if you want to) over Slack.

For more information. look into https://github.com/slackapi/python-slackclient

First of all, let’s install the slack library on your environment using either:

  • For Anaconda: conda install -c conda-forge slackclient
  • Else: pip install slackclient

1. Get your Token:

The first thing is to get your token on the following link: https://api.slack.com/custom-integrations/legacy-tokens

Note: Yes, I’ve noticed they are now called ‘Legacy Tokens’ and might be deprecated in the future. I promise I’ll update the post once I look into the new ways that are being implemented, or if you figure it out before, please, reach up and share with us.

2. Sending Messages:

Once you have that, we can send a message over our channel, just use the following code:

slack_token = 'SLACK_API_TOKEN' # Remember to keep your token private.
sc = SlackClient(slack_token)
sc.api_call('chat.postMessage', # Method
channel = '@javier.galvis', # If you use the user name, the message will be privately delivered over the slackbot channel.
text = 'Your model has been trained.')

3. Share Files:

Sending files is just as easy, just change the method to ‘files.upload’. The file should be uploaded to the channel (by your user) and your team would be able to download it.

The following chunk should do the trick:

sc = SlackClient(slack_token)
sc.api_call('files.upload',
filename='submission_bayesian_XGB.csv',
channels='general',
file=open('example_data\submission_bayesian_XGB.csv','rb'))

4. Wrap-Up Function:

Finally, always remember to build functions for code that you have to use often. If you’ll be using this over and over, it pays to code a function so you save some time. This is my version but feel free to experiment with different methods and build your own version (and please, share it with us).

from slackclient import SlackClient

def send_slack_message(text = None, filename = None, filepath = None, channel = 'general', method = 'message', print_response = False):
'''
Function that either:
1. Receives Text, Channel, and method='message'; and sends the text as a message over the specified channel.
2. Receives a Channel, a File Name and Path, Channel, and method='file'; and shares the file over the given channel
'''

slack_token = 'SLACK_API_TOKEN' # Remember to keep your token private.
sc = SlackClient(slack_token)

if method == 'message':
method = 'chat.postMessage'
if (text == None) & ((filename != None) & (filepath != None)): # These couple lines will help the program avoid errors when the user forgets to change the method.
print('Using "file" as method.') # Print a warning stating that the method has been changed
method = 'files.upload'
elif method == 'file':
method = 'files.upload'
else:
print('Please check valid method.')

if method == 'chat.postMessage':
response = sc.api_call(method = method,
channel = channel,
text = text)
elif method == 'files.upload':
response = sc.api_call(method,
filename = filename,
channels = channel,
file = open(filepath,'rb'))

if print_response: # If the user want's to read the entire response from Slack's API
return response
else:
if response['ok'] == True: # When the message is sent, API's response indicates it. This fails when it comes to files.
print('Message sent')
else:
print('Error, printing response.')
return response

Mobile Push notifications via Pushbullet

Send a push notification to your iPhone or Android

Now, this is much simpler to code and use, and I love the idea to just get a push notification on my mobile.

The application I’m using for this is Pushbullet, and works great for other uses, you might want to check it out.

  1. The first thing is to get the app and sign-up, you can do this at: https://www.pushbullet.com/
  2. Get your token at https://www.pushbullet.com/#settings
  3. Download the app on your phone and logon
  4. Run the code below in your Python notebook (replacing with your own token, of course).

For more information, visit: https://docs.pushbullet.com/#create-push

Original idea found on https://simply-python.com/2015/03/23/sending-alerts-to-iphone-or-android-phone-using-python/

Let’s just move into the code:

import requests
import json
def pushbullet_message(title, body):
msg = {"type": "note", "title": title, "body": body}
TOKEN = 'PUSHBULLET_TOKEN'
resp = requests.post('https://api.pushbullet.com/v2/pushes',
data=json.dumps(msg),
headers={'Authorization': 'Bearer ' + TOKEN,
'Content-Type': 'application/json'})
if resp.status_code != 200:
raise Exception('Error',resp.status_code)
else:
print ('Message sent')

As you can see, it’s very easy to do and you’ll be able spend time on more valuable things than looking at your model converge. Let us know if you think of some cool ideas to go from here.

You might encounter some limitations though. For instance, if your code crashes before reaching the messaging function, you’d never get the notification. However, I’m sure this won’t be a big issue.

Share your comments, let us know what you think.

--

--