Class: Cleverbot

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

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_user, api_key, nick = nil) ⇒ Cleverbot

Creates a new instance of the Cleverbot.

Parameters:

  • api_user (String)

    The API user for the Cleverbot API.

  • api_key (String)

    The API key for the Cleverbot API.

  • nick (String) (defaults to: nil)

    The reference nick. If nil, one will be set automatically through the API.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cleverbot.rb', line 18

def initialize(api_user, api_key, nick = nil)
  @api_user = api_user
  @api_key = api_key
  @nick = nick
  @client = HTTPClient.new

  params = {
    user: @api_user,
    key: @api_key
  }
  params[:nick] = @nick unless @nick.nil?
  response = Oj.load(@client.post('https://cleverbot.io/1.0/create', params).body)
  try_throw(response['status'])
  @nick = response['nick']
end

Instance Attribute Details

#api_keyString (readonly)

Returns The API Key for the instance.

Returns:

  • (String)

    The API Key for the instance.



9
10
11
# File 'lib/cleverbot.rb', line 9

def api_key
  @api_key
end

#api_userString (readonly)

Returns The API User for the instance.

Returns:

  • (String)

    The API User for the instance.



6
7
8
# File 'lib/cleverbot.rb', line 6

def api_user
  @api_user
end

#nickString

Returns The reference nick for the session.

Returns:

  • (String)

    The reference nick for the session.



12
13
14
# File 'lib/cleverbot.rb', line 12

def nick
  @nick
end

Instance Method Details

#say(str) ⇒ String

Sends the bot a message and returns its response.

Parameters:

  • str (String)

    The message to send to the bot.

Returns:

  • (String)

    The bot’s response, or its error message.



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/cleverbot.rb', line 37

def say(str)
  params = {
    user: @api_user,
    key: @api_key,
    text: str,
    nick: @nick
  }
  response = Oj.load(@client.post('https://cleverbot.io/1.0/ask', params).body)
  try_throw(response['status'])

  response['response']
end