class Ruboty::Url::Actions::Title

Ruboty::Url::Actions::Title

Public Instance Methods

call() click to toggle source
# File lib/ruboty/url/actions/title.rb, line 8
def call
  url = message[0]
  attachment = {
    color: '#E2E2E2',
    title_link: url,
  }
  open(url) do |f|
    html = Nokogiri::HTML(f)
    title = html.xpath('/html/head/title').text

    # guard slack_rtm
    return message.reply(title) unless Ruboty.const_defined? 'Adapters::SlackRTM'

    # optional infos
    og_title = html.xpath('/html/head/meta[@property="og:title"]/@content').first
    attachment[:title] = og_title.present? ? og_title.text : title
    og_site_name = html.xpath('/html/head/meta[@property="og:site_name"]/@content').first
    attachment[:author_name] = og_site_name.text if og_site_name.present?
    favicon_url = html.xpath('/html/head/link[@rel="icon"]/@href').first
    attachment[:author_icon] = favicon_url.text if favicon_url.present?
    og_description = html.xpath('/html/head/meta[@property="og:description"]/@content').first
    attachment[:text] = og_description.text if og_description.present?
    og_image = html.xpath('/html/head/meta[@property="og:image"]/@content').first
    attachment[:thumb_url] = og_image.text if og_image.present?
  end
  message.reply(nil, attachments: [attachment]) if attachment[:title].present?
end