summaryrefslogtreecommitdiff
path: root/lib/6-chit-chat/subscribe.rb
blob: c3827c6cb5c08cdc907c2143caa80664d5bf8828 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env ruby
## encoding: utf-8

require "bunny"

connection = Bunny.new(host: ENV.fetch('RABBIT_HOST', 'localhost'))
connection.start

channel = connection.create_channel
exchange = channel.topic("chitchat")
queue = channel.queue("", exclusive: true)

ARGV.push('#') if ARGV.empty?
ARGV.each do |username|
  queue.bind(exchange, routing_key: username)
end

puts " [*] Waiting for gossip from #{ARGV}. To exit press CTRL+C"

begin
  queue.subscribe(block: true) do |delivery_info, properties, body|
    puts " [x] #{delivery_info.routing_key}:#{body}"
    message = "#{delivery_info.routing_key} says #{body}"
    system("say '#{message}'")
  end
rescue Interrupt => _
  channel.close
  connection.close
end