Python Twitter Bot

This is just a quick write up on the python weather twitter-bot we put together this week at the Naas-Sallins Coder Dojo. For this task we needed three things, a source for the weather data, a twitter account and a twitter api library for python.

We created a twitter account for the dojo @NaasCoderDojo and then followed the instructions here to register an application. We did this ahead of the session because it can take a couple of days. In order to write tweets you need to register your application for read-write and you need a mobile phone to complete the process. Once you get your application registered you will need the api token and secret as well as the access key and secret for your python application. You need not to share this information otherwise anyone can tweet as you.

 

Once you have these four bits of information you need a python twitter library to get started. We chose Tweepy. To install you can choose a number of methods. From a command window/terminal type

easy_install tweepy

or grab the zip file from github, unzip and then in the command window in the folder you put the files in type

python setup.py install

Once we have tweepy installed we need to check that our setting are working so we wrote a quick program to print out our tweets.

""" Program to Read tweets"""
import tweepy

#enter the corresponding information for your Twitter application:
CONSUMER_KEY = 'abc123 put your api consumer key here'
CONSUMER_SECRET = 'abc123 put you api consumer secret code here'
ACCESS_KEY = 'xyz123 put access token here'
ACCESS_SECRET = 'xyz123 put your access token secret here'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api =tweepy.API(auth)
#---now we can connect to twitter
for tweet in api.user_timeline():
    print(tweet.text)

This code imports the tweepy library, defines the variables needed (you need to place the ones you got on apps.twitter.com here) and then sets us up to connect to twitter. We based this code on the getting started examples in the tweepy documentation. The last two lines loop through our tweets and prints them out. If we wanted to send a tweet then we just need to change these last two lines to something like

tweet = "Hello World. Test Tweet using Tweepy and Python"
api.update_status(tweet)

The next step was to find source of weather data. We chose openweathermap.org as they offer free weather data to everyone. Their api page has some examples on how to get the weather data and we decided to use the JSON one. Python has a number of ways of interaction with the web and we picked one of the most commonly used ones, urllib2. Our initial code to get the data was as follows.

import urllib2

def getweather():
    """ call openweathermap api"""
    response = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=Naas')
    mydata = response.read()
    return mydata 

weather = getweather()
print weather

This code imports urllib2 and then defines our function to get the weather called getweather. Here we set response equal to our call to the open weather api (setting the town to Naas) and then say that the variable mydata will be equal to a read of that url. We return this variable and then print it. which gives something like

{“coord”:{“lon”:-6.67,”lat”:53.22},”sys”:{“message”:0.0042,”country”:”IE”,”sunrise”:1398057151,”sunset”:1398109082},”weather”:[{“id”:800,”main”:”Clear”,”description”:”Sky is Clear”,”icon”:”01d”}],”base”:”cmc stations”,”main”:{“temp”:286.29,”humidity”:81,”pressure”:1007,”temp_min”:286.15,”temp_max”:286.48},”wind”:{“speed”:4.63,”gust”:7.71,”deg”:82},”rain”:{“3h”:0},”clouds”:{“all”:0},”dt”:1398076686,”id”:2962334,”name”:”Naas”,”cod”:200}

This is our weather data in JSON format and even by looking at this you can see that elements such as wind speed and temp are present. To put this data in a tweet we need to parse the JSON data to extract the we want so we imported the python json library and started playing around with print statements to see what data we could extract

""" get the weather for Naas from openweathermap """
import urllib2
import json
def getweather():
    """ call openweathermap api"""
    response = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=Naas')
    mydata = response.read()
    return mydata

weather = getweather()
w = json.loads(weather)
print w['wind']['speed']
print w['main']['temp']

So the way that this JSON is structured is that there is a series of sections followed by some names and associated values. In our code above we set w to the result of using the json.loads method on our weather data. We can then extract individual parts of the data by referring to them by their name in the manner shown. Our next step was to compose our tweet which we did by building up a list of the bits we wanted and some words as appropriate.

""" get the weather for Naas from openweathermap """
import urllib2
import json
def getweather():
    """ call openweathermap api"""
    response = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=Naas')
    mydata = response.read()
    return mydata

weather = getweather()
w = json.loads(weather)
temp = -273 + int(w['main']['temp']) #--since temp is in kelvin
mylist = ['OpenWeather for', w['name'],'-',w['weather'][0]['description'],'Wind Speed',str(w['wind']['speed']),'Temp',str(temp),'degrees C']
outstring = " ".join(mylist)
print outstring

You will also notice that we had to adjust for the fact that the temp is in Kelvin to get degrees celsius.
At this stage all we had to do was put the two chunks of code together to have our python weather twitter bot.

""" Python Weather Twitter-Bot for @NaasCoderDojo using tweepy and openweathermap """
import tweepy
import urllib2
import json

#codes below are fake: enter details from your Twitter application
CONSUMER_KEY = 'asdadjakljdakljdakljdlklm'
CONSUMER_SECRET = 'dkjahdkhakdhakjdhkajhdkjahdkjahdkahdkhakdhajhdajbi'
ACCESS_KEY = 'ajsdhakhdkajhdkjahdkjahdkjhakjdhakjdhkajhdkajhdakh'
ACCESS_SECRET = 'djaghdhakhfkahfkjahfkjahfkhakfjhakjfhakfhkfah'

def getweather():
    """ call openweathermap api"""
    response = urllib2.urlopen('http://api.openweathermap.org/data/2.5/weather?q=Naas')
    mydata = response.read()
    return mydata

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

weather = getweather()
w = json.loads(weather)
temp = -273 + int(w['main']['temp']) #--since temp is in kelvin
mylist = ['OpenWeather for', w['name'],'-',w['weather'][0]['description'],'Wind Speed',str(w['wind']['speed']),'Temp',str(temp),'degrees C']
tweet = " ".join(mylist)

api.update_status(tweet)

Our Tweet

@NaasCoderDojo

Our aim here was to show the guys how they could put together some web technologies by using the examples provided by tweepy and openweathermap and adjusting them to their own needs. We hope to amend our code to take advantage of other freely available data such as International Space Station location in the next session. Hopefully you can follow the results on @NaasCoderDojo

edit: just noticed some formatting issues with code on iphone etc. looks fine on chrome/IE/Firefox will investigate

Advertisements

4 thoughts on “Python Twitter Bot

  1. Pingback: Raspberry PI, Python, Scratch and Minecraft | damian mooney

  2. can you tell me what i am doing wrong

    “”” Program to Read tweets”””
    import tweepy
    import urllib2
    import json

    #enter the corresponding information for your Twitter application:
    CONSUMER_KEY = ‘usftXMKnsTj1HYnpWZXcMzO8U’
    CONSUMER_SECRET = ‘Ux1LSnYVDJOOkjt6VD7fmLlWOL0PtYr9UW1qg3maH9nvXTHSst’
    ACCESS_KEY = ‘22938545-wr7H2wwhwQjjFlUym6LS3JOZPQ4KSy8BGn4eaWOwU’
    ACCESS_SECRET = ‘qyIgh7MbPUDEyaKZhmhVf8fE4Mu5Z5AUirDrPNl9MuEDD’

    def getweather():
    “”” call openweathermap api”””
    response = urllib2.urlopen(‘api.openweathermap.org/data/2.5/weather?q=Huntsville,us&APPID=9593fc0e2307ea6d6f354dc8db079ee6’)
    mydata = response.read()
    return mydata

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    api = tweepy.API(auth)

    weather = getweather()
    w = json.loads(weather)
    temp = -273 + int(w[‘main’][‘temp’]) #–since temp is in kelvin
    mylist = [‘OpenWeather for’, w[‘name’],’-‘,w[‘weather’][0][‘description’],’Wind Speed’,str(w[‘wind’][‘speed’]),’Temp’,str(temp),’degrees C’]
    tweet = ” “.join(mylist)

    api.update_status(tweet)

  3. Pingback: Project #18 – OpenWeatherMap | Ben's Pi

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