Skip to content

Instantly share code, notes, and snippets.

Created December 21, 2012 06:54
Show Gist options
  • Save anonymous/4351109 to your computer and use it in GitHub Desktop.
Save anonymous/4351109 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'uri'
require 'open-uri'
require 'net/http'
require 'nokogiri'
class Wikipedia < Citrus::Plugin
def initialize(*args)
super
@prefix = @config['prefix'] || '\? *?'
@keyword
end
def on_privmsg(prefix, channel, message)
return if !@config["channels"].nil? && !@config["channels"].include?(channel)
case message
when /^[\s]{0,}(.+)#{@prefix}$/i
parse(Regexp.last_match[1].gsub(/\s/,"_")).each {|m| notice(channel, m)}
end
end
private
def google(keyword)
shtml = Nokogiri::HTML(open(URI.escape("http://ja.wikipedia.org/w/index.php?title=特別%3A検索&search=#{keyword}")).read)
ret = shtml.search("ul.mw-search-results")
if !ret.nil?
url = ret.search("a").first.attributes['href']
address = "http://ja.wikipedia.org#{url}"
else
tit = shtml.at("#firstHeading").inner_text
address = URI.escape("http://ja.wikipedia.org/wiki/#{tit}")
end
html = Nokogiri::HTML(open(address).read)
[html,address]
rescue => e
puts "google => #{e}"
[nil,nil]
end
def parse(keyword)
address = URI.escape("http://ja.wikipedia.org/wiki/#{keyword}")
begin
html = Nokogiri::HTML(open(address).read)
rescue
html, address = google(keyword)
end
begin
m = html.search("p").first.inner_text[0..300]
m << "\n"
#open("http://tinyurl.com/api-create.php?url=#{address}") do |f|
# m << f.read()
#end
m << URI.short_uri(address)
rescue => e
p e.inspect
'べ、別にあんたのために調べた訳じゃないんだからね!'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment