Lesson 1. Simple echo bot
Hello! If you want to know, how to code Telegram Bots on Java, you are on the right way!
Prepare to launch
Bot API is based on HTTP-requests, but in this book I will use Rubenlagus' library for Java.
Install the library
You can install TelegramBots library with different methods:
Using Maven:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>Latest</version>
</dependency>In this tutorial I will use next machines:
Ubuntu 16.04 Server with 1GB of RAM
My home Windows 10 laptop with IntelliJ Idea pre-installed
Lets go to code!
Well, enough for words. Let's get down to buisness. In this lesson we will write simple bot that echoes everything we sent to him. Now, open IntelliJ Idea and create a new project. You can call it whatever you want. Then, dont forget to install TelegramBots library with preffered method. I think, that it is most easy to just download .jar from here
Now, when you are in the project, create files MyAmazingBot.java and Main.java within the src directory. Open MyAmazingBot.java and lets write our actual bot:
Remember! The class must extends
TelegramLongPollingBotand implement necessary methods
As you can understand, getBotUsername() and getBotToken() must return bot's username and bot's token, obtained from @BotFather. So now, our MyAmazingBot.java file will look like this:
Now, let's move on to the logic of our bot. As I said before, we want him to reply every text we send to him. onUpdateReceived(Update update) method is for us. When an update recieved, it will call this method.
Good! But how do I run the bot? Well, its a good question. Lets save that file and open Main.java. This file will instantiate TelegramBotsApi and register our new bot. It will look like this:
Now, lets initialize Api Context
Instantiate Telegram Bots API:
And register our bot:
Here is all our files:
src/Main.java
src/MyAmazingBot.java
Well done! Now we can pack our project into runnable .jar file and run it on our computer/server!
You can find all sources to this lesson in GitHub repository.
Now we can see our bot running:

Well, thats all for now. Hope to see you soon!:)
Last updated
Was this helpful?