shaikhu-blog-v1626889635/image_2_p8gyrm.jpg

How to trigger a job or program from anywhere with a SMS ?

Published on 2020-11-01, by Javed Shaikh

Subscribe for new article
*No spam. unsubscribe at anytime

Its holiday season every where and we don't want to open laptop and system all the time when travelling and enjoying our personal time. In this post, I am going to show how we can run some important jobs or programs with just one SMS when we are on the go.

Introduction

In this tutorial we are going to learn how we can trigger a job or program with just one SMS. For this tutorial we are going to use Twilio API for sending and receiving SMS. With just few lines of codes, we will implement a very basic app to receive sms and trigger jobs based on the sms. So lets check out what we are going to learn in this tutorial.

What we will learn in this article?

📗 How to setup programmable SMS api on Twilio?
📙 How to write a basic Flask app?
📗 How to setup ngrok to access your app outside localhost?
📙 How to run a shell command from Python?

How to setup programmable SMS api on Twilio?

In the very first step, we are going to need a mobile number and API where we can send a SMS and run a script. For this purpose, we are going to use Twilio's beautiful and easy to use API to setup our SMS app.

Get your free $10 credit to use Twilio SMS api

Twilio is providing $10 credit for new user signup and interesting thing about Twilio trial account is that you don't need to have a credit card to try its free service. Please click here and visit Twilio to create a free account and get $10 credit to use its SMS api during trial period.

  • Once your free account is created, login to your account and create a project from top right corner of your dashboard.
  • Then go to All products & services from the left tab and click # Phone numbers. You should see screen similar to below. Click Buy a Number and get a new number where we will send a SMS.

post image H-mXW1yDF_vkckcm

Now that we have a number registered, lets go to next step and setup a Flask app.

How to write a basic Flask app?

As I mentioned we are going to use a very basic Flask app. Before writing our Flask app, lets install virtual environment so that our app will be running independently with the packages installed within the environment.

Step 1: Create virtual environment

  • Lets install virtual environment.
pip3 install virtualenv
  • Now create a virtual environment within a new directory smsapp
shaikh@ubuntu:~/scripts/smsapp$ virtualenv venv
  • Activate the virtual environment
shaikh@ubuntu:~/scripts/smsapp$ source venv/bin/activate
(venv) shaikh@ubuntu:~/scripts/smsapp$


Step 2: Install Flask

  • Install Flask app using below entry
pip3 install flask
  • Lets write very basic flask app with below lines of code.
python
1from flask import Flask 2app = Flask(__name__) 3 4@app.route('/') 5def hello_world(): 6 return 'Hello, World!' 7 8if __name__ == "__main__": 9 app.run() 10

You should see the output "Hello World!" in your localhost at port 5000. As shown above you can check the output at localhost:5000

Step 3: How to install and access app using ngrok

Now that we have installed our flask app and able to run it in our localhost but we cannot access our app outside our local network. To access this app over internet lets install ngrok which will allow us to expose our app over the internet.

  • Install this with below command (for Ubuntu)
snap install ngrok
  • Activate ngrok to expose our app to the internet.
python3 app.py &
ngrok http 5000

This is how it will look once we run above commands

post image _xoC7Pzak_rca7mh

We need to use the ngrok http URL from above output. Lets checkout the app at this url on any device over the internet.

post image x04qK7TFX_vk0umk

How to run a shell command from Python?

To run a shell command from Python, we will use OS module's special function popen().

os.popen(command)

So this is how our Flask app looks like if we want to run a command using popen()

python
1from flask import Flask 2import os 3app = Flask(__name__) 4 5@app.route('/') 6def hello_world(): 7 return 'Hello, World!' 8@app.route('/command',methods=['POST']) 9def command(): 10 command = "/usr/bin/python3 ~/scripts/send_alert.py" 11 os.popen(command) 12 return 'Command executed' 13 14if __name__ == "__main__": 15 app.run() 16

Please note that we have created a new route /command to execute the command to run another python script send_alert.py. You can execute any command you want. For this example I am running a script to send email alert.

So this is how our Flask app will trigger a new process and execute the command. Now we are going to configure Twilio so that when we send sms to its number, Twilio should trigger a HTTP request to our /Command route.

Lets head over to Twilio again and click the mobile number you purchased in previous steps and then update the webhook for "A message comes in" as shown below

post image h7eaz9GqH_wszhfb

Now when we send a sms to Twilio number, It will make HTTP Post request to above link and when it does, our command() function is going to be executed 😃

Now if you want to run multiple jobs based on SMS body (like JOB1,JOB2) we need to install Twilio library so that we can parse SMS and run the jobs accordingly. Here is the app.py looks like with that feature.

python
1from flask import Flask, request 2from twilio.twiml.messaging_response import MessagingResponse 3 4app = Flask(__name__) 5 6@app.route('/command', methods=['POST']) 7def command(): 8 number = request.form['From'] 9 message_body = request.form['Body'] 10 action = message_body.split()[0] 11 12 response = 'command ' + action + ' executed' 13 14 if action.lower()== 'job1': 15 command = "/usr/bin/python3 ~/scripts/job1.py" 16 os.popen(command) 17 18 elif action.lower()== 'job2': 19 command = "/usr/bin/python3 ~/scripts/job2.py" 20 os.popen(command) 21 else: 22 response = "Invalid request 23 24 resp = MessagingResponse() 25 resp.message(response) 26 return str(resp) 27 28if __name__ == '__main__': 29 app.run() 30

As shown above, with the help of Twilio library we are able to parse text message and run jobs based on incoming message content. Now if we send a text 'JOB1' to the Twilio mobile number, Twilio will make a HTTP POST request to our flask app and execute our job1 script. Once job1 script is executed a return sms will be received on your mobile number that 'command executed' else you will receive 'Invalid request' in case you send some invalid job requests:) In above Flask app, you can replace the jobs or program names and add any number of programs or commands or even shell scripts if you want to execute them.

Output:

Here is the output of above script and this is how our app should work.

post image FuxnbdSlP_b1zwkj

Conclusion

Congratulations on building your SMS app to run a job with just a SMS🥳.. In this article we learned some interesting concepts like how to run a shell command from Python script and how to integrate third party sms api to our FLASK app.

Hope this will help you build some amazing sms apps. Let me know your thoughts in the comment section and dont forget to read my other interesting posts in below links.

Thanks for reading this article. Hit like if you want more such posts 😊

Visit my GitHub page for complete code at GitHub


References

  1. https://docs.python.org/3/library/os.html#os.popen
  2. Twilio sms api
  3. Flask documentaion
  4. ngrok

My other recent posts

About the Author

I am a Backend System Engineer at a credit card company, specializing in C/C++ and assembler on IBM's TPF OS. I have a passion for web development and enjoy working with Node.js and Python in my free time.

Connect with author

Related articles ...

How to auto change desktop wallpaper every minute using Python

We are going to build a CLI app using Python to change desktop wallpaper every given number of minutes. Every wallpaper downloaded from internet will be unique and our app will change the wallpaper based on the time we set.

2020-10-27

How to get email alert when your website is down using shell and Python?

There are many ways to monitor and set alerts for your web server using third party apps but they don't come with free, be it Pingdom or Amazon's CloudWatch. In this post I am going to show how we can write and setup our own alert tool with just few lines of code

2020-10-29

Files, Folders and Python

In this post we are going to see how we can use Python to find the size of any file and folder. We will check how many files we have inside a folder and how many of them are empty files and how to delete those empty files.

2020-10-26

How to setup alarm for CPU usage using IFTTT ?

Monitoring CPU and memory usage are one of the top todo checklist for a backend engineer. Sometimes you wont even notice when your server is down due to high CPU usage unless you login and manually check the system.

2020-11-04