Telegram Bot in JAVA

Naveen Kumar M N
3 min readMar 29, 2021

App stores are filled with hundreds of Instant Messaging 📝apps and services but Telegram stands out with its huge Bot Collection ranging from Weather to Movie Update bots. It’s time to build one in Java.

Photo by Christian Wiediger on Unsplash

Hello-World! 🔥

After scratching my head for 2 long minutes I decided to develop the sacred Hello-World bot which would greet the user with a username.

Check out the complete GitHub code. 💻

Bot-Father ✋

Search for BotFather in search and send the /start command.

Next /newbot command will create new bot and will ask for name for it.

If the name of the bot is unique, next we will be provided with the access token.

Its Maven Time ⏰

Create a simple maven project and add Telegram-Bot and Logging jars to it. Checkout Telegram Bots repo for the latest jars.

Bot Session and TelegramLongPollingBot 🌎

Create a new bot session with Default Bot Session class which would configure the listener so that it handles the token, callBack, and state of App.

Extend a class with TelegramLongPollingBot by implementing the following methods.

onUpdateReceived() would be called when an user sends a message or command to the bot, getBotUsername() returns the name of the bot and getBotToken() returns the token.

Update Object 🍧

This object holds the message along with user details and we can send message based on it.

If the message from the user is of type /hello we log it and create a new SendMessage object which can be used to respond back. 💁 Every user is Identified with a chat Id which are fetched from the Update Object. Finally the execute method would send the message back to the user.

Run the main method and we have the bot. The updates would be flooded with messages if the user sends commands when the bot is not running or offline and will be processed once its online(running). Finally we can package it as jar and host the same. I run all my bots as service in Raspberrypi 4. 💻

Check out the complete GitHub code. 💻

--

--