DEV Community

Cover image for Building a JAVA Telegram Bot and Deploying in heroku
VINU
VINU

Posted on • Updated on • Originally published at vinuxd.me

Building a JAVA Telegram Bot and Deploying in heroku

Overview

Here we are going to use Spring Boot Maven to Build a JAVA Telegram bot which (echoes) sends back the received text message to the user. Then we are going to deploy our bot on Heroku.
Let's get in by assuming you have a basic knowledge in Java.


Prerequisites

  • A Code Editor
  • JDK 11 or more
  • Patience and Time.

Initializing our code

  • First things first, Go to the following link which points to Spring Initializr's official webpage and download the premade configuration I made to initialize our project.
  • Unzip the downloaded file to your preffered location.
  • Open your preferred code editor and hit Import existing project.

Adding dependencies

  • Find a file named pom.xml in the root of your project. Open the file and add the following dependencies.
  • If you look carefully you can see the following tags in our pom.xml file.
<dependencies>

  </dependencies>
Enter fullscreen mode Exit fullscreen mode
  • And that's the right place to add our dependencies.
  • We are going to use Rubenlagus TelegramBots library to build our bot.
  • Add the following contents in the <dependencies> section.
<dependencies>

     <dependency>
       <groupId>org.telegram</groupId>
       <artifactId>telegrambots-spring-boot-starter</artifactId>
       <version>5.7.1</version>
    </dependency>

</dependencies>
Enter fullscreen mode Exit fullscreen mode
  • Save and Update the project by using Shift+Alt+U or with the Sync button and we are done adding dependencies.

Declaring Env Variables

  • To make our bot work we need to declare some environmental variables.
  • Here we are going to add two mandatory variables named,
    • BOT_TOKEN
    • BOT_USERNAME
  • Since it was a Spring Boot application, We need to add a variable named,
    • PORT
  • Navigate to src\main\resources and rename application.properties to applicaton.yml and add the following variables.
bot:
  BOT_TOKEN: <Super_Secret_Token_Here>
  BOT_USERNAME: <ExampleBot>
server:
  PORT: 5000
Enter fullscreen mode Exit fullscreen mode

Programming Part

  • Navigate to src/main/java/com/echobot/echobotexample.
  • You can see there will be a file named EchobotexampleApplication.java and thats the main class of our project. Leave the file as it is.
  • Create a class file named EchoBot.javain the same directory and that's the actual bot class.

Things to do

  • Importing Packages
  • Getting Variables
  • getBotToken() method
  • getbotUsername() method
  • onUpdateReceived() method
  • Procfile

Importing Packages

  • Lets import the necessary packages and make our EchoBot class extending TelegramLongPollingBot. (We aren't using Webhook here)
// Defining Package name
package com.echobot.echobotexample;

// @Value annotation
import org.springframework.beans.factory.annotation.Value;
// @Component annotation
import org.springframework.stereotype.Component;
// LongPollingBot class
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
// Update Method
import org.telegram.telegrambots.meta.api.objects.Update;
// SendMessage method
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;

@Component
class EchoBot extends TelegramLongPollingBot {

}
Enter fullscreen mode Exit fullscreen mode

Getting Variables

  • We are going to get the BOT_TOKEN and BOT_USERNAME from application.yml to our java file.
String BOT_TOKEN;
String BOT_USERNAME;

EchoBot(@Value("${bot.BOT_TOKEN}") String BOT_TOKEN, @Value("${bot.BOT_USERNAME}") String BOT_USERNAME) {
        this.BOT_TOKEN = BOT_TOKEN;
        this.BOT_USERNAME = BOT_USERNAME;
    }
Enter fullscreen mode Exit fullscreen mode

Returning Token and Username

  • To make our bot work we need to return the BOT_TOKEN and BOT_USERNAME from the getBotToken() and getbotUsername() methods.
  • And It is necessary to @Override these getBotToken() and getBotUsername() methods.
    @Override
    public String getBotToken() {
        return BOT_TOKEN;
    }

    @Override
    public String getBotUsername() {
        return BOT_USERNAME;
    }
Enter fullscreen mode Exit fullscreen mode

Actual Bot

  • After a long time of coding we are now ready to code our actual bot.
  • So, lets create a method named onUpdateReceived() with Update update as a parameter and @Override it.
  • As we know, Our bot will echo back the received text message.
  • Lets Start with the following code.
// onUpdateReceived method
@Override
public void onUpdateReceived(Update update) {
  // Checking if the update has message and it has text
  if (update.hasMessage() && update.getMessage().hasText()) {
      // Creating object of SendMessage
      SendMessage message = new SendMessage();
      // Setting chat id
      message.setChatId(update.getMessage().getChatId().toString());
      // Setting reply to message id
      message.setReplyToMessageId(update.getMessage().getMessageId());
      // Getting and setting received message text
      message.setText(update.getMessage().getText());
      try {
        // Sending message
        execute(message);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  • And Thats it! Programming part is finished!

Procfile

  • Since We are deploying in Heroku, We need a Procfile to tell How to Build and Run our app.
  • We are going to create this file in root of our project.
  • The Procfile should look something like this,
worker: java -Dserver.port=$PORT $JAVA_OPTS -jar target/*.jar
Enter fullscreen mode Exit fullscreen mode
  • Now We are ready to deploy our bot in cloud.

Deployment

  • If you are new to this, Learn more from official docs.
  • So, Lets start by creating a heroku account.
  • Go to dashboard and Click Create new app.
  • Navigate to Deploy panel and Connect Github.
  • Search for your repository and Click enter.
  • On Manual Deploy section, Select the Branch and click Deploy.
  • The most awaited final results are comming!
  • Go to LOGS and Wait until Build finishes.
  • If things gone good? Sit back and relaxx.
  • Then go to your telegram bot and send any text and watch it echo back.

Conclusion

  • So, In this blog we developed and deployed a Java telegram bot.
  • And Guess What? The example I used here is Open Source! You can get the whole source code in Github. Click me to grab and don't forgot to ⭐
  • In case of any errors, Please Open a issue on Github.
  • Still having doubts? Feel free to reach me in Telegram.

Top comments (5)

Collapse
 
renanfranca profile image
Renan Franca

Thank you for sharing this ☺. Spring boot is fantastic! I am interested in the subject of chatbots, but here in Brazil Whatsapp is more popular than telegram. Do you know how to do the same thing for WhatsApp?

I appreciate the open source move, I gave my ⭐! Son I will share a open source project too!

Collapse
 
vinuxd profile image
VINU • Edited

Thanks Renan! I'm glad you liked it 🥳!
So, I researched about WhatsApp bots and found a Java lib which interacts with WhatsApp api and it was pretty similar to telegram. Soon I will post a blog about whatsapp bots using java.

Thanks for sharing 💪❤️

Collapse
 
renanfranca profile image
Renan Franca

Wow 🤩!!!
Thank you for take the time to take a look on Whatsapp bot! Much better that you going to create new post about it!!! Keep up!!!

I am going to be waiting here 😆

Collapse
 
adityaprasad502 profile image
Aditya Prasad S • Edited

Wew, Nice 🌝

Collapse
 
vinuxd profile image
VINU

🥳❤️