Hello Bot — or how to write a Telegram bot in Java

Riccardo Zanchi
4 min readSep 26, 2020

(let’s all pretend that here there’s a funny, smartass introduction and thanks to it you figure me as a very nice person).

Connect to telegram (using the mobile app or the desktop app or the web app) and search for the BotFather. Then, start it.

Just for the image and the name, I give them 10/10

Launch the command /newbot and follow the instructions, providing a name and a username for your bot. The name can be anything you want, this will be the name shown in the Telegram chat. The username, on the other hand, should be a unique identifier, so if someone already used your best bot name, you should find another one. Is a First Come, First Served world, darling.

Say my username

When, after hours, maybe days of trying, you finally found a suitable username for your bot, the BotFather will provide you a unique token to access the APIs. Needless to say, but the token is very important, it will gave complete access and control to your bot, so, keep it safe (and warm). In this example, I’m not going to hide the token because the bot will be deleted soon.

I’m gonna make him a token he can’t refuse

Using the link provided by the BotFather, t.me/BOT_USERNAME, you can reach your beautiful, empty, useless bot:

We need to find a way to break the ice with this bot

Now we can start coding, finally. Open your preferred IDE (just consider that if you don’t use Intellij I will not accept your friend request) and download the dependencies (I’ve used Maven).

<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>4.9.1</version>
</dependency>

Create a new Java class and make it extends the abstract class TelegramLongPollingBot. This class provides three abstract methods:

  • onUpdateReceived: it handles the messages received by the bot (i.e. what you write in the bot);
  • getBotUsername: returns the name associated to the bot. In fact, it returns any string you provide;
  • getBotToken: it will returns the token associated with the bot and it will be used to register our application to Telegram API.

Pay attention that in fact there is another method that you could implement: onUpdatesReceived. It is very similar to the method described above, with the difference that this method accepts an array of Update objects, but more important, if you implement both the *Received methods, this one will be the one called.

public class HelloJavaBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {

}

@Override
public String getBotUsername() {
return null;
}

@Override
public String getBotToken() {
return null;
}
}

We can easily fill the get* methods, providing the username of our bot (or any string you like) and the token received by the BotFather:

public String getBotUsername() {
return "HelloJavaBot";
}

public String getBotToken() {
return "1292346644:AAFl48xURKWaSSKnK7xg4hdgTgWnGbguqFI";
}

Now, we’ll implement our bot as a simple “parrot bot”: it will answer to any received message with the message itself.

public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
String messageText = update.getMessage().getText();

long chatId = update.getMessage().getChatId();

SendMessage sendMessage = new SendMessage()
.setChatId(chatId)
.setText(messageText);

try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}

The code is quite self-explanatory:

  1. first we check that there is a message with text
  2. then we retrieve the ID of the chat we are currently responding
  3. we create a new SendMessage object setting ID and text
  4. We call the execute method

Last thing to do, is to create the entry point of our bot:

public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();

TelegramBotsApi telegramBotsApi = new TelegramBotsApi();

try {
telegramBotsApi.registerBot(new HelloJavaBot());

} catch (TelegramApiRequestException e) {
e.printStackTrace();
}
}
}

Again, is very easy to understand the code above:

  1. We initialize the Telegram APIs
  2. We create the main object to handle the requests
  3. we register our HelloJavaBot class to the handler.

Done. Your bot is ready to be “botted”. Start the application and then try to talk to you bot.

It’s getting bot in here

For any detail, RTFM (https://core.telegram.org/bots/api)

--

--