Skip to content

About

Java client for the Bot API of Dialog, the private messenger

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dialog-bot (Java)

Java client for the Bot API of Dialog, the private messenger. Send yourself (or anyone who starts your bot) a notification from a program, a server or a scheduled job: text, pictures and buttons.

  • No dependencies, Java 11+.
  • A bot writes only to people who started it, and stops when they stop it.
  • The bot never learns who it is talking to: a chat id is random and different for every bot.

Install

Gradle:

implementation 'pm.dialog.app:dialog-bot:0.1.0'

Maven:

<dependency>
  <groupId>pm.dialog.app</groupId>
  <artifactId>dialog-bot</artifactId>
  <version>0.1.0</version>
</dependency>

Create a bot

In the Dialog app: Settings → Bots → New bot. You get a token and a public link (dialog.pm/@your_bot). Open the link, press Start, and the chat id appears in the list of subscribers.

Send a message

import pm.dialog.bot.*;

DialogBot bot = new DialogBot("TOKEN");
bot.sendMessage("CHAT_ID", "Backup finished");

Pictures and buttons:

bot.sendPhoto("CHAT_ID", Path.of("door.jpg"), new SendOptions()
        .caption("*Motion at the door*")
        .row(Button.callback("Ignore", "ignore"), Button.link("Live view", "https://example.org/cam")));

Answer people

bot.poll(update -> {                          // long polling, forever
    if (update.message() != null) {
        bot.sendMessage(update.message().chatId(), "You said: " + update.message().text());
    } else if (update.callbackQuery() != null) {
        bot.sendMessage(update.callbackQuery().chatId(), "You pressed " + update.callbackQuery().data());
    } else if (update.isChatStopped()) {
        System.out.println("stopped by " + update.chatId());
    }
});

poll confirms each update once the handler returned, retries network errors and throws when the server refuses the bot.

Commands offered after / in the chat:

bot.setMyCommands(List.of(new Command("status", "How things are")));

Errors

A call that fails throws DialogException with status(), code() and, when the server gives one, a reason():

reason() Meaning
bot_stopped The user stopped the bot (e.isStopped()). Do not write to this chat until it sends /start again.
chat_not_found Not a chat of this bot.
bot_disabled The server operator switched the bot off.

A 429 carries retryAfter(). status() is 0 when the server could not be reached. Exception messages never contain the token.

Another server

Dialog can be self-hosted:

DialogBot bot = new DialogBot("TOKEN", "https://chat.example.org");

Good to know

Messages exchanged with bots are not end-to-end encrypted: the bot's program and the server can read them. Everything else in Dialog is.

License

MIT

About

Java client for the Bot API of Dialog, the private messenger

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages