youtube.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import re
  2. import urllib2
  3. from urlparse import urlparse, parse_qsl
  4. from xml.dom.minidom import parseString
  5. from datetime import datetime, timedelta
  6. from collections import OrderedDict
  7. from event import Event
  8. try:
  9. from modules.basemodule import BaseModule
  10. except ImportError:
  11. from basemodule import BaseModule
  12. class Youtube(BaseModule):
  13. def post_init(self):
  14. youtube = Event("__.youtubes__")
  15. youtube.define(msg_definition="youtube\.com[\S]+")
  16. youtube2 = Event("__.youtubeshort__")
  17. youtube2.define(msg_definition="(?<!=)youtu\.be[\S]+")
  18. youtube.subscribe(self)
  19. youtube2.subscribe(self)
  20. self.bot.register_event(youtube, self)
  21. self.bot.register_event(youtube2, self)
  22. self.bot.mem_store['youtube'] = OrderedDict()
  23. def print_video_title(self, event, url, video_tag):
  24. if event.user == self.bot.conf.getNick(self.bot.network): #ignore himself
  25. return
  26. if event.msg.startswith("Youtube:"):
  27. return
  28. try:
  29. response = urllib2.urlopen("https://gdata.youtube.com/feeds/api/videos/"+video_tag+"?v=2").read()
  30. except urllib2.HTTPError:
  31. return
  32. xml_response = parseString(response)
  33. duration = xml_response.getElementsByTagName('yt:duration')
  34. ulength = duration[0].getAttribute("seconds")
  35. alength = ulength.encode('ascii', 'ignore')
  36. length = str(timedelta(seconds=int(alength)))
  37. titletag = xml_response.getElementsByTagName('title')[0]
  38. video_title = titletag.childNodes[0].nodeValue
  39. self.say(event.channel, "Youtube: " + video_title + " ("+length+")")
  40. self.bot.mem_store['youtube'][video_title] = url
  41. def handle(self, event):
  42. # prevent bot from printing youtube information if a youtube link is in the channel topic (or elsewhere that isn't a message to a channel)
  43. if "PRIVMSG" not in event.line:
  44. return
  45. if event._type == "__.youtubes__":
  46. url = re.search("youtube.com[\S]+", event.line).group(0)
  47. try:
  48. get_dict = dict(parse_qsl(urlparse(url).query)) # create dictionary of strings, instead of of lists. this fails to handle if there are multiple values for a key in the GET
  49. video_tag = get_dict['v']
  50. except KeyError:
  51. return
  52. elif event._type == "__.youtubeshort__":
  53. url = re.search("youtu\.be[\S]+", event.line).group(0)
  54. if url:
  55. video_tag = url.split("/")[-1]
  56. else:
  57. return
  58. if url and video_tag.__len__() > 1:
  59. self.print_video_title(event, url, video_tag)