Good morning and welcome back to my weekend project. Meanwhile it is Sunday and this is the second part on learning python by writing a small script (bot) that is able to read from and write to a twitter feed. As described in my previous blog entry, we are now able to do read / write interaction with twitter.
The plan for today is experiment with read / write access to files and combine the knowledge to read entries from a text file and post the content to a twitter feed. The relevant section of the python tutorials is 7.2. Reading and Writing Files.
Lets start with reading some content from a plain text file. Create a file and write some statements in different lines. For that you can use either vim directly in a terminal or a gui based editor like gedit.
then press “a” to insert text. When finished press “Ctrl C” to close inserting mode and “:wq” to write/store your changes and quit vim.
Now we want to read the content of the file using python. So open a terminal and start your python interpreter in interactive mode. Use the following commands to open the file and read the whole content of the file to a variable:
file = open("yourTextfile", "r") content = file.read() print content Hello World this is a line that will be a tweet at sometime and here we have the latest news
Please notice two things:
- executing file.read() again will return an empty string (”), because the file pointer is at the end of the file already
- print formates the output in the same way it was stored in the file. If you output the result directly without storing it to a variable like:
file = open("yourTextfile", "r") file.read() 'Hello World\n\nthis is a line that will be a tweet at sometime\n\nand here we have the latest news'
the whole content is printed in a single line and you see special characters like line break in their encodings: line break is “\n” and the German umlauts e.g. Ä is encoded by “\xc3\x84”.
After reading the files’ content you should close the file handler with the file.close() command.
Putting the puzzle pieces together
Now we are able to combine our knowledge. First we write a script that expects the tweet it publishes on twitter via command line argument. Create a file twitterbot.py and fill in the following source:
#! /usr/bin/env python # -*- coding: UTF-8 -*- """ the first version of our twitterbot """ import twitter def getAuthClient(): return twitter.Api(consumer_key='enter your consumer key', consumer_secret='enter your consumer secret', access_token_key='enter your access token', access_token_secret='enter your access token secret') if __name__ == "__main__": import sys client = getAuthClient() status = client.PostUpdate(sys.argv)
Now you can save the script and close your editor. Further more you have to make the script executable. That is done by “chmod +x twitterbot.py”. And now, the first test whether it runs as it should. Switch to a terminal and enter:
./twitterbot.py "Hello World, that's my first tweet via my self-written python script"
You should see the new tweet appearing in your time line, and we are almost done – the only thing left is the linkage to the tweets in our text file. So let us extend our script from above so it can handle files:
#! /usr/bin/env python # -*- coding: UTF-8 -*- """ the first version of our twitterbot """ import twitter def getAuthClient(): return twitter.Api(consumer_key='enter your consumer key', consumer_secret='enter your consumer secret', access_token_key='enter your access token', access_token_secret='enter your access token secret') if __name__ == "__main__": import sys import random client = getAuthClient() # open file in read mode if len(sys.argv) > 1: file = open(sys.argv, "r") else: file = open("./defaultTextFile", "r") content= # read file line by line and store lines to a list for line in file: content.append(line) # select a tweet at random and cut of the \n in the end tweet = random.choice(content)[:-1] status = client.PostUpdate(tweet)
This script is called from terminal by “./twitterbot.py [optionalTextfile]”. You can provide as first parameter an optional text file containing a bunch of tweets. The script then randomly selects one entry from your file and posts it on twitter.
We are done 🙂 Have fun with your script and I you have any suggestion or opinion leave me a comment 😉
- the Python tutorial: http://docs.python.org/tutorial/index.html
- python twitter wrapper documentation: https://code.google.com/p/python-twitter/ is also available when you have the package installed by typing “pydoc twitter” in a terminal
regarding the authentication methods those projects maybe not up-to-date anymore !