Sha256: c0b28762bf4a40fb8345383d0c083024697830a08eb2bc273160f859018fc027

Contents?: true

Size: 1.94 KB

Versions: 3

Compression:

Stored size: 1.94 KB

Contents

module Boty
  class Bot
    include Boty::Eventable
    include Boty::MatchHandler
    include Boty::Logger
    include Slack

    attr_reader :id, :name, :brain

    def initialize(bot_info)
      Locale.reload
      @raw_info = bot_info
      @id       = bot_info["id"]
      @name     = bot_info["name"]

      @brain ||= {}

      on :message, &method(:message_handler)
      ScriptLoader.new(self).load
    end

    def say(message, api_parameters = {})
      channel = (trigger_message && trigger_message.channel) || "#general"
      options = { channel: channel }.merge api_parameters
      post_response = Slack.chat.post_message message, options
      logger.debug { "Post response: #{post_response}." }
    end

    def im(text, destiny: nil, to: nil, user_id: nil)
      destiny = User(user_id) || user_by_name(destiny, to)
      if destiny
        logger.debug do "Sending #{text} to #{destiny.name}." end
        Slack.chat.post_im destiny.id, text
      else
        logger.debug do "User not found, refusing to send im." end
      end
    end

    def know_how
      actions = Array(commands) + Array(listeners)
      actions.sort_by { |action| action.desc.command || "_" }
    end

    private

    def user_by_name(destiny, to)
      to ||= destiny
      if to
        Slack.users.by_name to
      else
        trigger_message.user
      end
    end

    def message_from_bot_itself?(data)
      data["user"] == id || data["user"] == name
    end

    def command?(data)
      return false if message_from_bot_itself? data

      if /(<@#{id}|#{name}>)/ =~ data["text"]
        true
      else
        false
      end
    end

    def message_handler(data)
      unless data["text"]
        return logger.debug do "Non text message, just ignoring." end
      end
      execute data
    end

    def execute(data)
      message = Message.new data
      if command?(data)
        execute_commands message
      else
        execute_matches message
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
boty-1.0.1 lib/boty/bot.rb
boty-1.0.0 lib/boty/bot.rb
boty-0.2.0 lib/boty/bot.rb