煤 - Note

Entries

14

Google 計算機で賢くなる chokan プラグイン

前に書いたのをちょっといじって公開。

google_calc.rb

require 'chokan/plugin_base'
require 'net/http'
require 'uri'

class GoogleCalc < Chokan::PluginBase
	def initialize(config, chokan)
		super
		@prefix = @config['prefix'] || 'c '
	end

	def on_privmsg(prefix, channel, message)
		case message
		when /^#{@prefix}(.+)$/i
			notice(channel, parse(Regexp.last_match[1]))
		end
	end

	private
	def parse(syntax)
		syntax.gsub!(/([\d.,_]+) *?hyde/) { ($1.to_i * 156).to_s + 'cm' }
		hyde = (syntax = syntax.sub(/hyde$/, 'cm')) ? true : false

		Net::HTTP.start('www.google.co.jp', 80) do |http|
			uri = "/search?q=#{URI.encode(syntax, /.*/n)}&oe=utf-8"
			log uri
			response = http.get(uri)
			log response.code.inspect
			if /<font size=\+1><b>(.+?)<\/b>/.match(response.body)
				result = Regexp.last_match[1].gsub(/<sup>/, '^').gsub(/<.*?>/, '').gsub(/&#215;/, '*')
				if hyde
					result.sub(/= (.+) cm$/) { '= ' + ($1.gsub(/ /, '').to_i / 156.0).to_s + ' hyde' }
				end
			else
				'ごっすんごっすん、分からないわ'
			end
		end
	end
end

config で prefix が指定出来ます。