Sha256: d3d005b977168e9fa12e2210e446adac6720e9b6f00ded1ae685cd4e4f75c3d9

Contents?: true

Size: 1.61 KB

Versions: 3

Compression:

Stored size: 1.61 KB

Contents

require "forwardable"

module Boty
  class ScriptDSL
    INSTANCES = {}
    private_constant :INSTANCES
    class << self
      alias original_constructor new
    end

    attr_accessor :bot

    extend Forwardable
    def_delegators :bot, :desc, :respond, :name, :brain, :know_how, :im, :say,
      :match, :no_match, :no_respond, :no
    def_delegators :message, :user, :channel

    def self.new(bot)
      INSTANCES[bot] ||= original_constructor bot
    end

    def initialize(bot)
      @bot = bot
    end

    def message
      @bot.trigger_message
    end

    def message_from_me?
      message.from? @bot
    end

    def hear(*args, &block)
      match(*args, &block)
    end

    def command(*args, &block)
      respond(*args, &block)
    end

    def match_im(*args, &block)
      command(*args, &block)
    end

    def http
      @http ||= HTTP.new
    end
  end

  class HTTP
    [:get, :post, :put, :delete, :head, :patch, :options].each do |verb|
      define_method verb do |url, params = {}|
        response = connection verb, url, params
        handle_response response
      end
    end

    private

    def connection(verb, url, params)
      uri = URI url
      Faraday.new(url: "#{uri.scheme}://#{uri.host}") { |builder|
        builder.adapter(*Faraday.default_adapter)
      }.public_send(verb) { |req|
        req.url uri.path, params
      }
    end

    def handle_response(response)
      # TODO: use a response parser accordingly to the
      body = response.body
      if /application\/json/.match response.headers["Content-Type"]
        JSON.parse body
      else
        body
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
boty-0.0.17.1 lib/boty/script_dsl.rb
boty-0.0.17 lib/boty/script_dsl.rb
boty-0.0.16 lib/boty/script_dsl.rb