Building Bot. Part three: Creating Telegram bot

I continue to write about telegram bot which I going to create. This time I’ll tell about initial steps, required to create Telegram bot using Java. First of all, we need to create a bot, let’s do it. There is a funny way to create it, using another bot, called Bot Father. Install it, the process is really straightforward and if you have any problems, I encourage you to look through the official documentation. At this moment you should have bot username and token, so now, let’s create Java application. There is official Java library to create bots and this is good news for us. Let’s add it as a dependency. I use gradle, so just add compile 'org.telegram:telegrambots:2.4.0' to my dependencies.

Now create new class for bot and extend it from TelegramLongPollingBot . This means that this bot asks for messages itself. There is another option – TelegramWebhookBot, which calls your bot on event, when the message arrives. There are some requirements which your server should apply, so let’s just proceed with Long Polling.

There are three methods to implement, so let’s do it to make bot send the same message as it receives. Here is what you about to have:

public class RecipeBot extends TelegramLongPollingBot {
  @Override
  public void onUpdateReceived(Update update) {
    if(update.hasMessage() && update.getMessage().hasText()){
      sendResponse(update.getMessage().getText(), update.getMessage().getChatId().toString());
    }
  }

  @Override
  public String getBotUsername() {
    return "BotUsername";
  }

  @Override
  public String getBotToken() {
    return "TOKEN";
  }

  private void sendResponse(String r, String chatID){
    SendMessage sendMessageRequest = new SendMessage();
    sendMessageRequest.setChatId(chatID);
    sendMessageRequest.setText(r);

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

Now you have the working bot which just echoes incoming messages. It is good practice to override standard commands /start and /help to control what your bot says. To do this, add this inside your update.hasMessage if

if (message.isCommand()){
  String command = message.getEntities().get(0).getText();
  if(command.equalsIgnoreCase(START_COMMAND)){ // "/start" string
    sendResponse("Hi, Nice to meet you!" , message.getChatId().toString());
  }
}

Now you bot will say hello when it first time added.

This is all steps to create simple telegram bot. Next time I’ll add more complexity and will tell about searching recipes with MongoDB