Simple bridge server for various bots of mine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.9 KiB

#!/usr/bin/ruby
require 'readline'
require 'net/http'
require 'json'
require 'websocket-client-simple'
require 'uri'
puts "Connecting to server #{ARGV[0]} on port #{ARGV[1]}"
def get(path)
where = URI("http://#{ARGV[0]}:#{ARGV[1]}/#{path}")
JSON.parse(Net::HTTP.get(where))
end
def post(path,data)
where = URI("http://#{ARGV[0]}:#{ARGV[1]}/#{path}")
Net::HTTP.post(where,data.to_json)
end
version = get("version")["version"]
puts "Server reported version: #{version}"
print "Nickname> "
nickname = $stdin.gets.strip
puts "Trying to log in..."
res = get("/user/exists?protocol_id=#{"heimdall-"+nickname}")
puts "Account exists! exiting" if res["exists"]
return if res["exists"]
puts "Creating account..."
test = post("/user/new",{username: nickname, protocol_id: "heimdall-"+nickname})
unless test.kind_of? Net::HTTPOK then
puts "Something went wrong! exiting"
exit
end
puts "Your id is: heimdall-#{nickname}"
puts "Establishing websocket connection..."
ws = WebSocket::Client::Simple.connect "ws://#{ARGV[0]}:#{ARGV[2]}"
ws.on :message do |msg|
data = JSON.parse(msg.data)
if data.has_key? "websocket" then
uid = data["websocket"]
response = post("/user/listen",{
websocket: uid,
protocol_id: "heimdall-"+nickname
})
unless response.kind_of? Net::HTTPOK then
puts "Something went wrong when initiating listening to user! Check server logs for info."
end
elsif data.has_key? "error" then
puts "ERROR: #{data["error"]}"
else
puts "#{data["user"]["username"]}: #{data["content"]}"
end
end
ws.on :open do |msg|
puts "Websocket connection established"
end
at_exit do
ws.close
end
target = nil
at_exit do
post("/user/delete",{
"protocol_id"=> "heimdall-"+nickname
})
end
while buf = Readline.readline("> ", true)
if buf == "/help" then
puts "Commands:"
puts "/help - this message"
puts "/send <protcol_id> - direct messages to somebody"
puts "/exit - quit program"
puts "/find <username> - find a username by pattern"
puts "/find-protoid <protoid> - find by a protocol id"
next
end
if buf == "/exit" then
post("/user/delete",{
"protocol_id"=> "heimdall-"+nickname
})
exit
end
if buf.match(/^\/send .*$/) then
target = buf.match(/^\/send ([^\s]*)$/)[1]
next
end
if buf.match(/^\/find .*$/) then
uname = (buf.match /^\/find (.*)$/)[1]
users = get("/user/find/by-username?username=#{uname}")["results"]
puts "Found #{users.length} results: "
users.each { |x| puts x[0] }
next
end
if buf.match(/^\/find-protoid .*$/) then
pid = (buf.match /^\/find-protoid (.*)$/)[1]
users = get("/user/find/by-protoid?protocol_id=#{pid}")["results"]
puts "Found #{users.length} results: "
users.each { |x| puts x[0] }
next
end
if target then
post("/user/send", {
"to" => target,
"content" => buf,
"from" => "heimdall-"+nickname
})
end
end