Archive

Posts Tagged ‘PYTHON’

Shorten URLs using goo.gl and Python

October 1st, 2010 4 comments

As we all know it, Google has its own URL shortening service called goo.gl. Google’s URL shortener still doesn’t have an official API and it doesn’t offer all the features that are available at bit.ly, but it works well.

Here is a Python script to shorten URL using goo.gl.

#!/usr/bin/python
# use Google's http://goo.gl/ URL shortener
# requires urllib, urllib2, re, simplejson
def shorten(url):
  try:
    from re import match
    from urllib2 import urlopen, Request, HTTPError
    from urllib import quote
    from simplejson import loads
  except ImportError, e:
    raise Exception('Required module missing: %s' % e.args[0])
  if not match('http://',url):
    raise Exception('URL must start with "http://"')
  try:
    urlopen(Request('http://goo.gl/api/url','url=%s'%quote(url),{'User-Agent':'toolbar'}))
  except HTTPError, e:
    j = loads(e.read())
    if 'short_url' not in j:
      try:
        from pprint import pformat
        j = pformat(j)
      except ImportError:
        j = j.__dict__
      raise Exception('Didn\'t get a correct-looking response. How\'s it look to you?\n\n%s'%j)
    return j['short_url']
  raise Exception('Unknown eror forming short URL.')
 
if __name__ == '__main__':
  from sys import argv
  print shorten(argv[1])

Usage:

$ python g.py http://segfault.in
http://goo.gl/Uh5h

Update:
Expand URLs

def expand(url):
  try:
    import urllib
  except ImportError, e:
    raise Exception('Required module missing: %s' % e.args[0])
 
  f = urllib.urlopen(url)
  return f.geturl()
Categories: PYTHON Tags: , ,

Catch Invisible Friends On GTalk The Python Way

July 16th, 2010 4 comments

Google-TalkEver wanted to know that someone is really offline or has just gone invisible in GTalk? Here is a small trick. The bellow peace of python code get the list of invisible users from your GTalk buddy list. It uses XMPP module for python. You can install this module in Ubuntu/Debian via apt. It also requires python dns module.

$ sudo aptitude install python-xmpp python-dnspython

Now here is our script. Open your favorite text editor and save the code as ‘gchat.py’. Dont forget to fill your gtalk username and password in the script.

import xmpp
 
# Google Talk constants
FROM_GMAIL_ID = "username@gmail.com"
GMAIL_PASS = "secret"
GTALK_SERVER = "gmail.com"
 
jid=xmpp.protocol.JID(FROM_GMAIL_ID)
C=xmpp.Client(jid.getDomain(),debug=[])
 
if not C.connect((GTALK_SERVER,5222)):
    raise IOError('Can not connect to server.')
if not C.auth(jid.getNode(),GMAIL_PASS):
    raise IOError('Can not auth with server.')
 
C.sendInitPresence(requestRoster=1)
 
def myPresenceHandler(con, event):
   if event.getType() == 'unavailable':
     print event.getFrom().getStripped()
 
C.RegisterHandler('presence', myPresenceHandler)
while C.Process(1):
  pass

Now simply run:

$ python gchat.py

So , Next time do not let anyone fool you , rather catch him Invisibly .

Categories: PYTHON Tags: , , , ,

Check Your IMAP Quota Using Python Imaplib

July 16th, 2010 No comments

pythonThe python-imaplib module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060.

Here’s a code sample that returns your gmail quota details.

import getpass, imaplib, re
 
p = re.compile('\d+')
 
IMAP_SERVER='imap.gmail.com'
IMAP_PORT=993
IMAP_USERNAME='username@gmail.com'
 
M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
M.login(IMAP_USERNAME, getpass.getpass())
quotaStr = M.getquotaroot("INBOX")[1][1][0]
r = p.findall(quotaStr)
if r == []:
  print "Unlimited Quota Account"
  r.append(0)
  r.append(0)
 
print 'Allotted = %f MB'%(float(r[1])/1024)
print 'Used = %f MB'%(float(r[0])/1024)
M.logout()

The script will ask your gmail password and the output will be something like this:

Allotted = 7476.760000 MB
Used = 961.390000 MB
Categories: PYTHON Tags: , , ,

Switch to our mobile site