Module: Cleverbot::API

Defined in:
lib/cleverbot/api.rb

Overview

Wrapper for Cleverbot’s REST API

Constant Summary collapse

API_URL =

Base API url

'http://cleverbot.com'.freeze
WRAPPER =

Name of the library

'cleverbot'.freeze
MAX_BACKOFF =

The most time to wait to retry for a response from the API in seconds. This is because, at the time of writing, the API will sometimes return an empty response and you must retry your request.

60

Class Method Summary collapse

Class Method Details

.get_reply(key, input, conversation = nil, retry_empty: true, backoff: 1) ⇒ String

Returns the reply.

Parameters:

  • key (String)

    API key

  • input (String)

    the phrase to pass to the conversation

  • conversation (String) (defaults to: nil)

    the conversation ID to pass input to

  • retry_empty (true, false) (defaults to: true)

    whether to retry if we get an empty response

  • backoff (Integer) (defaults to: 1)

    how long to wait before retrying if retry_empty

Returns:

  • (String)

    the reply



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

def get_reply(key, input, conversation = nil, retry_empty: true, backoff: 1)
  return if backoff > MAX_BACKOFF

  reply = get_request(
    'getreply',
    key: key, input: input, cs: conversation
  )

  return reply unless retry_empty && reply['output'].nil?
  puts "Reponse empty! Retrying after #{backoff} seconds."
  sleep backoff

  get_reply(key, input, conversation, retry_empty: true, backoff: backoff * 2)
end

.get_request(route = '', params = {}) ⇒ Object

Executre a GET request.

Parameters:

  • route (String) (defaults to: '')

    the route to request

  • params (Hash) (defaults to: {})

    the params to query



24
25
26
27
28
# File 'lib/cleverbot/api.rb', line 24

def get_request(route = '', params = {})
  params[:wrapper] = WRAPPER
  response = RestClient.get "#{API_URL}/#{route}", params: params
  JSON.parse response
end