Class: Viberroo::Bot

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

Overview

This class represents a server bot/client which communicates to Viber API. Each request sends a http POST request to a particular endpoint, each returns either http response, or parsed response body as specified in configuration.

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(response: Response.new({}), token: nil) ⇒ Bot

Returns a new instance of Bot.

Examples:

Initializing

class ViberController < ApplicationController
  skip_before_action :verify_authenticity_token

  def callback
    @response = Viberroo::Response.new(params.permit!)
    @bot = Viberroo::Bot.new(response: @response)

    head :ok
  end
end

Parameters:

  • response (Response) (defaults to: Response.new({}))

    Required. A callback response.

  • token (String) (defaults to: nil)

    Optional. Normally should be provided by ‘Viberroo.configure.auth_token` but is available here as a shortcut when predefined configuration is undesirable. Takes precedence over `Viberroo.configure.auth_token`.

See Also:


31
32
33
34
35
36
37
38
39
# File 'lib/viberroo/bot.rb', line 31

def initialize(response: Response.new({}), token: nil)
  Viberroo.configure

  @headers = {
    'X-Viber-Auth-Token': token || Viberroo.config.auth_token,
    'Content-Type': 'application/json'
  }
  @response = response
end

Instance Method Details

#broadcast(message:, to:) ⇒ Net::HTTPResponse || Hash

Note:

This request has a rate limit of 500 requests in a 10 seconds window.

Broadcasts a messages to subscribed users by making a request to ‘/broadcast_message`.

Examples:

Broadcast simple message

message = Viberroo::Message.plain(text: 'Howdy.')
response = @bot.broadcast(message: message, to: ViberSubscriber.sample(500).pluck(:viber_id))

Parameters:

  • message (Hash)

    Required. One of the message types to broadcast.

  • to (Array)

    Required. List of user ids to broadcast to. Specified users need to be subscribed.

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


180
181
182
# File 'lib/viberroo/bot.rb', line 180

def broadcast(message:, to:)
  request(URL::BROADCAST_MESSAGE, message.merge(broadcast_list: to))
end

#get_account_infoNet::HTTPResponse || Hash

Retrieves account info by making a request to ‘/get_account_info`. These settings can be set in you Viber admin panel.

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


191
192
193
# File 'lib/viberroo/bot.rb', line 191

def 
  request(URL::GET_ACCOUNT_INFO)
end

#get_online(ids:) ⇒ Net::HTTPResponse || Hash

Note:

The API supports up to 100 user id per request and those users must be subscribed to the account.

Retrieves a list of user status by making a request to ‘get_online`.

Examples:

response = @bot.get_online(ids: ViberSubscriber.sample(100).pluck(:viber_id))

Parameters:

  • ids (Array)

    Required. List of user ids.

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


227
228
229
# File 'lib/viberroo/bot.rb', line 227

def get_online(ids:)
  request(URL::GET_ONLINE, ids: ids)
end

#get_user_details(id:) ⇒ Net::HTTPResponse || Hash

Note:

This request can be sent twice during a 12 hours period for each user ID.

Retrieves details of particular user by making a request to ‘/get_user_details`.

Examples:

response = @bot.get_user_details(id: ViberSubscriber.sample.viber_id)

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


208
209
210
# File 'lib/viberroo/bot.rb', line 208

def get_user_details(id:)
  request(URL::GET_USER_DETAILS, id: id)
end

#remove_webhookNet::HTTPResponse || Hash

Removes a webhook by making a request to ‘/set_webhook`.

Examples:

Remove webhook with rake task

namespace :viber do
  task remove_webhook: :environment do
    Viberroo::Bot.new.remove_webhook
  end
end

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


85
86
87
# File 'lib/viberroo/bot.rb', line 85

def remove_webhook
  request(URL::WEBHOOK, url: '')
end

#send(message:, keyboard: {}) ⇒ Object

Deprecated.

Use #send_message instead.


153
154
155
156
157
158
159
160
# File 'lib/viberroo/bot.rb', line 153

def send(message:, keyboard: {})
  Viberroo.config.logger.info(<<~WARNING)
    DEPRECATION WARNING: Bot#send method is going to be removed in the next
    minor release. Use Bot#send_message instead.
  WARNING

  send_message(message, keyboard: keyboard)
end

#send_message(message, keyboard: {}) ⇒ Net::HTTPResponse || Hash

Sends a message to a user by making a request to ‘/send_message`.

Examples:

Send a plain message

go_somewhere = Viberroo::Input.url_button({
  Columns: 3,
  Rows: 2,
  Text: 'Mystery link',
  ActionBody: 'somewhere.com'
})

keyboard = Viberroo::Input.keyboard(Buttons: [go_somewhere])
message = Viberroo::Message.plain(text: 'Click if you dare.')

@bot.send(message: message, keyboard: keyboard)

Send a rich media

search = Viberroo::Input.reply_button({
  Columns: 4,
  Rows: 3,
  ActionBody: '/search',
  Text: 'Search something...'
}

locate = Viberroo::Input.reply_button({
  Columns: 4,
  Rows: 3,
  ActionBody: '/near_me'
}

browse = Viberroo::Input.url_button({
  Columns: 4,
  Rows: 2,
  ActionBody: 'parrot.live',
  Text: 'Browse something wierd'
}

rich_message = Viberroo::Message.rich(rich_media: { ButtonsGroupColumns: 4,
                                                    ButtonsGroupRows: 6,
                                                    Buttons: [search, locate, browse] })

@bot.send(message: rich_message)

Parameters:

  • message (Hash)

    Required. One of the message types to send.

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

    Optional. A keyboard that can be attached to a message.

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


143
144
145
146
147
148
149
150
# File 'lib/viberroo/bot.rb', line 143

def send_message(message, keyboard: {})
  request(
    URL::MESSAGE,
    { receiver: @response.user_id }.merge(message, keyboard).tap do |hash|
      hash.merge!(min_api_version_hash(keyboard)) unless hash[:min_api_version]
    end
  )
end

#set_webhook(url:, event_types: nil, send_name: nil, send_photo: nil) ⇒ Net::HTTPResponse || Hash

Sets a webhook by making a request to ‘/set_webhook`. Necessary for receiving callbacks from Viber. For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. `ngrok` is a good workaround for development convenience.

Examples:

Setup webhook with rake task

namespace :viber do
  task set_webhook: :environment do
    Viberroo::Bot.new.set_webhook(
      url: 'https://<your_ngrok_public_address>/viber',
      event_types: %w[conversation_started subscribed unsubscribed],
      send_name: true,
      send_photo: true
    )
  end
end

Parameters:

  • url (String)

    Required. HTTPs callback URL.

  • event_types (Array) (defaults to: nil)

    Optional. Indicates the types of Viber events that the bot will receive. Leaving this parameter out will include all events. **API default**: ‘%w[delivered seen failed subscribed unsubscribed conversation_started]`.

  • send_name (true, false) (defaults to: nil)

    Optional. Indicates whether or not the bot should receive the user name. **API default**: ‘false`.

  • send_photo (true, false) (defaults to: nil)

    Optional. Indicates whether or not the bot should receive the user photo. **API default**: ‘false`.

Returns:

  • (Net::HTTPResponse || Hash)

See Also:


66
67
68
69
# File 'lib/viberroo/bot.rb', line 66

def set_webhook(url:, event_types: nil, send_name: nil, send_photo: nil)
  request(URL::WEBHOOK, url: url, event_types: event_types,
                        send_name: send_name, send_photo: send_photo)
end