Class: Caldera::WebSocket

Inherits:
Object
  • Object
show all
Includes:
EventEmitter
Defined in:
lib/caldera/websocket.rb

Constant Summary collapse

LOGGER =
Logging.logger[self]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, authorization, num_shards, user_id) ⇒ WebSocket

Create a WebSocket that connects to the Lavalink server.

Parameters:

  • uri (URI, String)

    The URI to connect with. (ex: ‘“ws://localhost:8080”`)

  • authorization (String)

    Password matching the server config.

  • num_shards (Integer)

    Total number of shards your bot is operating on.

  • user_id (String, Integer)

    The user ID of the bot you are playing music with.



25
26
27
28
29
30
31
32
# File 'lib/caldera/websocket.rb', line 25

def initialize(uri, authorization, num_shards, user_id)
  @uri = uri.is_a?(URI::Generic) ? uri : URI.parse(uri)
  @uri.scheme = 'ws'

  create_driver
  set_headers(authorization, num_shards, user_id)
  register_handlers
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



15
16
17
# File 'lib/caldera/websocket.rb', line 15

def thread
  @thread
end

#uriObject (readonly)

Returns the value of attribute uri.



15
16
17
# File 'lib/caldera/websocket.rb', line 15

def uri
  @uri
end

Instance Method Details

#close(message: nil, code: 1000) ⇒ Object

Send a close frame

Parameters:

  • message (String) (defaults to: nil)

    The close reason

  • code (Integer) (defaults to: 1000)

    The close code



61
62
63
64
# File 'lib/caldera/websocket.rb', line 61

def close(message: nil, code: 1000)
  LOGGER.debug { "Sending close: (#{message.inspect}, #{code})" }
  @driver.close(reason, code)
end

#send_json(message) ⇒ Object

Encode a hash to json, and send it over the websocket.

Parameters:

  • message (Hash)


47
48
49
50
# File 'lib/caldera/websocket.rb', line 47

def send_json(message)
  LOGGER.debug { "Sending message: #{message.inspect}" }
  @driver.text(JSON.dump(message))
end

#startObject

Start the connection to the Lavalink server.



35
36
37
38
39
40
41
42
43
# File 'lib/caldera/websocket.rb', line 35

def start
  LOGGER.info { "Opening connection to #{url}" }
  @tcp  = TCPSocket.new(@uri.host || localhost, @uri.port)
  @dead = false
  create_thread

  @driver.start
  LOGGER.info { 'Driver started' }
end

#urlObject



66
67
68
# File 'lib/caldera/websocket.rb', line 66

def url
  @uri.to_s
end

#write(data) ⇒ Object

Write data to the socket

Parameters:

  • data (String)


54
55
56
# File 'lib/caldera/websocket.rb', line 54

def write(data)
  @tcp.write(data)
end