Building a JAVA Telegram Bot and Deploying in heroku
Tags: java, telegrambot, heroku, spring
Published: 2022-03-05 08:07:43


## 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
  - [VSCode](https://vscode.dev?ref=vinuxd.github.io) or [Eclipse](https://eclipse.org/ide?ref=vinuxd.github.io)
- JDK 11 or more
- Patience and Time.

## Initializing our code

- First things first, Go to the following link which points to [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.6.4&packaging=jar&jvmVersion=11&groupId=com.echobot&artifactId=echobotexample&name=echobotexample&description=Simple%20Echo%20Bot%20in%20JAVA&packageName=com.echobot.echobotexample)'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.

```xml
<dependencies>

  </dependencies>
```

- And that's the right place to add our dependencies.
- We are going to use Rubenlagus [TelegramBots](https://github.com/Rubenlagus/TelegramBots) library to build our bot.
- Add the following contents in the `<dependencies>` section.

```xml
<dependencies>

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

</dependencies>
```

- 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.

```yml
bot:
  BOT_TOKEN: <Super_Secret_Token_Here>
  BOT_USERNAME: <ExampleBot>
server:
  PORT: 5000
```

## 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.java `in 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)

```java
// 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 {

}
```

### Getting Variables

- We are going to get the `BOT_TOKEN` and `BOT_USERNAME` from `application.yml` to our java file.

```java
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;
    }
```

### 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.

```java
    @Override
    public String getBotToken() {
        return BOT_TOKEN;
    }

    @Override
    public String getBotUsername() {
        return BOT_USERNAME;
    }
```

### 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.

```java
// 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();
    }
  }
}
```

- 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,

```yml
worker: java -Dserver.port=$PORT $JAVA_OPTS -jar target/*.jar
```

- Now We are ready to deploy our bot in cloud.

## Deployment

- If you are new to this, Learn more from [official docs](https://docs.heroku.com?ref=vinuxd.github.io).
- 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](https://github.com/VinuXD/EchoBot-Example) and don't forgot to :star:
- In case of any errors, Please [Open a issue on Github](https://github.com/VinuXD/EchoBot-Example/issues).
- Still having doubts? Feel free to reach me in [Telegram](https://t.me/VINUsChat).