Sha256: 8915d5281a1ac05d6ce54a9f8c8cbd6c47f6e19fe3a5f4bb6f96cb8dfd530a86

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

require "lita"

module Lita
  module Handlers
    class Stocks < Handler
      route %r{^stock ([\w .-_]+)$}i, :stock_info, command: true, help: {
        "stock <symbol>" => "Returns stock price information about the provided stock symbol."
      }



      def stock_info(response)
        symbol = response.matches[0][0]
        data = get_stock_data(symbol)

        response.reply format_response(data)

      rescue Exception => e
        Lita.logger.error("Stock information error: #{e.message}")
        response.reply "Sorry, but there was a problem retrieving stock information."
      end

      private 


      def get_stock_data(symbol)
        resp = http.get("https://www.google.com/finance/info?infotype=infoquoteall&q=#{symbol}")
        raise 'RequestFail' unless resp.status == 200
        MultiJson.load(resp.body.gsub(/\/\//, ''))[0]
      end

      def format_response(data)
        line = []
        line << "#{data['name']} (#{data['e']}:#{data['t']})"
        line << "#{data['l']} (#{data['c']}, #{data['cp']}%)"
        line << "52week high/low: (#{data['hi52']}/#{data['lo52']})"

        # don't include these sections if they don't exist
        line << "MktCap: #{data['mc']}" unless data['mc'].empty?
        line << "P/E: #{data['pe']}" unless data['pe'].empty?

        line.join ' - '
      end


    end

    Lita.register_handler(Stocks)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lita-stocks-0.0.4 lib/lita/handlers/stocks.rb