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.
Import the library to your project using jitpack repository
- Add the JitPack repository to your build file
repositories {
...
maven { url 'https://jitpack.io' }
}
- 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
- Create ViberBot instance with bot name and auth token
- Start callback server to receive webhook requests
- Register webhook url in Viber API
- Add message listener to handle incoming events
- 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()
.
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()));
}
});
}
}
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.
This library is released under the terms of the Apache 2.0 license. See License for more information.