How to create a Telegram bot using java?

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

Get API Token

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.

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

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?

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_

👦 CSE Student| Flutter, Java ❤️ | Open Source Enthusiast | Mobile app Developer | Freelancer | Content Creator |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store