0 Replies - 25449 Views - Last Post: 19 January 2010 - 05:44 PM Rate Topic: -----

#1 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Using the Python Twitter API

Posted 19 January 2010 - 05:44 PM

This tutorial will explain how to write a basic twitter client using the Python Twitter API. Firstly, the API can be downloaded from here. After installing, you can import the twitter module in Python and start using the API.

The first thing that needs to be done is to create an Api object. This is the object that provides all the functions for interacting with twitter.
import twitter
api = twitter.Api(username="insert twitter username here", password="insert twitter account password here")


We now have an api object that we can use to interact with Twitter in various ways.

Posting a Tweet
To post a tweet from the Python API, the api.PostUpdate function is used.
tweet = api.PostUpdate("Tweeting from Python!!!")
# tweet now contains the tweet we just posted. We can print it out like this:
print tweet.GetUser().GetScreenName(), ":", tweet.GetText()
# This should result in output similar to username : Tweeting from Python!!!



Getting tweets
The Python Twitter API allows you to get tweets in all the normal ways allowed by the Twitter website. You can view your friends timeline, tweets of a user, the public timeline, or all replies to you.
To get tweets from the public timeline, the api.GetPublicTimeline().
ptimeline = api.GetPublicTimeline()
# ptimeline is a list of tweet objects. We can print them out just like when posting a tweet.
for tweet in ptimeline:
    print tweet.GetUser().GetScreenName(), ":", tweet.GetText()


To get tweets from your friends, use api.GetFriendsTimeline(). You can then use similar code to output the tweets.
To get the tweets of a user, use api.GetUserTimeline.
tweets = api.GetUserTimeline("programble")
for tweet in tweets:
    print tweet.GetUser().GetScreenName(), ":", tweet.GetText()


api.GetUserTimeline takes a username as a parameter and returns the tweets of that user.
To retrieve all replies to you, use api.GetReplies() and similar code.

Getting Followers and Following
To get a list of users who are following you, use the following code.
followers = api.GetFollowers()
# followers is a list of users, like the user object returned by tweet.GetUser()
for user in followers:
    print user.GetScreenName()


This will print out the screen name of everyone following you.
Similarly, you can get a list of all people you are following using api.GetFriends().


And that concludes this tutorial. For more information on the Twitter API, visit http://code.google.c...python-twitter/ or http://apiwiki.twitter.com/.

Is This A Good Question/Topic? 2
  • +

Page 1 of 1