SMS Bot Using Python and Twilio

I built the SMS bot using the Twilio API and Python, which allows you to send a Twilio number messages and get answers back. I got the inspiration of this project and some part of the codes from Make webpage. For this work I used Twilio API, Ngrok, Flask, Wolfram Alpha API, Wikipedia, and yWeather.

Steps:

1. Install ngrok and add the exec file in Mac:

/usr/local/bin

2. Go to twilio webpage (https://www.twilio.com/)and get free API and number (number should have sms capability)
3. Install ngrok and add the exe file here (open /usr/local/bin)
4. You need to get API from Wolfram Alpha (https://products.wolframalpha.com/api/) and add that API to getReply.py line 43.
5. Run run.py
6. Type in terminal (same path as run.py)

ngrok http port_number

You will see on you screen:

Version                                                            
Region                                                    
Web Interface                                              
Forwarding                           
Forwarding 

copy one of the Forwarding address (something like http:// …. .io)

7. Go to your Twilio dashboard and press the “#” on the left. Click on your Twilio number, scroll down and enter the http address into the space that says “A message comes in” in Messaging part. Make sure the dropdown is set to “webhook”. Now paste the Forwarding address here!
8. Open sms app on your mobile and type your question and send in to your Twilio number. (e.g., wiki Barak Obama )
9. Thanks to Sophia Smith and me, now you have working SMS chatbot 🙂


***** removeHead.py *****

# -*- coding: utf-8 -*-
# Function for editing input text.
def removeHead(fromThis, removeThis):
    if fromThis.endswith(removeThis):
        fromThis = fromThis[:-len(removeThis)].strip()
    elif fromThis.startswith(removeThis):
        fromThis = fromThis[len(removeThis):].strip()
    
    return fromThis

***** getReply.py *****

# -*- coding: utf-8 -*-
from removeHead import removeHead
import wikipedia
import yweather
import urllib2, urllib, json 
import wolframalpha


# Function to formulate a response based on message input.
def getReply(message):
    
    # Make the message lower case and without spaces on the end
    message = message.lower().strip()
    # store our response
    answer = ""
    # is the keyword "weather" in the message? Ex: "weather Oslo, Norway"
    if "weather" in message:
        message = removeHead(message, "weather")
        
        # Get the weather for the request
        try:
	     # Get the weather
	    baseurl = "https://query.yahooapis.com/v1/public/yql?" 
	    client = yweather.Client()
            a  = client.fetch_woeid(message)	    
	    yql_query = "select item.condition.text from weather.forecast where woeid="+a
	    yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json" 
	    result = urllib2.urlopen(yql_url).read() 
	    data = json.loads(result) 
	    
	    answer=data['query']['results']['channel']['item']['condition']['text']

        except:
            # handle errors or non specificity errors 
            answer = "We could not find your location. Be more specific?"	
	
            
    # is the keyword "wolfram" in the message? Ex: "wolfram pi"
    elif "wolfram" in message:
	message = removeHead(message, "wolfram")
	try:
            ## Edit here with your API ##
	    client = wolframalpha.Client("your wolfram API") ##### app_id
	    res = client.query(message)
	    answer=next(res.results).text
	    
	except:
	    answer = "We could not find your answer. Ask another question?"
    
    # is the keyword "wiki" in the message? Ex: "wiki Barack Obama"
    elif "wiki" in message:
        # remove the keyword "wiki" from the message
        message = removeHead(message, "wiki")
        
        # Get the wikipedia summary for the request
        try:
	     # Get the summary of wikipedia
            answer = wikipedia.summary(message)
        except:
            # handle errors or non specificity errors
            answer = "We could not the name you are looking for. Can you check the spelling?"	
    
    # Shortening wikipedia test for Twilio sms 
    if len(answer) > 1500:
        answer = answer[0:1500] + "..."
    
    # return the formulated answer
    return answer

***** run.py *****

# -*- coding: utf-8 -*-
from flask import Flask, request
from twilio import twiml
from getReply import getReply
# set up Flask to connect this code to the local host, which will
# later be connected to the internet through Ngrok
app = Flask(__name__)
    
# When a POST request is sent to our local host through Ngrok 
# Twilio service sends the POST request. 
# when a message is sent over SMS to our Twilio number, this code will run
@app.route('/', methods=['POST'])
def sms():
    # Get the text in the message sent
    message_body = request.form['Body']
    
    # Create a Twilio response object to be able to send a reply back
    resp = twiml.Response()
    
    # Send the message body to the getReply message, where 
    # we will query the String and formulate a response
    replyText = getReply(message_body)

	# Text back our response!
    resp.message('Here is the result:\n\n' + replyText )
    return str(resp)
	
if __name__ == '__main__':
    app.run()

Leave a Reply

Your email address will not be published. Required fields are marked *