class Beeline::Bot

Constants

BASE_COOLDOWN
MAX_COOLDOWN
MIN_COOLDOWN

Attributes

prefix[R]

Public Instance Methods

command(name, options = {}) click to toggle source
# File lib/beeline/bot.rb, line 5
def command name, options = {}, &block
  commands[name] = {options: options, block: block}
end
message(pattern, options = {}) click to toggle source
# File lib/beeline/bot.rb, line 9
def message pattern, options = {}, &block
  messages[pattern] = {options: options, block: block}
end
process_chat_message(payload) click to toggle source
# File lib/beeline/bot.rb, line 21
def process_chat_message(payload)
  from = payload['from']
  
  cooldown(from)
  
  conversation_id = payload['conversation_id']
  content = payload['content'].to_s
  command_key = content.split(' ').first.split(prefix).last.to_sym
  reply = if commands.keys.include? command_key
    args = (content.split(' ') - ["#{prefix}#{command_key}"]).join(' ')
    args = args.empty? ? nil : args
    
    commands[command_key][:block].call(args, from, conversation_id)
  elsif (matching_messages = messages.select{|k| Regexp.new(k).match?(content)}).any?
    message = matching_messages.values.first # match in order of declaration
    
    message[:block].call(content, from, conversation_id)
  end
  
  if !!reply
    chat_message(conversation_id, from, reply)
  end
end
process_friendship_requested(payload) click to toggle source
# File lib/beeline/bot.rb, line 45
def process_friendship_requested(payload)
  return unless friendships[:accept] == 'auto'
  
  accept_pending_friend_requests
end
process_status(payload) click to toggle source
# File lib/beeline/bot.rb, line 13
def process_status(payload)
  if payload['authenticated']
    puts 'Got acknowledge authenticated.'
  else
    abort 'Unable to authenticate.'
  end
end

Private Instance Methods

cooldown(key) click to toggle source

Exponential backoff for key. This will apply a rate-limit for each key that depends on how often the key is used.

@private

# File lib/beeline/bot.rb, line 59
def cooldown(key)
  @cooldown ||= {}
  @cooldown[key] ||= Time.now
  elapsed = Time.now - @cooldown[key]
  
  if elapsed > MAX_COOLDOWN
    @cooldown[key] = nil
  else
    interval = [BASE_COOLDOWN * elapsed, MIN_COOLDOWN].max
    
    sleep interval
  end
end