Sep 202019

Implement mobile notifications from any app or script

Although I am no longer a professional web developer, I still write some scripts from time to time, to help me in life. These scripts could vary from backup scripts to some website parser processing.

Their execution times ranged between a few minutes to a few hours. What I wanted to have is some notification that a script has ended its execution, so I could check the results. What options do I have?

Email?

The easiest way would be to simply send an email, but

  • I wanted to have an instant notification and have email notification disabled (so I wouldn’t be distracted by every single email)
  • I don’t check my inbox every single minute

SMS?

Another option would be sending an SMS, using an SMS gateway. But that would be too easy :). And I wanted to make it free. There?s an additional cost per SMS.

Communication app?

Why not use one of the existing communication apps, like FB Messanger, WhatsApp, Telegram or Signal?
After checking API documentation, the one for Telegram seemed to be easy. I thought I’ll give it a try and at the end – it worked perfectly.
Here’s how I did it.

  1. First of all – install Telegram on desktop or mobile.
  2. Create a bot using BotFather. All you need to do is to send a message “/newbot”, choose a name and username. After that, you’ll receive an API key used later to send messages.
  3. As documentation says – “Bots can’t initiate conversations with users. A user must either add them to a group or send them a message first. People can use telegram.me/<bot_username> links or username search to find your bot.”.  So simply message your bot.
  4. Now we need your user ID. Go to URL:
    https://api.telegram.org/bot**YourBOTToken**/getUpdates
    As YourBOTToken put your bot API key from step 1.
    And you’ll see the ID of your user.
  5. We have all that’s needed to send messages. There is many examples for Node.js, PHP, Python, Java, Ruby, Swift and other but I used very simple callout to send a message.

    Simply run URL
    https://api.telegram.org/botBotToken/sendMessage?chat_id=UserId&text=Hello

  6. Notification will popup in your desktop / mobile app.
  7. Finally – example how to run it in Python
    import urllib.request as urllib2
    import os
    
    token = 'BotApiKey'
    chatId = 'UserId';
    message = 'Hello'
    
    url = 'https://api.telegram.org/bot'+str(token)+'/sendMessage?chat_id='+str(chatId)+'&text='+str(message);
    req = urllib2.Request(url, headers={'User-Agent':'Mozilla/5.0'})
    html_page = urllib2.urlopen(req)
    
    
Tagged with , , 0 comments

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.