Youtube.print_video_title()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
c 1
b 1
f 0
dl 0
loc 28
rs 7.5384
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
12
try:
13
  import isodate
14
except ImportError:
15
  print "WARNING: youtube module now requires isodate (thanks, ISO8601)"
16
17
try:
18
  from modules.basemodule import BaseModule
19
except ImportError:
20
  from basemodule import BaseModule
21
class Youtube(BaseModule):
22
  def post_init(self):
23
    youtube = Event("__.youtubes__")
24
    youtube.define(msg_definition="youtube\.com[\S]+")
25
    youtube2 = Event("__.youtubeshort__")
26
    youtube2.define(msg_definition="(?<!=)youtu\.be[\S]+")
27
    youtube.subscribe(self)
28
    youtube2.subscribe(self)
29
30
    self.bot.register_event(youtube, self)
31
    self.bot.register_event(youtube2, self)
32
33
    self.bot.mem_store['youtube'] = OrderedDict()
34
35
36
    # for the new v3 google api >:(
37
    try: 
38
        from youtube_credentials import YoutubeCredentials as yc
39
    except ImportError:
40
        print "Warning: youtube module requires credentials in modules/youtube_credentials.py"
41
        class PhonyYc:
42
            api_key = "None"
43
        yc = PhonyYc()
44
45
    self.api_key = yc.api_key    
46
    self.api_url = "https://www.googleapis.com/youtube/v3/videos?id="
47
    #self.api_url = "https://www.googleapis.com/youtube/v3/videos?id=2k_9mXpNdgU&key=&part=snippet"
48
49
  def print_video_title(self, event, url, video_tag):
50
    if event.user == self.bot.conf.getNick(self.bot.network): #ignore himself
51
      return
52
    if event.msg.startswith("YouTube:"):
53
      return
54
    try:
55
      response = urllib2.urlopen(self.api_url+video_tag+"&key="+self.api_key+"&part=contentDetails,snippet").read()
56
    except urllib2.HTTPError:
57
      return
58
59
    try:
60
      jsonified = json.loads(response)["items"][0]
61
    except IndexError, e:
62
      self.bot.logger.write(logger.Logger.WARNING, "IndexError pulling youtube videos. Zero results for: ")
63
      self.bot.logger.write(logger.Logger.WARNING, url)
64
      return
65
66
    duration_string = jsonified['contentDetails']['duration']
67
    title = jsonified['snippet']['title']
68
69
    if isodate:
70
      duration = isodate.parse_duration(duration_string)
71
    else:
72
      duration = dict()
73
      duration['seconds'] = 00
74
75
    self.say(event.channel, "YouTube: \"" + title + "\" (" + time.strftime("%H:%M:%S", time.gmtime(duration.seconds)) + ")")
76
    return 
77
78
  def handle(self, event):
79
#   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)
80
    if "PRIVMSG" not in event.line:
81
      return
82
    if event._type == "__.youtubes__":
83
      url = re.search("youtube.com[\S]+", event.line).group(0)
84
      try:
85
        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
86
        video_tag = get_dict['v']
87
      except KeyError:
88
        return
89
    elif event._type == "__.youtubeshort__":
90
      url = re.search("youtu\.be[\S]+", event.line).group(0)
91
      if url: 
92
        video_tag = url.split("/")[-1]
93
        if "?" in video_tag:
94
          video_tag = video_tag.split("?")[0]
95
      else:
96
        return
97
    if url and video_tag.__len__() > 1:
98
      self.print_video_title(event, url, video_tag)
99