April 29, 2012

#

send tweets from pythom , using python-twitter ...simple way ( 5 steps )

Today morning around 4am , when I was designing my codeleaf blog site I just thought of tweeting something interesting but I dont wanted to tweet from the twitter Page. Instead, I wanted to tweet from terminal where I was doing other programming stuffs... So I decided to write a python-script to Post a tweet from my Terminal .
So I googled about "tweet from python" and I came across python-twitter and I started following Wiki for implementing that thing .
Steps that need to be followed are as follows ::
1. Register an Application on Twitter Dev-Center
Set your application's "Access level : Read, write, and direct messages "
Otherwise you will get an error for "Access level : Read Only"(TwitterError: Read-only application cannot POST.)

2. Copy your
 consumer_key = 'consumer_key',
 consumer_secret = 'consumer_secret',
 access_token_key = 'access_token_key',
 access_token_secret = 'access_token_secret'
and paste on some TextEditor ,because we will use this later .
3. Installation ( Python-Twitter )

Install the dependencies:
If your python-version > python2.7.2 , then skip first two library and directly install the third-one(python-oauth2) .
Download the latest python-twitter library from:
Extract the source distribution and run:
 $ python setup.py build
   $ python setup.py install
 

4 . create a python file and write the below code on it .

  
 import twitter
 api  = twitter.Api()

 #tweet
 def tweet(tweet_status):
  status = api.PostUpdate(tweet_status)
  print "Posted successfully"
  print status.text

 # OAuth authentication
 api = twitter.Api(
  consumer_key = 'consumer_key',
  consumer_secret = 'consumer_secret',
  access_token_key = 'access_token_key',
  access_token_secret = 'access_token_secret'
 )

 tweet_status = raw_input("Tweet Status : ")
 tweet(tweet_status)

5. Thats it . Now run the script , and Terminal(command prompt) will ask you to enter your "Tweet" .

 $ python pytweet.py 
   Tweet Status : I love Python-Twitter .
   Posted successfully
 Tweet Status : I love Python-Twitter .

No comments:

Post a Comment

Follow Us @soratemplates