Hi,
I am newbie in the python, I am stuck into a small problem.

Me and my friend are working on the gedit based Twitter plugin.
http://code.google.com/p/gedit-twitter-plugin/

Now I want to add the tiny URL thing into this. I am using the bitly
API for this.
Its is already available in the python bitly.py
http://code.google.com/p/python-bitly/

now i want to use this bitly.py into the main file ( importing the
bitly.py to the twitter_gedit.py) .

One thing more, bitly.py uses the django.utils so you can download
that from http://www.djangoproject.com/download/

Thanks. its open
#!/usr/bin/python2.4
#
# Copyright 2009 Empeeric LTD. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.utils import simplejson
import urllib,urllib2
import urlparse
import string

BITLY_BASE_URL = "http://api.bit.ly/";
BITLY_API_VERSION = "2.0.1"

VERBS_PARAM = { 
         'shorten':'longUrl',               
         'expand':'shortUrl', 
         'info':'shortUrl',
         'stats':'shortUrl',
         'errors':'',
}

class BitlyError(Exception):
  '''Base class for bitly errors'''
  
  @property
  def message(self):
    '''Returns the first argument used to construct this error.'''
    return self.args[0]

class Api(object):
    """ API class for bit.ly """
    def __init__(self, login, apikey):
        self.login = vikashdhankar
        self.apikey = R_a55b050e658854f6846a01faa92f66ee 
        self._urllib = urllib2
        
    def shorten(self,longURL):
        """ 
            Takes either:
            A long URL string and returns shortened URL string
            Or a list of long URL strings and returnes a list of shortened URL strings.
        """
        if not isinstance(longURL, list):
            longURL = [longURL]
        
        for index,url in enumerate(longURL):
            if not url.startswith("http"):
                longURL[index] = "http://"; + url
            
        request = self._getURL("shorten",longURL)
        result = self._fetchUrl(request)
        json = simplejson.loads(result)
        self._CheckForError(json)
        
        res = []
        for item in json['results'].values():
            if item['shortKeywordUrl'] == "":
                res.append(item['shortUrl'])
            else:
                res.append(item['shortKeywordUrl'])
        
        if len(res) == 1:
            return res[0]
        else:
            return res

    def expand(self,shortURL):
        """ Given a bit.ly url or hash, return long source url """
        request = self._getURL("expand",shortURL)
        result = self._fetchUrl(request)
        json = simplejson.loads(result)
        self._CheckForError(json)
        return json['results'][string.split(shortURL, '/')[-1]]['longUrl']

    def info(self,shortURL):
        """ 
        Given a bit.ly url or hash, 
        return information about that page, 
        such as the long source url
        """
        request = self._getURL("info",shortURL)
        result = self._fetchUrl(request)
        json = simplejson.loads(result)
        self._CheckForError(json)
        return json['results'][string.split(shortURL, '/')[-1]]

    def stats(self,shortURL):
        """ Given a bit.ly url or hash, return traffic and referrer data.  """
        request = self._getURL("stats",shortURL)
        result = self._fetchUrl(request)
        json = simplejson.loads(result)
        self._CheckForError(json)
        return Stats.NewFromJsonDict(json['results'])

    def errors(self):
        """ Get a list of bit.ly API error codes. """
        request = self._getURL("errors","")
        result = self._fetchUrl(request)
        json = simplejson.loads(result)
        self._CheckForError(json)
        return json['results']
        
    def setUrllib(self, urllib):
        '''Override the default urllib implementation.
    
        Args:
          urllib: an instance that supports the same API as the urllib2 module
        '''
        self._urllib = urllib
    
    def _getURL(self,verb,paramVal): 
        if not isinstance(paramVal, list):
            paramVal = [paramVal]
              
        params = [
                  ('version',BITLY_API_VERSION),
                  ('format','json'),
                  ('login',self.login),
                  ('apiKey',self.apikey),
            ]
        
        verbParam = VERBS_PARAM[verb]   
        if verbParam:
            for val in paramVal:
                params.append(( verbParam,val ))
   
        encoded_params = urllib.urlencode(params)
        return "%s%s?%s" % (BITLY_BASE_URL,verb,encoded_params)
       
    def _fetchUrl(self,url):
        '''Fetch a URL
    
        Args:
          url: The URL to retrieve
    
        Returns:
          A string containing the body of the response.
        '''
    
        # Open and return the URL 
        url_data = self._urllib.urlopen(url).read()
        return url_data    

    def _CheckForError(self, data):
        """Raises a BitlyError if bitly returns an error message.
    
        Args:
          data: A python dict created from the bitly json response
        Raises:
          BitlyError wrapping the bitly error message if one exists.
        """
        # bitly errors are relatively unlikely, so it is faster
        # to check first, rather than try and catch the exception
        if 'ERROR' in data or data['statusCode'] == 'ERROR':
            raise BitlyError, data['errorMessage']
        for key in data['results']:
            if type(data['results']) is dict and type(data['results'][key]) is dict:
                if 'statusCode' in data['results'][key] and data['results'][key]['statusCode'] == 'ERROR':
                    raise BitlyError, data['results'][key]['errorMessage'] 
       
class Stats(object):
    '''A class representing the Statistics returned by the bitly api.
    
    The Stats structure exposes the following properties:
    status.user_clicks # read only
    status.clicks # read only
    '''
    
    def __init__(self,user_clicks=None,total_clicks=None):
        self.user_clicks = user_clicks
        self.total_clicks = total_clicks
    
    @staticmethod
    def NewFromJsonDict(data):
        '''Create a new instance based on a JSON dict.
    
        Args:
          data: A JSON dict, as converted from the JSON in the bitly API
        Returns:
          A bitly.Stats instance
        '''
        return Stats(user_clicks=data.get('userClicks', None),
                      total_clicks=data.get('clicks', None))

        
if __name__ == '__main__':
    testURL1="www.yahoo.com"
    testURL2="www.cnn.com"
    a=Api(login="pythonbitly",apikey="R_06871db6b7fd31a4242709acaf1b6648")
    short=a.shorten(testURL1)    
    print "Short URL = %s" % short
    urlList=[testURL1,testURL2]
    shortList=a.shorten(urlList)
    print "Short URL list = %s" % shortList
    long=a.expand(short)
    print "Expanded URL = %s" % long
    info=a.info(short)
    print "Info: %s" % info
    stats=a.stats(short)
    print "User clicks %s, total clicks: %s" % (stats.user_clicks,stats.total_clicks)
    errors=a.errors()
    print "Errors: %s" % errors
from gettext import gettext as _
import gettext
import gedit
import gtk
import gobject
import pickle
import pprint
import twitter
from bitly import Api

class TwitterPluginHelper(object):
    def __init__(self, window):
        self._window = window
       # self._plugin = plugin
        self._build_logpanel(window)
        
    def update_ui(self):
        # Called whenever the window has been updated (active tab
        # changed, etc.)
        pass
        
    def _build_logpanel(self,window):
        panel = self._window.get_bottom_panel()
        self.box = gtk.VBox(False,0)
        self.messageLabel = gtk.Label("What are you doing ?")
        self.box2 = gtk.HBox(False,0)
        self.tweetLabel= gtk.Label("Last Message:")
        self.lastTweet = gtk.Label("")
        self.box.pack_start(self.messageLabel, False, False, 0)
        self.box2.pack_start(self.tweetLabel,False,False,0)
        self.box2.pack_start(self.lastTweet,False,False,0)
        self.box.pack_start(self.box2, False, False, 0)
      #  self.box.pack_start(self.messageLabel, True, True, 0)
        self.box1 = gtk.HBox(False, 0)
        self.tweet = gtk.Entry()
        self.tweet.set_max_length(140)
        self.box1.pack_start(self.tweet, True, True, 0)
        self.button = gtk.Button("Tweet")
        self.button.connect("clicked", self._tweet, None)
        self.box1.pack_start(self.button, False, True, 0)
        image = gtk.Image()
        self.box.pack_start(self.box1, True, True, 0)
        panel.add_item(self.box, "Twitter", image)
        self.box.show_all()        
        self.box1.show_all()
    
    def deactivate(self):
        pannel = self._window.get_bottom_panel()
        pannel.remove_item(self.box) 
    
    def _tweet(self,widget,info):
        message = self.tweet.get_text()
        pkl_file = open('.gnome2/gedit/plugins/data.pkl', 'rb')
        data = pickle.load(pkl_file)
        pkl_file.close()
        username=data["username"]
        password=data["password"]
        api = twitter.Api(username,password)
        status = api.PostUpdate(message)
        self.tweet.set_text('')
        self.lastTweet.set_text(message)
      
        
class TwitterPlugin(gedit.Plugin):
    WINDOW_DATA_KEY = "GeditPluginWindowData"
    
    def __init__(self):
        gedit.Plugin.__init__(self)

    def activate(self, window):
        helper = TwitterPluginHelper(window)
        window.set_data(self.WINDOW_DATA_KEY, helper)	
  	
    def deactivate(self, window):
        window.get_data(self.WINDOW_DATA_KEY).deactivate()
        window.set_data(self.WINDOW_DATA_KEY, None)


    def update_ui(self, window):
        window.get_data(self.WINDOW_DATA_KEY).update_ui()
        
        
    def is_configurable(self):
        return True

    def create_configure_dialog(self):
        pkl_file = open('.gnome2/gedit/plugins/data.pkl', 'rb')
        data = pickle.load(pkl_file)
        pkl_file.close()
        buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        dialog = gtk.Dialog("Twitter Plugin Configuration", None,0,buttons)
        usernameLabel = gtk.Label("Username")
        self.nameEntry = gtk.Entry()
        self.nameEntry.set_max_length(50)
        self.nameEntry.set_text(data["username"])
        pwLabel = gtk.Label("Password")
        self.pwEntry = gtk.Entry()
        self.pwEntry.set_max_length(50)
        self.pwEntry.set_text(data["password"])
        self.pwEntry.set_visibility(False)
        table = gtk.Table(2, 2, True)
        table.attach(usernameLabel, 0, 1, 0, 1)
        table.attach(self.nameEntry, 1, 2, 0, 1)
        table.attach(pwLabel, 0, 1, 1, 2)
        table.attach(self.pwEntry, 1, 2, 1, 2)
        self.savePassCheck = gtk.CheckButton("Remember Username/Password")
        self.label = gtk.Label("Enter your user name and password")
        self.label.set_selectable(True)
        self.label.set_line_wrap(True)
        dialog.vbox.pack_start(self.label, True, True, 10)
        dialog.vbox.pack_start(table, True, True, 0)
        dialog.vbox.pack_start(self.savePassCheck, True, True, 0)
        dialog.show_all()
        dialog.connect("response", self.on_response)
        self.dialog = dialog
        return dialog
        
    def on_response(self, dialog, response_id):
      if (response_id == gtk.RESPONSE_OK):
        #get the login details, etc:
        self.username = self.nameEntry.get_text()
        self.password = self.pwEntry.get_text()
        data = {'username': self.username, 'password': self.password}
        output = open('.gnome2/gedit/plugins/data.pkl', 'wb')
        pickle.dump(data, output)
        output.close()
        self.label.set_text("Saving Data...")
        
        

       
      elif (response_id == gtk.RESPONSE_CANCEL):
        self.dialog.destroy()
      else:
        self.label.set_text("How did that even happen?")

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to