youtube.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import re
  2. import urllib2
  3. import json
  4. from urlparse import urlparse, parse_qsl
  5. from xml.dom.minidom import parseString
  6. from datetime import datetime, timedelta
  7. from collections import OrderedDict
  8. import time
  9. import logger
  10. from event import Event
  11. try:
  12. import isodate
  13. except ImportError:
  14. print "WARNING: youtube module now requires isodate (thanks, ISO8601)"
  15. try:
  16. from modules.basemodule import BaseModule
  17. except ImportError:
  18. from basemodule import BaseModule
  19. class Youtube(BaseModule):
  20. def post_init(self):
  21. youtube = Event("__.youtubes__")
  22. youtube.define(msg_definition="youtube\.com[\S]+")
  23. youtube2 = Event("__.youtubeshort__")
  24. youtube2.define(msg_definition="(?<!=)youtu\.be[\S]+")
  25. youtube.subscribe(self)
  26. youtube2.subscribe(self)
  27. self.bot.register_event(youtube, self)
  28. self.bot.register_event(youtube2, self)
  29. self.bot.mem_store['youtube'] = OrderedDict()
  30. # for the new v3 google api >:(
  31. self.api_key = "AIzaSyDwzB3Sf_E-7VyKZYWXP9DjjlnPBs5kSfc"
  32. self.api_url = "https://www.googleapis.com/youtube/v3/videos?id="
  33. #self.api_url = "https://www.googleapis.com/youtube/v3/videos?id=2k_9mXpNdgU&key=&part=snippet"
  34. def print_video_title(self, event, url, video_tag):
  35. if event.user == self.bot.conf.getNick(self.bot.network): #ignore himself
  36. return
  37. if event.msg.startswith("YouTube:"):
  38. return
  39. try:
  40. response = urllib2.urlopen(self.api_url+video_tag+"&key="+self.api_key+"&part=contentDetails,snippet").read()
  41. except urllib2.HTTPError:
  42. return
  43. try:
  44. jsonified = json.loads(response)["items"][0]
  45. except IndexError, e:
  46. self.bot.logger.write(logger.Logger.WARNING, "IndexError pulling youtube videos. Zero results for: ")
  47. self.bot.logger.write(logger.Logger.WARNING, url)
  48. return
  49. duration_string = jsonified['contentDetails']['duration']
  50. title = jsonified['snippet']['title']
  51. if isodate:
  52. duration = isodate.parse_duration(duration_string)
  53. else:
  54. duration = dict()
  55. duration['seconds'] = 00
  56. self.say(event.channel, "YouTube: \"" + title + "\" (" + time.strftime("%H:%M:%S", time.gmtime(duration.seconds)) + ")")
  57. return
  58. def handle(self, event):
  59. # 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)
  60. if "PRIVMSG" not in event.line:
  61. return
  62. if event._type == "__.youtubes__":
  63. url = re.search("youtube.com[\S]+", event.line).group(0)
  64. try:
  65. 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
  66. video_tag = get_dict['v']
  67. except KeyError:
  68. return
  69. elif event._type == "__.youtubeshort__":
  70. url = re.search("youtu\.be[\S]+", event.line).group(0)
  71. if url:
  72. video_tag = url.split("/")[-1]
  73. if "?" in video_tag:
  74. video_tag = video_tag.split("?")[0]
  75. else:
  76. return
  77. if url and video_tag.__len__() > 1:
  78. self.print_video_title(event, url, video_tag)