Python script to make api calls to DatumBox, Twitter, and Maker
try:
import json
except ImportError:
import simplejson as json
# Import the necessary methods from "twitter" library
from twitter import *
import requests
import random
from datetime import datetime as dt
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = '<<Twitter ACCESS TOKEN>>'
ACCESS_SECRET = '<<Twitter ACCESS SECRET>>'
CONSUMER_KEY = '<<Consumer KEY>>'
CONSUMER_SECRET = '<<Consumer SECRET KEY>>'
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter = Twitter(auth=oauth)
#List of politicians to cycle through
politicians = {"Barack Obama" : "@BarackObama", "Paul Ryan" : "@SpeakerRyan",
"Cory Booker": "@CoryBooker", "Donald Trump":"@realDonalTrump", "POTUS" : "@POTUS", "Elizabeth Warren" : "@SenWarren",
"Bernie Sanders" : "@BernieSanders", "Kelleyanne Conway" : "@KelleyannePolls", "Mike Pence" : "@mike_pence",
"John McCain" : "@SenJohnMcCain"}
def run():
#Only run the code at a certain time of day
if(dt.now().hour == 12 and dt.now().minute == 0):
politicianName = random.choice(list(politicians.keys()))
politicianHandle = politicians[politicianName]
makeReq(politicianName,politicianHandle)
def searchTweets(politicianName, politicianHandle):
#Search twitter for the chosen politician
tweets = twitter.search.tweets(q=politicianHandle, result_type='recent', lang='en', count=60)['statuses']
corpus = ''
#Build a corpus of the tweets to be analyzed all at once
for tweet in tweets:
tweetText = tweet["text"]
tweetText = tweetText.replace(politicianHandle,"")
corpus = corpus + " ---- " + tweetText
return corpus
def makeReq(politicianName,politicianHandle):
sentiment = makeAPICall(politicianName, politicianHandle)
#In the photon board code:
#'a' = Positive sentiment
#'b' = Negative sentiment
#'o' = Neutral Sentiemnt
data = "o"
if(sentiment > 0):
data = "a"
elif(sentiment < 0):
data = "b"
payload = {'value1' : data, 'value2' : politicianName }
print(payload)
requests.post("https://maker.ifttt.com/trigger/TwitterSearch/with/key/<<Maker IFTT KEY>>", data=payload)
def makeAPICall(politicianName, politicianHandle):
sentimentVal = 0
#Run twitter search multiple times because the datumbox request has a max corpus length
for i in range(10):
r = requests.post("http://api.datumbox.com/1.0/SentimentAnalysis.json",
params={"api_key":<<DatumBox API KEY>>, "text": searchTweets(politicianName, politicianHandle)})
sentiment = r.json()["output"]['result'
if(sentiment == "positive"):
sentimentVal+=1
elif(sentiment == "negative"):
sentimentVal -= 1
return sentimentVal
run()
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .