### Basic Viber Bot Example in Java Source: https://github.com/viber/viber-bot-java/blob/master/README.md A simple example demonstrating how to initialize a Viber bot, set up a message received handler, and process incoming requests. This requires a Viber bot profile and an authentication token. ```java public void botExample() { ViberBot bot = new ViberBot(new BotProfile("SampleBot", "http://viber.com/avatar.jpg"), "YOUR_AUTH_TOKEN_HERE"); bot.onMessageReceived((event, message, response) -> response.send(message)); // somewhere else in your web server of choice: bot.incoming(Request.fromJsonString("...")); } ``` -------------------------------- ### Install Viber Java Bot with Maven Source: https://github.com/viber/viber-bot-java/blob/master/README.md This snippet shows how to add the Viber Java Bot library to your project using Maven. Ensure you have Java 8 or higher installed. ```xml com.viber viber-bot 1.0.11 ``` -------------------------------- ### Install Viber Java Bot with Gradle Source: https://github.com/viber/viber-bot-java/blob/master/README.md This snippet shows how to add the Viber Java Bot library to your project using Gradle. Ensure you have Java 8 or higher installed. ```gradle compile group: 'com.viber', name: 'viber-bot', version: '1.0.11' ``` -------------------------------- ### Viber Bot Text Message Router Example in Java Source: https://github.com/viber/viber-bot-java/blob/master/README.md An example of setting up a text message router for the Viber bot. This allows you to define specific responses for certain text patterns. Note that messages sent to the router are also emitted to the general `onMessageReceived` event. ```java public void botTextRouterExample() { bot.onTextMessage("(hi|hello)", (event, message, response) -> response.send("Hi " + event.getSender().getName())); } ``` -------------------------------- ### ViberBot - Initialize, Set Webhook, Handle Messages and Conversations (Java) Source: https://context7.com/viber/viber-bot-java/llms.txt Demonstrates the initialization of the `ViberBot` class with profile and auth token, setting up the webhook endpoint, and registering handlers for incoming messages and conversation start events. It uses OkHttp for HTTP communication, Jackson for JSON, and Guava's ListenableFuture for async operations. ```java import com.viber.bot.api.ViberBot; import com.viber.bot.profile.BotProfile; import com.viber.bot.message.TextMessage; import com.viber.bot.Request; import com.google.common.util.concurrent.Futures; import java.util.Optional; // Initialize the bot with profile and auth token ViberBot bot = new ViberBot( new BotProfile("MyBot", "https://example.com/avatar.jpg"), "YOUR_AUTH_TOKEN_HERE" ); // Register webhook (HTTPS required with valid SSL certificate) bot.setWebhook("https://your-server.com/webhook").get(); // Handle incoming messages - echo back any received message bot.onMessageReceived((event, message, response) -> { String senderName = event.getSender().getName(); System.out.println("Received message from: " + senderName); response.send(message); // Echo the message back }); // Handle conversation started - send welcome message bot.onConversationStarted(event -> Futures.immediateFuture( Optional.of(new TextMessage("Welcome " + event.getUser().getName() + "!")) )); // Process incoming webhook request (in your web server handler) // String json = // ... JSON from HTTP POST body // InputStream responseStream = bot.incoming(Request.fromJsonString(json)).get(); ``` -------------------------------- ### GET /viber/botProfile Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Retrieves the profile information for the Viber bot. ```APIDOC ## GET /viber/botProfile ### Description Returns the BOT profile. ### Method GET ### Endpoint /viber/botProfile ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **botProfile** (BotProfile) - An object containing the bot's profile information. #### Response Example ```json { "botProfile": { "id": "1234567890abcdef", "name": "My Awesome Bot", "avatar": "http://example.com/avatar.png" } } ``` ``` -------------------------------- ### Register Conversation Started Callback (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Registers a callback for the Event.CONVERSATION_STARTED event. The provided listener will be invoked when a conversation started event is received via incoming requests. Requires an OnConversationStarted listener. ```java public void onConversationStarted(@Nonnull OnConversationStarted listener) ``` -------------------------------- ### Register Conversation Started Callback Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Registers a callback for the `Event.CONVERSATION_STARTED` event. The provided listener will be invoked when a new conversation is initiated with the bot. ```APIDOC ## POST /viber/viber-bot-java/onConversationStarted ### Description Registers a callback for event [`Event.CONVERSATION_STARTED`](../../../../com/viber/bot/event/Event.html#CONVERSATION_STARTED). The listener will be called upon [`incoming(Request)`](../../../../com/viber/bot/api/ViberBot.html#incoming-com.viber.bot.Request-) of that event. ### Method POST ### Endpoint /viber/viber-bot-java/onConversationStarted ### Parameters #### Request Body - **listener** (OnConversationStarted) - Required - The listener to be called when a conversation starts. ### Request Example ```json { "listener": "com.example.MyConversationListener" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Callback registered successfully" } ``` ``` -------------------------------- ### Integrate Viber Bot with Spring Boot (Java) Source: https://context7.com/viber/viber-bot-java/llms.txt This example shows a complete integration of the Viber bot with a Spring Boot application. It sets up the ViberBot, registers message and conversation handlers, and implements a webhook endpoint for receiving Viber messages, including signature validation. ```java import com.viber.bot.api.ViberBot; import com.viber.bot.profile.BotProfile; import com.viber.bot.ViberSignatureValidator; import com.viber.bot.Request; import com.viber.bot.message.TextMessage; import com.google.common.util.concurrent.Futures; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @SpringBootApplication public class ViberBotApplication { private final ViberBot bot; private final ViberSignatureValidator validator; public ViberBotApplication() { this.bot = new ViberBot( new BotProfile("SpringBot", "https://example.com/avatar.jpg"), "YOUR_AUTH_TOKEN" ); this.validator = new ViberSignatureValidator("YOUR_AUTH_TOKEN"); // Set webhook on startup bot.setWebhook("https://your-server.com/viber"); // Register handlers bot.onMessageReceived((event, message, response) -> response.send(message)); bot.onConversationStarted(event -> Futures.immediateFuture(Optional.of(new TextMessage("Welcome!"))) ); } @PostMapping(value = "/viber", produces = "application/json") public String webhook( @RequestBody String json, @RequestHeader("X-Viber-Content-Signature") String signature) throws Exception { if (!validator.isSignatureValid(signature, json)) { throw new SecurityException("Invalid signature"); } bot.incoming(Request.fromJsonString(json)).get(); return "{}"; } public static void main(String[] args) { SpringApplication.run(ViberBotApplication.class, args); } } ``` -------------------------------- ### Handle Conversation Start Event in Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/callback/OnConversationStarted.html This Java code snippet demonstrates how to implement the OnConversationStarted interface to handle incoming conversation start events. It defines the 'conversationStarted' method which receives an IncomingConversationStartedEvent and returns a Future containing an Optional Message. ```java package com.viber.bot.event.callback; import com.viber.bot.event.incoming.IncomingConversationStartedEvent; import com.viber.bot.message.Message; import java.util.Optional; import java.util.concurrent.Future; public interface OnConversationStarted extends com.viber.bot.event.BotEventListener> { /** * Handles the event when a conversation is started. * * @param event The incoming conversation started event. * @return A Future containing an Optional Message to be sent back. */ Future> conversationStarted(IncomingConversationStartedEvent event); /** * Emits an event with the given arguments. * * @param args The arguments for the event. * @return A Future containing an Optional Message. */ default Future> emit(Object... args) { // Default implementation or abstract method declaration throw new UnsupportedOperationException("emit method not implemented"); } } ``` -------------------------------- ### GET /viber/accountInfo Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Retrieves the public account information for the Viber bot. ```APIDOC ## GET /viber/accountInfo ### Description Returns the BOT public account info. ### Method GET ### Endpoint /viber/accountInfo ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **accountInfo** (ApiResponse) - An object containing the bot's account information. #### Response Example ```json { "accountInfo": { "id": "1234567890abcdef", "name": "My Awesome Bot", "uri": "mybot.viber.com", "icon": "http://example.com/icon.png" } } ``` ``` -------------------------------- ### IncomingConversationStartedEvent Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingConversationStartedEvent.html Represents an event triggered when a new conversation is started with the bot. It provides details about the user and the conversation context. ```APIDOC ## IncomingConversationStartedEvent ### Description This class represents an incoming event indicating that a conversation has been started with the bot. It extends the base `IncomingEvent` class and provides specific details related to the conversation initiation. ### Method This documentation describes the methods available for the `IncomingConversationStartedEvent` class. ### Endpoint N/A (This is an event class, not an API endpoint). ### Parameters This class does not have direct parameters in the context of an API request. It represents data received from the Viber platform. #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example This is an event object, not a request. ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Methods * **`getType()`** * **Description**: Returns the type of the event. * **Return Type**: `java.lang.String` * **`getToken()`** * **Description**: Returns the token associated with the event. * **Return Type**: `long` * **`getUser()`** * **Description**: Returns the `UserProfile` object of the user who started the conversation. * **Return Type**: `com.viber.bot.profile.UserProfile` * **`isSubscribed()`** * **Description**: Indicates whether the user is subscribed to the bot. * **Return Type**: `boolean` * **`getContext()`** * **Description**: Returns the context of the conversation, if available. * **Return Type**: `java.lang.String` (Nullable) * **`equals(java.lang.Object o)`** * **Description**: Compares this `IncomingConversationStartedEvent` object with another object for equality. * **Return Type**: `boolean` * **Overrides**: `java.lang.Object.equals()` * **`hashCode()`** * **Description**: Returns a hash code value for this `IncomingConversationStartedEvent` object. * **Return Type**: `int` * **Overrides**: `java.lang.Object.hashCode()` ### Inherited Methods Methods inherited from `com.viber.bot.event.incoming.IncomingEvent`: * `getEvent()` * `getTimestamp()` Methods inherited from `java.lang.Object`: * `getClass()` * `notify()` * `notifyAll()` * `toString()` * `wait()` * `wait(long timeout)` * `wait(long timeout, int nanos)` ``` -------------------------------- ### Register Conversation Started Listener - ViberBot Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Registers a callback listener for the 'conversation started' event. When a new conversation is initiated with the bot, the provided listener will be invoked. This method allows the bot to react to the beginning of new user interactions. ```java void onConversationStarted(com.viber.bot.event.callback.OnConversationStarted listener) ``` -------------------------------- ### Viber Bot Event Enum Methods (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/Event.html Details the static and instance methods available for the Viber Bot Event enum. This includes the 'valueOf' method to retrieve an enum constant by its name and the 'values' method to get an array of all constants. ```java public static com.viber.bot.event.Event valueOf(java.lang.String name); public static com.viber.bot.event.Event[] values(); public java.lang.String getServerEventName(); ``` -------------------------------- ### Get Account Info - ViberBot Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Retrieves the public account information for the Viber bot. This method returns a ListenableFuture that will resolve to an ApiResponse object containing the account details. It's useful for fetching bot-specific metadata. ```java com.google.common.util.concurrent.ListenableFuture getAccountInfo() ``` -------------------------------- ### FileMessage Methods - Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/FileMessage.html Provides methods to retrieve information about a FileMessage. These include getting the file's URL, size in bytes, and filename. The equals and hashCode methods are inherited from Object and are overridden for proper object comparison. ```java public boolean equals(java.lang.Object o) ``` ```java public java.lang.String getFilename() ``` ```java public int getSizeInBytes() ``` ```java public java.lang.String getUrl() ``` ```java public int hashCode() ``` -------------------------------- ### IncomingEvent Class Methods - Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingEvent.html This snippet details the methods available in the IncomingEvent class. It includes methods for getting the event type, timestamp, and for object comparison (equals and hashCode). These methods are fundamental for processing incoming events from the Viber platform. ```java public Event getEvent() { // ... implementation details ... } public long getTimestamp() { // ... implementation details ... } public boolean equals(Object o) { // ... implementation details ... } public int hashCode() { // ... implementation details ... } ``` -------------------------------- ### RichMediaObject Constructors Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/RichMediaObject.html Provides details on how to instantiate a RichMediaObject. ```APIDOC ## RichMediaObject Constructors ### Description This section details the constructors available for the `RichMediaObject` class, allowing for its instantiation either with default values or by delegating to an existing Map. ### Method - `RichMediaObject()` - `RichMediaObject(Map delegate)` ### Parameters #### Constructor: `RichMediaObject(Map delegate)` - **delegate** (Map) - Optional - The map to delegate to for this RichMediaObject. ### Request Example ```json // Example of creating a RichMediaObject with a delegate map Map myMap = new HashMap<>(); myMap.put("key1", "value1"); RichMediaObject richMedia = new RichMediaObject(myMap); // Example of creating an empty RichMediaObject RichMediaObject emptyRichMedia = new RichMediaObject(); ``` ### Response #### Success Response (Object Creation) - The constructor successfully creates an instance of `RichMediaObject`. #### Response Example ```json // No direct response body for constructor calls, but the object is created. // Example of accessing data after creation: // String value = (String) richMedia.get("key1"); ``` ``` -------------------------------- ### IncomingEvent Class Methods Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingConversationStartedEvent.html Documentation for the `equals` and `hashCode` methods within the `IncomingEvent` class. ```APIDOC ## IncomingEvent Class Methods ### Description Provides details on the `equals` and `hashCode` methods available in the `IncomingEvent` class. ### Method `equals(Object)` ### Description Compares this `IncomingEvent` object to another object for equality. Overrides: `equals` in class `IncomingEvent`. ### Method `hashCode()` ### Description Returns a hash code value for the `IncomingEvent` object. Overrides: `hashCode` in class `IncomingEvent`. ``` -------------------------------- ### MessageKeyboard Class Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/MessageKeyboard.html Provides details about the MessageKeyboard class, its constructors, and inherited methods. ```APIDOC ## MessageKeyboard Class ### Description A simple wrapper class for `Map` used to construct message keyboards in the Viber bot API. It extends `com.google.common.collect.ForwardingMap`. ### Class Hierarchy * java.lang.Object * com.google.common.collect.ForwardingObject * com.google.common.collect.ForwardingMap * com.viber.bot.message.MessageKeyboard ### Implemented Interfaces * java.util.Map ### Constructors #### `MessageKeyboard()` Default constructor for creating an empty `MessageKeyboard`. #### `MessageKeyboard(Map delegate)` Constructor that takes an existing `Map` as the delegate. * **delegate** (Map) - The map to wrap. ### Methods This class inherits numerous methods from `com.google.common.collect.ForwardingMap` and `java.lang.Object`, including: * **From `ForwardingMap`**: `clear`, `containsKey`, `containsValue`, `entrySet`, `equals`, `get`, `hashCode`, `isEmpty`, `keySet`, `put`, `putAll`, `remove`, `size`, `values`. * **From `ForwardingObject`**: `toString`. * **From `Object`**: `getClass`, `notify`, `notifyAll`, `wait`. * **From `Map`**: `compute`, `computeIfAbsent`, `computeIfPresent`, `forEach`, `getOrDefault`, `merge`, `putIfAbsent`, `remove`, `replace`, `replaceAll`. ### Example Usage (Conceptual) ```java // Creating a new message keyboard MessageKeyboard keyboard = new MessageKeyboard(); // Adding elements to the keyboard (using inherited Map methods) keyboard.put("Type", "keyboard"); keyboard.put("Buttons", new ArrayList>()); // Or initializing with an existing map Map initialData = new HashMap<>(); initialData.put("Type", "keyboard"); MessageKeyboard keyboardFromMap = new MessageKeyboard(initialData); ``` ``` -------------------------------- ### Incoming Event Methods Source: https://github.com/viber/viber-bot-java/blob/master/docs/index-files/index-6.html This section details methods related to incoming events, such as retrieving timestamps and tokens from various event types. ```APIDOC ## GET /viber/events ### Description Retrieves timestamp information from incoming Viber events. ### Method GET ### Endpoint /viber/events ### Parameters #### Query Parameters - **event_type** (string) - Required - The type of incoming event (e.g., ConversationStarted, Delivered, Message). ### Request Example ```json { "event_type": "ConversationStarted" } ``` ### Response #### Success Response (200) - **timestamp** (long) - The timestamp of the event. #### Response Example ```json { "timestamp": 1678886400000 } ``` ## GET /viber/events/token ### Description Retrieves the token associated with specific incoming Viber events, such as conversation starts or message deliveries. ### Method GET ### Endpoint /viber/events/token ### Parameters #### Query Parameters - **event_type** (string) - Required - The type of incoming event for which to retrieve the token. ### Request Example ```json { "event_type": "ConversationStarted" } ``` ### Response #### Success Response (200) - **token** (string) - The token associated with the event. #### Response Example ```json { "token": "some_auth_token" } ``` ``` -------------------------------- ### RichMediaObject Methods Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/RichMediaObject.html Details on methods inherited and available for RichMediaObject. ```APIDOC ## RichMediaObject Methods ### Description This section outlines the methods available for the `RichMediaObject` class. As it extends `ForwardingMap`, it inherits all standard Map operations. ### Method - `clear()` - `containsKey(Object key)` - `containsValue(Object value)` - `entrySet()` - `equals(Object o)` - `get(Object key)` - `hashCode()` - `isEmpty()` - `keySet()` - `put(String key, Object value)` - `putAll(Map m)` - `remove(Object key)` - `size()` - `values()` - `toString()` - `compute(String key, BiFunction remappingFunction)` - `computeIfAbsent(String key, Function mappingFunction)` - `computeIfPresent(String key, BiFunction remappingFunction)` - `forEach(BiConsumer action)` - `getOrDefault(Object key, Object defaultValue)` - `merge(String key, Object value, BiFunction remappingFunction)` - `putIfAbsent(String key, Object value)` - `remove(Object key, Object value)` - `replace(String key, Object value)` - `replace(String key, Object oldValue, Object newValue)` - `replaceAll(BiFunction function)` ### Parameters Parameters vary depending on the specific method called. Refer to standard Java Map and Guava ForwardingMap documentation for detailed parameter information for each method. ### Request Example ```java // Example usage of inherited methods: RichMediaObject richMedia = new RichMediaObject(); richMedia.put("title", "Hello World"); richMedia.put("text", "This is a rich media message."); String title = (String) richMedia.get("title"); boolean hasText = richMedia.containsKey("text"); System.out.println("Title: " + title); System.out.println("Has text: " + hasText); ``` ### Response #### Success Response (Method Execution) - Methods return values or modify the object state according to their standard Java Map and Guava ForwardingMap behavior. #### Response Example ```json // Example of data retrieval: { "title": "Hello World", "text": "This is a rich media message." } ``` ``` -------------------------------- ### VideoMessage Constructors - Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/VideoMessage.html These constructors are used to create VideoMessage objects. The first constructor allows for optional text, thumbnail, duration, keyboard, and tracking data, while the second is more specific to video properties like URL, size, text, thumbnail, and duration. ```java public VideoMessage(@Nonnull java.lang.String url, int size, @Nullable java.lang.String text, @Nullable java.lang.String thumbnail, @Nullable java.lang.Integer duration, @Nullable com.viber.bot.message.MessageKeyboard keyboard, @Nullable com.viber.bot.message.TrackingData trackingData) public VideoMessage(@Nonnull java.lang.String url, int size, @Nullable java.lang.String text, @Nullable java.lang.String thumbnail, @Nullable java.lang.Integer duration) ``` -------------------------------- ### Get Text Content of TextMessage Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/TextMessage.html Retrieves the text content of a TextMessage object. This method is essential for accessing the message's textual data. ```java public java.lang.String getText() ``` -------------------------------- ### ViberBot Constructor Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Initializes a new instance of the ViberBot class. It requires a BotProfile object and an authentication token to establish a connection with the Viber API. ```java public ViberBot(@NonNull BotProfile botProfile, @NonNull String authToken) ``` -------------------------------- ### IncomingMessageEvent Details Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingMessageEvent.html This section provides details about the IncomingMessageEvent class, including its methods for retrieving message content, sender information, and token. ```APIDOC ## IncomingMessageEvent ### Description Represents an incoming message event from a user in the Viber bot. This class allows access to the message content, sender's profile, and a unique token associated with the event. ### Class Hierarchy - java.lang.Object - com.viber.bot.event.incoming.IncomingEvent - com.viber.bot.event.incoming.IncomingMessageEvent ### Methods #### `getMessage()` - **Description**: Retrieves the message content associated with this event. - **Return Type**: `Message` #### `getSender()` - **Description**: Retrieves the user profile of the sender. - **Return Type**: `UserProfile` #### `getToken()` - **Description**: Retrieves the unique token for this event. - **Return Type**: `Long` #### `equals(Object o)` - **Description**: Compares this IncomingMessageEvent object to another object for equality. - **Overrides**: `equals` in class `IncomingEvent` - **Return Type**: `boolean` #### `hashCode()` - **Description**: Returns a hash code value for this IncomingMessageEvent object. - **Overrides**: `hashCode` in class `Object` - **Return Type**: `int` ``` -------------------------------- ### Get Viber User Online Status (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Fetches the online status for a collection of Viber users. The method returns a ListenableFuture containing an ApiResponse, which might include an ApiException. User IDs can be obtained from UserProfile.getId(). ```java public com.google.common.util.concurrent.ListenableFuture getOnlineStatus(@Nonnull java.util.Collection userIds) ``` -------------------------------- ### IncomingErrorEvent Class Definition (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingErrorEvent.html This Java code defines the IncomingErrorEvent class, which inherits from IncomingEvent. It includes methods to get the error description, token, and user ID. It also overrides the equals and hashCode methods. ```java package com.viber.bot.event.incoming; import com.viber.bot.event.incoming.IncomingEvent; @Immutable public class IncomingErrorEvent extends IncomingEvent { public String getDescription() { // Method implementation not provided in the source return null; } public Long getToken() { // Method implementation not provided in the source return null; } public String getUserId() { // Method implementation not provided in the source return null; } @Override public boolean equals(Object o) { // Method implementation not provided in the source return super.equals(o); } @Override public int hashCode() { // Method implementation not provided in the source return super.hashCode(); } } ``` -------------------------------- ### Request Class Methods Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/Request.html This section covers the static and instance methods available for the Request class, including creation from various sources, event retrieval, response setting, and checking the closed status. ```APIDOC ## Request Class Documentation ### Description Provides methods for creating and managing Viber bot requests. It allows for request creation from input streams or JSON strings, retrieval of incoming events, and setting responses. ### Methods #### `static Request fromInputStream(InputStream inputStream)` * **Description**: Creates a Request object from an InputStream. The provided InputStream will be closed after use. * **Method**: POST (Implied, as it creates a resource) * **Endpoint**: N/A (Static factory method) * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **Request Example**: N/A * **Response**: * **Success Response (200)**: A `Request` object. * **Response Example**: N/A #### `static Request fromJsonString(String json)` * **Description**: Creates a Request object from a JSON string. * **Method**: POST (Implied, as it creates a resource) * **Endpoint**: N/A (Static factory method) * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **Parameters**: * `json` (String) - Required - The JSON string representing the request. * **Request Example**: ```json { "example": "request body" } ``` * **Response**: * **Success Response (200)**: A `Request` object. * **Response Example**: N/A #### `IncomingEvent getEvent()` * **Description**: Retrieves the incoming event associated with this request. * **Method**: GET * **Endpoint**: N/A (Instance method) * **Parameters**: None * **Request Example**: N/A * **Response**: * **Success Response (200)**: An `IncomingEvent` object. * **Response Example**: N/A #### `InputStream getResponseInputStream()` * **Description**: Gets the input stream for the response. * **Method**: GET * **Endpoint**: N/A (Instance method) * **Parameters**: None * **Request Example**: N/A * **Response**: * **Success Response (200)**: An `InputStream` object for the response. * **Response Example**: N/A #### `boolean isClosed()` * **Description**: Checks if the request has been closed. * **Method**: GET * **Endpoint**: N/A (Instance method) * **Parameters**: None * **Request Example**: N/A * **Response**: * **Success Response (200)**: A boolean value indicating if the request is closed. * **Response Example**: ```json { "isClosed": true } ``` #### `void setResponse(InputStream inputStream)` * **Description**: Sets the response using an InputStream. * **Method**: POST (Implied, as it sets a resource) * **Endpoint**: N/A (Instance method) * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **Parameters**: * `inputStream` (InputStream) - Required - The InputStream to set as the response. * **Request Example**: N/A * **Response**: * **Success Response (200)**: Void. * **Response Example**: N/A #### `void setResponse(String response)` * **Description**: Sets the response using a String. * **Method**: POST (Implied, as it sets a resource) * **Endpoint**: N/A (Instance method) * **Parameters**: * **Path Parameters**: None * **Query Parameters**: None * **Request Body**: None * **Parameters**: * `response` (String) - Required - The String to set as the response. * **Request Example**: ```json { "response": "Success" } ``` * **Response**: * **Success Response (200)**: Void. * **Response Example**: N/A #### `void close()` * **Description**: Closes the request, releasing any associated resources. * **Method**: DELETE (Implied, as it closes a resource) * **Endpoint**: N/A (Instance method) * **Parameters**: None * **Request Example**: N/A * **Response**: * **Success Response (200)**: Void. * **Response Example**: N/A ``` -------------------------------- ### ViberBot - Core Bot Instance Source: https://context7.com/viber/viber-bot-java/llms.txt The ViberBot class is the main entry point for creating and managing a Viber bot. It handles initialization, webhook registration, event listener registration, and processing of incoming requests. ```APIDOC ## ViberBot - Core Bot Instance ### Description The `ViberBot` class is the main entry point for creating a Viber bot. It handles webhook registration, incoming request processing, message sending, and event listener registration. All operations are thread-safe and can be called from multiple threads concurrently. ### Method Initialization and configuration are done via constructor and methods. Event handling is done via listener registration. ### Endpoint N/A (Library usage, not a specific endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.viber.bot.api.ViberBot; import com.viber.bot.profile.BotProfile; import com.viber.bot.message.TextMessage; import com.viber.bot.Request; import com.google.common.util.concurrent.Futures; import java.util.Optional; // Initialize the bot with profile and auth token ViberBot bot = new ViberBot( new BotProfile("MyBot", "https://example.com/avatar.jpg"), "YOUR_AUTH_TOKEN_HERE" ); // Register webhook (HTTPS required with valid SSL certificate) bot.setWebhook("https://your-server.com/webhook").get(); // Handle incoming messages - echo back any received message bot.onMessageReceived((event, message, response) -> { String senderName = event.getSender().getName(); System.out.println("Received message from: " + senderName); response.send(message); // Echo the message back }); // Handle conversation started - send welcome message bot.onConversationStarted(event -> Futures.immediateFuture( Optional.of(new TextMessage("Welcome " + event.getUser().getName() + "!")) )); // Process incoming webhook request (in your web server handler) // String json = // ... JSON from HTTP POST body // InputStream responseStream = bot.incoming(Request.fromJsonString(json)).get(); ``` ### Response #### Success Response (200) N/A (Library methods return Futures or void) #### Response Example N/A ``` -------------------------------- ### Set Webhook for Viber Bot (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/index-files/index-14.html Configures the webhook URL for the Viber bot. The URL must start with HTTPS and have a valid SSL certificate. This method allows specifying which events the bot should receive notifications for. ```java ViberBot.setWebhook(String url); ViberBot.setWebhook(String url, List events); ``` -------------------------------- ### Get Viber Bot Profile (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Returns the profile information for the Viber bot. This method directly returns a BotProfile object containing details about the bot. It does not involve asynchronous operations or exception handling for API errors. ```java public com.viber.bot.profile.BotProfile getBotProfile() ``` -------------------------------- ### Message Class Overview Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/Message.html Provides an overview of the abstract Message class, its direct known subclasses, and its methods. ```APIDOC ## Class Message * java.lang.Object * com.viber.bot.message.Message * Direct Known Subclasses: * [ContactMessage](contact-message.html) * [FileMessage](file-message.html) * [LocationMessage](location-message.html) * [PictureMessage](picture-message.html) * [RichMediaMessage](rich-media-message.html) * [StickerMessage](sticker-message.html) * [TextMessage](text-message.html) * [UrlMessage](url-message.html) * [VideoMessage](video-message.html) @Immutable public abstract class Message extends java.lang.Object ### Method Summary * **`boolean`** `equals(java.lang.Object o)` * **`MessageKeyboard`** `getKeyboard()` * **`java.util.Map`** `getMapRepresentation()` * **`TrackingData`** `getTrackingData()` * **`java.lang.String`** `getType()` * **`int`** `hashCode()` ### Methods inherited from class java.lang.Object `getClass, notify, notifyAll, toString, wait, wait, wait ``` -------------------------------- ### Location Class Documentation Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/Location.html This section details the Location class, its constructors, and methods for accessing and managing geographical coordinates. ```APIDOC ## Class Location ### Description Represents a geographical location with latitude and longitude. ### Constructor #### `Location(float latitude, float longitude)` * **latitude** (float) - The latitude of the location. * **longitude** (float) - The longitude of the location. ### Methods #### `getLatitude()` * **Returns**: (float) - The latitude of the location. #### `getLongitude()` * **Returns**: (float) - The longitude of the location. #### `equals(Object o)` * **Description**: Compares this Location object with another object for equality. * **Parameters**: * **o** (Object) - The object to compare with. * **Returns**: (boolean) - `true` if the objects are equal, `false` otherwise. #### `hashCode()` * **Description**: Returns a hash code value for the Location object. * **Returns**: (int) - A hash code value for this object. ``` -------------------------------- ### FileMessage Getters - Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/FileMessage.html Provides methods to retrieve the properties of a FileMessage object. These include getting the file's URL, its size in bytes, and its filename. These methods are essential for accessing the details of a file message. ```java public java.lang.String getUrl() public int getSizeInBytes() public java.lang.String getFilename() ``` -------------------------------- ### Get Viber User Details (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Retrieves the details of a specific Viber user using their user ID. This method returns a ListenableFuture that resolves to an ApiResponse, which may contain an ApiException if an error occurs. The userId can be obtained from UserProfile.getId(). ```java public com.google.common.util.concurrent.ListenableFuture getUserDetails(@Nonnull java.lang.String userId) ``` -------------------------------- ### VideoMessage Class Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/VideoMessage.html Details about the VideoMessage class, including its constructors and methods for creating and managing video messages. ```APIDOC ## VideoMessage Class ### Description Represents a video message that can be sent through the Viber Bot API. It includes properties such as URL, size, text, thumbnail, duration, and optional keyboard and tracking data. ### Constructors #### `VideoMessage(String url, int size, String text, String thumbnail, Integer duration)` Constructs a `VideoMessage` with the specified URL, size, text, thumbnail, and duration. #### `VideoMessage(String url, int size, String text, String thumbnail, Integer duration, MessageKeyboard keyboard, TrackingData trackingData)` Constructs a `VideoMessage` with the specified URL, size, text, thumbnail, duration, keyboard, and tracking data. ### Methods #### `getUrl()` Returns the URL of the video. - **Returns**: `String` - The video URL. #### `getSize()` Returns the size of the video in bytes. - **Returns**: `int` - The video size. #### `getText()` Returns the text associated with the video message. - **Returns**: `String` - The message text. #### `getThumbnail()` Returns the URL of the video thumbnail. - **Returns**: `String` - The thumbnail URL. #### `getDuration()` Returns the duration of the video in seconds. - **Returns**: `Optional` - An optional containing the video duration if set. #### `equals(Object o)` Compares this `VideoMessage` object with another object for equality. - **Parameters**: - **o** (`Object`) - The object to compare with. - **Returns**: `boolean` - `true` if the objects are equal, `false` otherwise. #### `hashCode()` Returns a hash code value for the `VideoMessage` object. - **Returns**: `int` - The hash code value. ``` -------------------------------- ### IncomingSeenEvent Methods (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/incoming/IncomingSeenEvent.html Provides the method signatures for retrieving user ID and token from an IncomingSeenEvent. It also includes overridden equals and hashCode methods for object comparison. ```java public java.lang.Long getToken() public java.lang.String getUserId() public boolean equals(java.lang.Object o) public int hashCode() ``` -------------------------------- ### Get Bot Profile - ViberBot Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Returns the BotProfile object associated with this ViberBot instance. The BotProfile contains essential information about the bot, such as its name, avatar, and webhook URL. This method is synchronous and directly returns the profile object. ```java BotProfile getBotProfile() ``` -------------------------------- ### BotProfile Class Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/profile/BotProfile.html Documentation for the BotProfile class, which represents a bot's profile information. ```APIDOC ## BotProfile Class ### Description Represents a bot's profile information, including its name and optional avatar. ### Class `com.viber.bot.profile.BotProfile` ### Constructors #### BotProfile(String name) * **Description**: Constructs a BotProfile with the given name. * **Parameters**: * `name` (String) - Required - The name of the bot. #### BotProfile(String name, String avatar) * **Description**: Constructs a BotProfile with the given name and avatar URL. * **Parameters**: * `name` (String) - Required - The name of the bot. * `avatar` (String) - Optional - The URL of the bot's avatar. ### Methods #### getName() * **Description**: Returns the name of the bot. * **Return Type**: String #### getAvatar() * **Description**: Returns the avatar URL of the bot. * **Return Type**: String (Nullable) #### equals(Object o) * **Description**: Compares this BotProfile to another object for equality. * **Overrides**: `equals` in class `java.lang.Object` * **Parameters**: * `o` (Object) - The object to compare with. * **Return Type**: boolean #### hashCode() * **Description**: Returns a hash code value for this BotProfile. * **Overrides**: `hashCode` in class `java.lang.Object` * **Return Type**: int ``` -------------------------------- ### Send Messages (Varargs) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/Response.html Allows sending multiple messages to a user using varargs. This is a shorthand for ViberBot.sendMessage with a pre-set UserProfile. ```APIDOC ## POST /viber/send/messages/varargs ### Description Sends multiple messages to a user using varargs. This method is a shorthand for `ViberBot.sendMessage(UserProfile, Message...)` where the `UserProfile` is already set. ### Method POST ### Endpoint /viber/send/messages/varargs ### Parameters #### Request Body - **messages** (Message...) - Required - A variable number of messages to be sent. ### Response #### Success Response (200) - **messageTokens** (Collection) - A collection of message tokens as strings. #### Response Example ```json { "messageTokens": [ "token1", "token2" ] } ``` #### Error Response - **ApiException** - Thrown if there is an error sending the messages. ``` -------------------------------- ### Viber Bot Event Enum Definition (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/event/Event.html Defines the Event enum for the Viber bot Java library. This enum represents various event types such as message received, message sent, conversation started, and more. It implements Serializable and Comparable interfaces. ```java public enum Event extends java.lang.Enum { CONVERSATION_STARTED, ERROR, MESSAGE_DELIVERED, MESSAGE_RECEIVED, MESSAGE_SEEN, MESSAGE_SENT, SUBSCRIBED, UNSUBSCRIBED, WEBHOOK; // Methods for valueOf and values are typically generated by the compiler // and a method to get the server event name is also present. public java.lang.String getServerEventName() { // Implementation details omitted for brevity return ""; } public static com.viber.bot.event.Event valueOf(java.lang.String name) { // Implementation details omitted for brevity return null; } public static com.viber.bot.event.Event[] values() { // Implementation details omitted for brevity return null; } } ``` -------------------------------- ### RichMediaMessage Constructors - Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/RichMediaMessage.html These constructors are used to create instances of RichMediaMessage. The first constructor allows for detailed configuration including a RichMediaObject, alternative text, minimal API version, an optional keyboard, and tracking data. The second constructor provides a simpler way to initialize with a RichMediaObject, alternative text, and minimal API version. ```java public RichMediaMessage(@Nonnull RichMediaObject richMediaObject, @Nullable String alternativeText, @Nullable Integer minimalApiVersion, @Nullable MessageKeyboard keyboard, @Nullable TrackingData trackingData) ``` ```java public RichMediaMessage(@Nonnull RichMediaObject richMedia, String alternativeText, Integer minimalApiVersion) ``` -------------------------------- ### StickerMessage Constructors (Java) Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/message/StickerMessage.html Provides constructors for creating StickerMessage objects. The first constructor initializes a StickerMessage with a sticker ID. The second constructor allows for additional parameters like a MessageKeyboard and TrackingData for more complex message configurations. ```java public StickerMessage(long stickerId) ``` ```java public StickerMessage(long stickerId, @Nullable MessageKeyboard keyboard, @Nullable TrackingData trackingData) ``` -------------------------------- ### Get User Details - ViberBot Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Retrieves detailed information about a specific Viber user. This method takes a user ID as input and returns a ListenableFuture that will eventually contain an ApiResponse with the user's details. It's useful for personalizing interactions. ```java com.google.common.util.concurrent.ListenableFuture getUserDetails(java.lang.String userId) ``` -------------------------------- ### Request Handling API Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/Request.html This section details the methods for managing incoming requests, including checking their status and retrieving response data. ```APIDOC ## Request Handling API ### Description Provides methods to check the status of a request and retrieve its associated response data. ### Method N/A (These are class methods for request object manipulation) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ## Methods ### `isClosed()` #### Description Checks if the request has been closed. #### Method `boolean` #### Endpoint N/A ### `setResponse(String response)` #### Description Sets a string response for the request. #### Method `void` #### Parameters * **response** (String) - Required - The string to set as the response. #### Endpoint N/A ### `setResponse(InputStream inputStream)` #### Description Sets an InputStream as the response for the request. The InputStream will not be closed by this method. #### Method `void` #### Parameters * **inputStream** (InputStream) - Required - The InputStream to set as the response. #### Endpoint N/A ### `getResponseInputStream()` #### Description Retrieves the response as an InputStream. This may be null if no response has been set or if the response is not an InputStream. #### Method `InputStream` #### Endpoint N/A ### `close()` #### Description Closes the request, releasing any associated resources. This method is specified by `java.io.Closeable` and `java.lang.AutoCloseable`. #### Method `void` #### Throws * `java.io.IOException` - If an I/O error occurs during closing. #### Endpoint N/A ``` -------------------------------- ### Get Online Status - ViberBot Java Source: https://github.com/viber/viber-bot-java/blob/master/docs/com/viber/bot/api/ViberBot.html Fetches the online status for a collection of Viber user IDs. This method returns a ListenableFuture that resolves to an ApiResponse containing the online status information for each requested user. It requires a collection of user IDs as input. ```java com.google.common.util.concurrent.ListenableFuture getOnlineStatus(java.util.Collection userIds) ```