Skip to content

Instantly share code, notes, and snippets.

@mdusher
Created January 21, 2015 04:15
Show Gist options
  • Save mdusher/7314d3f324f374b0ad5e to your computer and use it in GitHub Desktop.
Save mdusher/7314d3f324f374b0ad5e to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'cinch'
require 'open-uri'
require 'nokogiri'
require 'cgi'
module Cinch::Plugins
class YoURLS
include Cinch::Plugin
match(/.*?(http:|https:)/i,method: :urlshortener)
def initialize(*)
super
@yourls = { host: config[:host], secret: config[:secret] }
end
# url shortener
def urlshortener(m)
debug "Triggered by #{m.user.name}"
msg = m.message
urls = URI.extract(msg, ["http","https"])
if !urls.empty?
short_url = yourls(urls[0])
noko = Nokogiri::HTML(open(urls[0]), nil, "UTF-8")
case urls[0]
when /[^\s]*?youtube\.com[^\s]*/i
title = noko.title.strip.split("\n").first
url_extra = " - #{title}"
when /[^\s]*?youtu\.be[^\s]*/i
title = noko.title.strip.split("\n").first
url_extra = " - #{title}"
when /[^\s]*?twitter\.com\/(.*)\/(status|statuses)\/.*/i
user = $1
tweet = noko.at_css("div.js-original-tweet p.js-tweet-text").text.gsub(/\n/,' ')
url_extra = " - @%s: %s" % [user, tweet]
else
url_extra = ""
end
debug "ShortURL: %s Extra: %s Original: %s Length: %s" % [short_url, url_extra, urls[0], urls[0].length]
if (!short_url.empty? && urls[0].length > 60)
m.reply "%s %s" % [short_url, url_extra]
end
end
end
# yourls shortener
def yourls(query)
url = "%s/yourls-api.php?signature=%s&action=shorturl&url=%s" % [@yourls[:host],@yourls[:secret],query]
res = Nokogiri::XML(open(url))
shorturl = res.at_css('shorturl').text rescue @yourls_host+res.at_css('keyword').text
return shorturl
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment