Programming a twitter-bot using python – Part 2/2

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.

vim testfile

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:

  1. executing file.read() again will return an empty string (”), because the file pointer is at the end of the file already
  2. 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[1])

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[1], "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 😉

Further reading:

similar projects:

regarding the authentication methods those projects maybe not up-to-date anymore !

Advertisements

One thought on “Programming a twitter-bot using python – Part 2/2

  1. Yes, as I said before, I like to read your threads. Starting with the warm welcome text in the beginning and the friendly invitation to continue to work at the end… nice, very nice.
    One idea= somehow I am reminded by your style of dealing with your readers to that man who was giving instructions “How to paint” on tv. His name was Bob Ross. Tipycally for Bob Ross: “I am certainly glad to see you” – He always starts his courses with those words. a warm welcome. That is what i found in your postings, a warm welcome for your readers.
    http://www.br-online.de/br-alpha/joy-of-painting/index.xml

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