-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollector.rb
executable file
·99 lines (84 loc) · 2.52 KB
/
collector.rb
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby
# Written by ABrambleNinja, based heavily on pickdenis's ps-chatbot <github.com/pickdenis/ps-chatbot>
# Released under MIT license, see LICENSE for details
CONFIG = "config.yml"
require 'faye/websocket'
require 'json'
require 'yaml'
require 'eventmachine'
require './battle'
unless File.exist? CONFIG
puts "Error - no config file. Please copy config-example.yml to config.yml."
exit
end
config = YAML.load(File.open(CONFIG))
if config["tiers"].is_a? Array
TIERS = config["tiers"].map(&:downcase)
else
TIERS = [config["tiers"]].map(&:downcase)
end
POLL_LENGTH = config["poll_length"]
SOCKET = config["socket"]
module Utils
def self.parse_battle_list data, formats
battles = []
data["rooms"].each do |key, value|
tier = /^battle-((\w|-)+)-\d+$/.match(key).captures[0] # what tier is the battle
battles << key if formats.include? tier
end
battles
end
end
EM.run do
ws = Faye::WebSocket::Client.new(SOCKET)
joined_battles = []
ws.on :open do |e|
puts "Connected!"
refresh_timer = EventMachine::PeriodicTimer.new(POLL_LENGTH) do
ws.send("|/cmd roomlist")
end
end
ws.on :message do |e|
room = ""
messages = e.data.split("\n")
if messages[0][0] == '>'
room = messages.shift[1..-1]
end
messages.each do |rawmessage|
message = rawmessage.split("|")
next if !message[1]
case message[1].downcase
when "queryresponse"
if message[2] == "roomlist"
battles = Utils::parse_battle_list(JSON.parse(message[3]), TIERS) # get all battles that are any of the formats contained in TIERS
battles.each do |battle_id|
unless joined_battles.any? {|joined_battle| joined_battle.battle_id == battle_id} # if we're not already in them
puts "Joining #{battle_id}"
ws.send("|/join #{battle_id}")
joined_battles << Battle.new(battle_id)
end
end
end
when "c", "c:"
# do nothing
else
battle = joined_battles.find {|joined_battle| joined_battle.battle_id == room}
next if battle.nil?
battle.log(message.join("|"))
if message[1].downcase == "win" or message[1].downcase == "tie"
puts "Leaving room #{room}"
ws.send("#{room}|/leave")
battle.close
joined_battles.delete(battle)
end
end
end
end
ws.on :close do |e|
puts "Disconnected"
end
Signal.trap("INT") do
joined_battles.each {|battle| battle.close }
exit
end
end