How to create a Telegram bot using java?

Viral Vaghela
3 min readDec 22, 2020

--

Hello developers, in this post I will explain to you How you can create a telegram bot using java?

Get API Token

So first Go to the telegram and search Bot Father.

Bot father is used to creating a bot, manage existing bots, changes settings, and delete a bot.

You have to enter the of your bot, and it’s always unique. after creating the bot you will get API Token (Do not share this with anyone).

Create a Java Maven Project.

Open your IDE and create a Java Maven project.

in the pom.xml add the java-telegram-bot-API dependency.

Now create a MainClass and inside main() method write following code to create an object of your MyBot class and register it and then create a MyBot.Java

MyBot class will extend TelegramLongPollingBot.

Now you have to implement methods

@Override
public void onUpdateReceived(Update update) {

}

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

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

Add token and username

Inside getBotUserName( ) replace null with the name of your Bot and paste your token in the return statement of getBotToken( ).Get a message from the Bot

When the user sends a message to the bot, it will receive in the onUpdateReceived( ),

to print the message on the console you can write the following code

System.out.println(update.getMessage().getText());

How to Send Message to the user?

Create a object of SendMessage

SendMessage sendMessage = new SendMessage();sendMessage.setText("Hii ") 
try {
sendMessage.setChatId(update.getMessage().getChatId());
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}

inside the setText( ), you can write your message. and set Chat ID using setChatID()

execute() will send a message to the user, don’t forget to write this code inside the try-catch block, because it may throw an exception.

I have created a telegram bot, which will show you live CORONA global data, bot send you coding jokes and FREE resources to learn programming languages, web development, android development, ethical hacking, and much more.

You can use my Bot Click here

Source Code of this bot is available on my GitHub repo you can download it and use it, just change your API TOKEN.

https://github.com/viralvaghela/Telegram-Bot-Array-Index-Out-Of-Bound

If you have any questions Feel free to ask in the comment and follow me on Instagram for daily amazing posts on coding, app development, and backend dev.

https://instagram.com/coding_boy_

--

--

Viral Vaghela

𝐒𝐞𝐜𝐮𝐫𝐢𝐭𝐲 Researcher • Software Developer •