Class: ChatScript::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hostname: 'localhost', port: 1024, bot: '', default_user: 'guest', error_handler: method(:error_handler)) ⇒ Client

Returns a new instance of Client.



48
49
50
51
52
53
54
55
# File 'lib/chatscript.rb', line 48

def initialize( hostname: 'localhost', port: 1024, bot: '', 
                default_user: 'guest', error_handler: method(:error_handler) )
  @hostname = hostname
  @port = port
  @bot = bot
  @default_user = default_user
  @error_handler = error_handler
end

Instance Attribute Details

#botObject

Returns the value of attribute bot.



45
46
47
# File 'lib/chatscript.rb', line 45

def bot
  @bot
end

#default_userObject

Returns the value of attribute default_user.



45
46
47
# File 'lib/chatscript.rb', line 45

def default_user
  @default_user
end

#errorObject (readonly)

Returns the value of attribute error.



46
47
48
# File 'lib/chatscript.rb', line 46

def error
  @error
end

#hostnameObject

Returns the value of attribute hostname.



45
46
47
# File 'lib/chatscript.rb', line 45

def hostname
  @hostname
end

#portObject

Returns the value of attribute port.



45
46
47
# File 'lib/chatscript.rb', line 45

def port
  @port
end

Class Method Details

.versionObject



41
42
43
# File 'lib/chatscript.rb', line 41

def self.version
  VERSION
end

Instance Method Details

#alive?Boolean

send a user message to the bot and get th ebot reply

Returns:

  • (Boolean)


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/chatscript.rb', line 101

def alive?
  begin 
    # open client socket 
    socket  = TCPSocket.open(@hostname, @port)

    # send an alive check message 
    socket.write( "\0\0\0" )

    Message.new socket.read
    true
  rescue 
    @error_handler.call
    false
  end 
end

#error_handlerObject



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

def error_handler
  @error = $!
  STDERR.print "#{timestamp}: runtime error connecting to server: #@error\n" 
end

#last_errorObject



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

def last_error
  @error
end

#start(user: @defaultuser) ⇒ Object

first volley user message is null (void string)



74
75
76
# File 'lib/chatscript.rb', line 74

def start( user: @defaultuser ) 
  volley( '', user: user )
end

#volley(message, user: @default_user) ⇒ Object

send a user message to the bot and get the bot reply



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/chatscript.rb', line 82

def volley( message, user: @default_user )
  begin 
    # open client socket 
    socket  = TCPSocket.open(@hostname, @port)

    # send user message to bot
    socket.write( "#{user}\0#{@bot}\0#{message}\0" )

    # return the bot's answer as Message
    Message.new socket.read

  rescue 
    @error_handler.call
  end 
end