How I satisfied a request from my friend with Python

 

You may have wondered by now why the title is in that way. Yes, my friend requested me to do a task. What is the request and how I completed that will be known to you if you read this story.

The Story

Two days back my friend Sai Madhu is leaving to his home place from our office in Kochi, which is 700 miles away. He booked the train and should leave in the afternoon. He is very passionate about cricket. He never missed the score when the Indian cricket team is playing. On the same day there is an ODI match between England and  India. Because he doesn’t have a smartphone to access, in the train, he is crippled  to know the score. But he had a feature phone. He requested me to send the score as sms frequently, and I gave my word. I have lots of work to do and thought for a moment “Whether I unthinkingly gave my word to him? No whatever I should send him the score”. Then python came into the rescue. In the next section you find how I successfully handled Sai Madhu request.

Python pulled rabbit out of hat

I thought “why  do I not automate the process?” and  two things came into my mind.

1. Scraping the score from the live score website

2. Send him an SMS, consisting score through a message API

3. SMS is sent for every 3 minutes

Step 1:

import requests

from lxml import html

Step 2:

I am using twilio for sending the SMS here. You can sign up  a free account and  can enjoy sending SMS for verified numbers. There are  lots of free SMS api but twilio works perfectly. I verified Sai Madhu no and kept ready to go. To access our twilio account from python program,we require to install  a package called twilio and we can get it easily by typing

$ sudo pip install twilio

Now installation is over and twilio library is ready to use.Do this final import.

from twilio.rest import TwilioRestClient

Now we imported all the tools required for completing my job of automation.

import requests
from lxml import html
from twilio.rest import TwilioRestClient
import time

 

Ok, i also imported time package to use the sleep function in it to make delay of 3 minutes between messages. Twilio provides Account SID  and Authorization token which are required to send a message. We will instantiate a Twillio Rest client with those details. But I am defining a function separately for dealing the sending stuff.I named it sendscore.

def sendscore(body):
    account_sid = "ACe5a382a0fe505XXXXXXXXXXXXXXXXXXX"
    auth_token = "cc2b50d82df3XXXXXXXXXXXXXXXXXXXXXXX"
    client = TwilioRestClient(account_sid, auth_token)
    message = client.messages.create(body=body,to="+919052108147",from_="+1 720-548-2740")
    print message.sid

 

So simple. First i created a twilio client  and passed Account SID,Authorization token as arguments.Then i will get a connection to my twilio account.There are many functions available on a twilio client for sending SMS,sending MMS,making a call etc.But i chose to send SMS. “twlio.messages” creates an instance for monitoring message transactions.I use create function on that  instance to send an SMS. ‘to’ argument is the verified destination no. ‘from_’  argument is the number  which also allocated to us on signup along with SID,token . If message is sent successfully SMS id will be returned else error message.I display it to know what happend actually.Now I design python code for scraping score.

page=requests.get('http://sports.ndtv.com/cricket/live-scores')
tree=html.fromstring(page.text)
score=(tree.xpath('//div[@class="ckt-scr"]/text()')[0].lstrip()).rstrip()

Ok now i got a clean score which is fetched using xpath method on tree object of lxml and formatting it neatly.Observe the way i send the body of the html response to the html.fromstring() to build an element tree.Now i am calling sendscore function with this score that fetched. as argument. It sends a message to the ‘to’ number with the score as it’s body.I also log the thing for monitoring the process.

sendscore(score)
print "%s sent at:%s "%(score,time.ctime())
#to delay a message by three minutes 
time.sleep(180)

This process should run for every three minutes.So i use while loop to achieve that and combine above two snippets.

while True:
    page=requests.get('http://sports.ndtv.com/cricket/live-scores')
    tree=html.fromstring(page.text)
    score=(tree.xpath('//div[@class="ckt-scr"]/text()')[0].lstrip()).rstrip()
    sendscore(score)
    print "%s sent at:%s "%(score,time.ctime())
    time.sleep(180)
This completes the task.Buliding all together will give us the program that sends the Score of England Vs India for every three minutes to Sai Madhu.
#final script for sending score.I name it sendscore.py
from twilio.rest import TwilioRestClient
from lxml import html
import requests
import time



def sendscore(body):
    #Your account_sid goes here
    account_sid = "ACe5a382a0fe505faaXXXXXXXXXXXXXXXX"
    #Your authorization token goes here
    auth_token = "cc2b50d82df3a31cXXXXXXXXXXXXXXXXXX"
    client = TwilioRestClient(account_sid, auth_token)
    #to = "number to which SMS should be sent",from_="your twilio number"
    message = client.messages.create(body=body,to="+919052108147",from_="+1 720-548-2740")
    print message.sid

while True:
    page=requests.get('http://sports.ndtv.com/cricket/live-scores')
    tree=html.fromstring(page.text)
    score=(tree.xpath('//div[@class="ckt-scr"]/text()')[0].lstrip()).rstrip()
    sendscore(score)
    print "%s sent at:%s "%(score,time.ctime())
    time.sleep(180)

You can press Ctrl+C to quit the program.Once you started running it,It automatically sends the score for every three minutes.I designed this program in 5 minutes and Sai Madhu is so much impressed for the accuracy of scores he got that day. “What not one can do with a computer,internet and python ? “.

My intention of writing this post is to show, how we can send a SMS via python program? .We can also send MMS and do calls.You can refer to complete API here. https://www.twilio.com/docs/api/rest .
Hope you enjoyed the post.Bye.

7 thoughts on “How I satisfied a request from my friend with Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s