Skip to content

galimru/viber-bot

Repository files navigation

Viber Bot for Java ☕️

Build Status Release License

Use this library to develop a bot for the Viber platform. The official Viber Bot library for java is deprecated so I recommend to use this library instead of official.

Installation

Import the library to your project using jitpack repository

Gradle

  1. Add the JitPack repository to your build file
repositories {
    ...
    maven { url 'https://jitpack.io' }
}
  1. Add the Viber Bot library dependency
implementation 'com.github.galimru:viber-bot:2.0.0'

Note: The JitPack supports both Gradle/Maven build tools, please refer to jitpack documentation if you want use Maven

Usage

  1. Create ViberBot instance with bot name and auth token
  2. Start callback server to receive webhook requests
  3. Register webhook url in Viber API
  4. Add message listener to handle incoming events
  5. Use sendMessage method to send any type of message

You also can use own webserver to receive webhook requests. In that case, you will have to transform json body to IncomingEvent object using jackson library and provide this object to method ViberBot#handle().

Creating an echo bot 🤖

In this example we use ngrok to have external url pointed to local machine on port 8080.

public class Example {

    public static void main(String[] args) throws IOException {
        ViberBot viberBot = new ViberBot("My Bot", "<AUTH_TOKEN>");
        // start server on 8080 port with path /callback
        viberBot.listen("/callback");
        // let Viber API know about webhook url
        viberBot.setWebhook("https://16063f37.ngrok.io/callback");
        // subscribes on message events 
        viberBot.addMessageListener((event, response) -> {
            Message message = event.getMessage();
            if (message.getType() == MessageType.TEXT) {
                TextMessage textMessage = (TextMessage) message;
                // send message back to user
                viberBot.sendMessage(message.getSender().getId(), 
                        new TextMessage().setText("echo " + textMessage.getText()));
            }
        });
    }
}

Limitations

Currently, the library doesn't support SSL termination on callback server. It means you will have to use another webserver behind callback server which supports SSL configuration. The Viber API requires to use HTTPS for webhook addresses.

Links

License

This library is released under the terms of the Apache 2.0 license. See License for more information.