Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 26th, 2012  |  syntax: Python  |  size: 1.96 KB  |  hits: 36  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import locale
  2. import re
  3. import time
  4.  
  5. from util import hook, http
  6.  
  7.  
  8. locale.setlocale(locale.LC_ALL, '')
  9.  
  10. youtube_re = (r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)'
  11.               '([-_a-z0-9]+)', re.I)
  12.  
  13. base_url = 'http://gdata.youtube.com/feeds/api/'
  14. url = base_url + 'videos/%s?v=2&alt=jsonc'
  15. search_api_url = base_url + 'videos?v=2&alt=jsonc&max-results=1'
  16. video_url = "http://youtube.com/watch?v=%s"
  17.  
  18.  
  19. def get_video_description(vid_id):
  20.     j = http.get_json(url % vid_id)
  21.  
  22.     if j.get('error'):
  23.         return
  24.  
  25.     j = j['data']
  26.  
  27.     out = '\x02%s\x02' % j['title']
  28.  
  29.     if not j.get('duration'):
  30.         return out
  31.  
  32.     out += ' - length \x02'
  33.     length = j['duration']
  34.     if length / 3600:  # > 1 hour
  35.         out += '%dh ' % (length / 3600)
  36.     if length / 60:
  37.         out += '%dm ' % (length / 60 % 60)
  38.     out += "%ds\x02" % (length % 60)
  39.  
  40.     if 'rating' in j:
  41.         out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
  42.                 j['ratingCount'])
  43.  
  44.     if 'viewCount' in j:
  45.         out += ' - \x02%s\x02 views' % locale.format('%d',
  46.                                                      j['viewCount'], 1)
  47.  
  48.     upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
  49.     out += ' - \x02%s\x02 on \x02%s\x02' % (j['uploader'],
  50.                 time.strftime("%Y.%m.%d", upload_time))
  51.  
  52.     if 'contentRating' in j:
  53.         out += ' - \x034NSFW\x02'
  54.  
  55.     return out
  56.  
  57. @hook.regex(*youtube_re)
  58. def youtube_url(match):
  59.     return get_video_description(match.group(1))
  60.  
  61.  
  62. @hook.command('y')
  63. @hook.command
  64. def youtube(inp):
  65.     '.youtube <query> -- returns the first YouTube search result for <query>'
  66.  
  67.     j = http.get_json(search_api_url, q=inp)
  68.  
  69.     if 'error' in j:
  70.         return 'error performing search'
  71.  
  72.     if j['data']['totalItems'] == 0:
  73.         return 'no results found'
  74.  
  75.     vid_id = j['data']['items'][0]['id']
  76.  
  77.     return get_video_description(vid_id) + " - " + video_url % vid_id