Class: Rebot::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/rebot/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(queue: nil) ⇒ Server

Returns a new instance of Server.



5
6
7
8
9
10
# File 'lib/rebot/server.rb', line 5

def initialize(queue: nil)
  @queue = queue
  @bots = {}
  @new_token_proc = -> (token) { Rebot::BaseBot.new(token: token) }
  @running = false
end

Instance Attribute Details

#queueObject (readonly)

Returns the value of attribute queue.



3
4
5
# File 'lib/rebot/server.rb', line 3

def queue
  @queue
end

Instance Method Details

#add_bot(bot) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/rebot/server.rb', line 35

def add_bot(bot)
  # Do not add bot same bot twice
  return if @bots[bot.token]
  log "adding bot #{bot}"
  @bots[bot.token] = bot
  bot.start if @running
end

#add_token(token) ⇒ Object



43
44
45
46
47
48
# File 'lib/rebot/server.rb', line 43

def add_token(token)
  bot = @new_token_proc.call(token)
  add_bot(bot) if bot
rescue => e
  log_error(e)
end

#listen_for_instructionsObject



28
29
30
31
32
33
# File 'lib/rebot/server.rb', line 28

def listen_for_instructions
  EM.add_periodic_timer(1) do
    next_message = queue.pop
    process_instruction(next_message) if next_message
  end
end

#on_new_token(&block) ⇒ Object



12
13
14
# File 'lib/rebot/server.rb', line 12

def on_new_token(&block)
  @new_token_proc = block
end

#remove_bot(token) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/rebot/server.rb', line 50

def remove_bot(token)
  if (bot = @bots[token])
    bot.stop
    @bots.delete(token)
  end
rescue => e
  log_error(e)
end

#startObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rebot/server.rb', line 16

def start
  EM.run do
    begin
      @running = true
      @bots.each { |key, bot| bot.start }
      listen_for_instructions if @queue
    rescue => e
      log_error(e)
    end
  end
end