Class: Cinch::Plugins::YouTube

Inherits:
Object
  • Object
show all
Includes:
Cinch::Plugin
Defined in:
lib/cinch/plugins/youtube.rb

Constant Summary collapse

YOUTUBE_VIDEO_REGEXP =

From Google's Closure Library, with slight modifications: closure-library.googlecode.com/svn/docs/closure_goog_ui_media_youtube.js.source.html

/https?:\/\/(?:[a-zA-Z]{2,3}\.)?(?:m\.)?(?:youtube\.com\/watch)(?:\?(?:[\w=-]+&(?:amp;)?)*v=([\w-]+)(?:&(?:amp;)?[\w=-]+)*)?(?:#[!]?(?:(?:(?:[\w=-]+&(?:amp;)?)*(?:v=([\w-]+))(?:&(?:amp;)?[\w=-]+)*)|(?:[\w=&-]+)))?[^\w-]?|https?:\/\/(?:[a-zA-Z]{2,3}\.)?(?:youtu\.be\/)([\w-]+)/i
YOUTUBE_API_VIDEO_URL =
"https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=%s&key=%s"

Instance Method Summary collapse

Instance Method Details

#listen_to_channel(m) ⇒ Object


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/cinch/plugins/youtube.rb', line 20

def listen_to_channel(m)
  return if is_channel_disabled?(m.channel)
  return unless m.message.match(YOUTUBE_VIDEO_REGEXP)
  video_ids = m.message.scan(YOUTUBE_VIDEO_REGEXP).flatten.reject(&:'nil?').uniq
  response = HTTParty.get(YOUTUBE_API_VIDEO_URL % [video_ids.join(','), config[:api_key]], headers: {'User-Agent' => "HTTParty/#{HTTParty::VERSION} #{RUBY_ENGINE}/#{RUBY_VERSION}"})
  raise StandardError, '%s - %s (%d)' % [response['error']['message'], video_ids.join(', '), response['error']['code']] if response['error']
  videos = response['items']

  videos.each {|video|
    m.reply "#{Format(:bold,'YouTube »')} #{Format(:purple,'%<title>s')} (%<length>s) · by %<uploader>s on %<uploaded>s · #{Format(:green,'☝%<likes>s')} #{Format(:red,'☟%<dislikes>s')} · %<views>s views" % {
      title: video['snippet']['title'],
      uploader: video['snippet']['channelTitle'],
      uploaded: Time.parse(video['snippet']['publishedAt']).strftime('%F'),
      length: seconds_to_time(ISO8601::Duration.new(video['contentDetails']['duration']).to_seconds),
      likes: commify_numbers(video['statistics']['likeCount'].to_i),
      dislikes: commify_numbers(video['statistics']['dislikeCount'].to_i),
      views: commify_numbers(video['statistics']['viewCount'].to_i)
    }
  }
rescue => e
  m.reply "#{Format(:bold,'YouTube »')} #{e.message}"
end