### 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