Simple Echo Bot

... by Bittle in Java Telegram Bot April 13, 2019

Before starting we need to contact @BotFather to receive a bot token.

Library

We have to install Ruben's library in able to communicate with Telegram servers easily. You can install TelegramBots library with different methods:

  • Using Maven:
<dependency>
 <groupId>org.telegram</groupId>
 <artifactId>telegrambots</artifactId>
 <version>Latest</version>
</dependency>
  • Using Jitpack
  • Or download .jar file with dependencies from here


Importing jar file in intelliJ

Download telegrambots-v.v-jar-with-dependencies.jar (4.1 for me)

Create a folder lib in your project root directory and place the jar file in it. Then import it.


Coding

Once you install the library we can start on the fun part! We are going to make a bot that sends back what you message it. Open Intellij and create a new project. Under your src folder create 2 new files: Main.java and KodeCentralBot.java. Lets write our bot code:

import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

public class KodeCentralBot extends TelegramLongPollingBot {
    @Override
    public void onUpdateReceived(Update update) {
        // TODO
    }

    @Override
    public String getBotUsername() {
        // Return bot username
        // If bot username is @KodeCentralBot, it must return 'KodeCentralBot'
        return "KodeCentralBot";
    }

    @Override
    public String getBotToken() {
        // Return bot token from BotFather
        return "someLongStringHere";
    }
}

getBotToken() and getBotUsername() must be the credentials received from @BotFather. Now let's move to the bot logic. We want to "echo" every message we send it. We need to place that code in onUpdateRecieved() since this method is called when an update is received from a user:

@Override
public void onUpdateReceived(Update update) {

    // We check if the update has a message and the message has text
    if (update.hasMessage() && update.getMessage().hasText()) {
        // Set variables
        String message_text = update.getMessage().getText();

        // id from sent message (will use to send back the message)
        long chat_id = update.getMessage().getChatId();

        SendMessage message = new SendMessage() // Create a message object
                .setChatId(chat_id)
                .setText(message_text);
        try {
            execute(message); // Sending our message object to user
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

Now we need to run the Bot. Go to Main.java and initialize Api Context, initialize Telegram Bots Api, and register our bot:

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

        // Instantiate Telegram Bots API
        TelegramBotsApi botsApi = new TelegramBotsApi();

        // Register our bot
        try {
            botsApi.registerBot(new KodeCentralBot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}


Files

Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

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

        // Instantiate Telegram Bots API
        TelegramBotsApi botsApi = new TelegramBotsApi();

        // Register our bot
        try {
            botsApi.registerBot(new KodeCentralBot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}


KodeCentralBot.java
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

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

        // We check if the update has a message and the message has text
        if (update.hasMessage() && update.getMessage().hasText()) {
            // Set variables
            String message_text = update.getMessage().getText();

            // id from sent message (will use to send back the message)
            long chat_id = update.getMessage().getChatId();

            SendMessage message = new SendMessage() // Create a message object
                    .setChatId(chat_id)
                    .setText(message_text);
            try {
                execute(message); // Sending our message object to user
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getBotUsername() {
        // Return bot username
        // If bot username is @KodeCentralBot, it must return 'KodeCentralBot'
        return "KodeCentralBot";
    }

    @Override
    public String getBotToken() {
        // Return bot token from BotFather
        return "token";
    }
}


Run the program and message the bot. PROFIT!


To make the bot better continue reading on!

Comments (0)

Search Here