Saturday, April 17, 2010

Script to update your STATUS of various social networking websites (facebook,twitter,google buzz) all at once

You might be aware of the site ping.fm. This site provides support to updating to various social networking sites by just updating at one place.

So, just sign up to that service and you can sync all your posts..

But, when I started using this site, I felt even logging into the site and then posting is also a long process so decided of using the ping.fm API to write a script in python to update my statuses..

This post can also act as a example on how to use REST via HTTP using python..

First of all, I looked at the documentation of the API:-

user.post

Posts a message to the user’s Ping.fm services.

URL: http://api.ping.fm/v1/user.post
Parameters:
  • api_key  – Your developer's API key
  • user_app_key – User’s application key
  • post_method – Posting method.  Either "default", "blog", "microblog" or "status."  Please refer to the section of this documentation that covers service method limitations.
  • body – Message body
Optional parameters:

  • title – Title of the posted message.  This will only appear if the specified service supports a title field.  Otherwise, it will be discarded.  Title is required for "blog" post method.
  • service – A single service to post to.  This used to support multiple services separated by a comma.  Posting to multiple services has been deprecated as of June 2008.  Posting to a single service is still functional.
  • location The user's current location.
  • tags comma-separated list of tag words to include with the post.  i.e. "tag1,tag2"
  • mood string literal mood.  i.e. "happy"
  • media – base64 encoded media data.
  • encoding – Set to "base64" to have the API decode before posting.  Useful when posting unicode or non URL encoded data.  If set, "title", "body", "location", "tags" and "mood" parameters are expected to be base64 encoded.
  • exclude comma separated values of service IDs (IDs returned from user.services, user.triggers, user.latest and system.services) to exclude from the post. 
  • debug – Set this value to "1" to avoid posting test data. 
  • checksum – Set this variable to pass a data checksum to confirm that the posted data reaches the API server. Please read the section titled "Payload Checksums" above.
  • media_checksum –Set this variable to compare an MD5 checksum of image data being supplied with the post update.  Please read the subsection titled "Media Checksums" under the "Posting Media" section above.

As it was written that it uses REST, doing it in python is very easy.. You just have to use urllib to do a POST to the URL  http://api.ping.fm/v1/user.post

The first group of parameters I have shown are the required parameters which cannot be ignored.. Looking at the DOC, there is also one more optional parameter "debug" which is useful..

Here is how I made the script..
  • Get the APIKEY and USERKEY from the website
  • Prepare the data_to_post (Refer to the FULL DOC on what you can send..)
  • Encode it
  • Send the request  using urllib

Usage for the script:-

$./statusUpdater.py "This is a status update"

to update status to all your acounts

$./statusUpdater.py facebook "This is an update only to facebook"

to update status of only facebook...


$./statusUpdater.py twitter "This updates twitter"


#!/usr/bin/python

__author__ = " Abhijeet Rastogi http://www.google.com/profiles/abhijeet.1989"

from xml.etree import ElementTree
import urllib,urllib2
import sys

APIURL = 'http://api.ping.fm/v1/'

#EDIT THE NEXT 2 LINES ACCORDING TO YOUR ACCOUNT
APIKEY = 'your key' #Get this from http://ping.fm/developers/
USERKEY = "your key" #get this from http://ping.fm/key
#######################################################

#degug = 1 just dumps the XML...
debug = 0

def StatusUpdate(msg = None, service = None):
    global debug
    print "Status message to be updated: "+msg
    if service is not None: print "Service to update: "+service
    data_to_post = {'api_key':APIKEY,'user_app_key':USERKEY,'post_method':'default','body': msg,'debug': debug}
    
    #If service is provided in the command line parameter, add that service in the data_to_post too...
    if service is not None: data_to_post['service'] = service        
    
    #Encoding the data to send...
    data_to_post = urllib.urlencode(data_to_post)    
    req = urllib2.Request(APIURL + 'user.post', data_to_post)
    
    try:
        response_page = urllib2.urlopen(req)
        #We get the response in XML
        responseXML = response_page.read()
        #Parsinf the XML
        result = ElementTree.XML(responseXML)
        if result.attrib is not None:
            if result.attrib['status'] == 'OK':
                print 'Your message has posted successfully!!!';
            else:
                print 'Error: ' + result[2].text
                if debug: print responseXML
    #Exception is handled
    except urllib2.URLError, e:
        if hasattr(e, 'reason'):
            print 'Couldnt connect to server.'
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print 'Error code: ', e.code

if __name__ == '__main__':
    if (len(sys.argv) == 2):
        StatusUpdate(sys.argv[1],None)
    else:
        StatusUpdate(sys.argv[2],sys.argv[1])

6 comments:

  1. got the api key and user key.... but terminal doen't identify your code as python script..... dunno y??!!!

    ReplyDelete
  2. ok...ok... needed to use chmod... now its working...gr8

    ReplyDelete
  3. This script works fine but if it can be modified to update status at a particular time.... For eg...
    ./statusupdate facebook 12:00pm "Wake up.." Then at that time it should post wake up on all my accounts in the 24 hour time frame....
    Thanks

    ReplyDelete
  4. Hey.. I can easily implement in script.
    But, you have a simple work around..

    To update status after 10 seconds.. do

    $for i in 1:; do sleep 10; ./statusUpdater.py facebook "Update after 10 sec minute"; done

    ReplyDelete
  5. thnaks... for ur fast reply..

    ReplyDelete
  6. Hi, well be sensible, well-all described

    ReplyDelete