Telegram is widely adopted as a messenger app and a good alternative to WhatsApp. With Telegram, you are not limited to chatting with persons but also with bots. You can use these bots to automate tasks or notify you e.g. about an application alarm, a failed deployment or anything else. The Telegram API offers a simple way to send notifications with a Telegram bot and you can easily integrate this in your Java project.
In this blog post, I'll show you how to send notifications to your private Telegram account using a Telegram Bot. The project uses Java 11 and almost no external dependency.
Creating the Telegram Bot
Telegram fully automates the creation of a new bot with an own Telegram Bot called BotFather. Just start a chat with @BotFather
your Telegram mobile, desktop or web app. You can then use the message /newbot
to start the bot creation process. You are asked to enter the name and the username of your bot, which has to be unique and ends with _bot
or Bot
.
The final message contains your token
secret to access the HTTP API later on. Next, make sure you write your first message to your new bot. You'll find the bot by its username:
This step is required as this will create a chat_id
in the background for your private communication with your bot in the background. We need this id to send the notification from Java to exactly this chat.
To retrieve this chat_id, visit the following endpoint: https://api.telegram.org/bot$TOKEN/getUpdates with either Postman or your Browser (it's HTTP GET). In the result JSON, you should then find the chat_id
alongside all messages, this bot already got:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | { "ok": true, "result": [ { "update_id": 123, "message": { "message_id": 1, "from": { "id": 42, "is_bot": false, "first_name": "Duke", "last_name": "Duke", "username": "duke", "language_code": "de" }, "chat": { "id": 1337, "first_name": "Duke", "last_name": "Duke", "username": "Duke", "type": "private" }, "date": 1564725221, "text": "Hey " } }, ... ] } |
In this example, it's the id 1337 which represents the chat_id.
Make sure to copy the token
and chat_id
for the next step.
Sending notifications with Java
For Java, there are multiple libraries (java-telegram-bot-api, TelegramBots, etc.) to access the Telegram API. These libraries offer a convenient way to access several Telegram APIs. However, for this example, I decided to communicate with the official API directly and use no wrapper.
First I wanted to not use any external library at all and just rely on Java SE, but once I constructed and encoded the HTTP URI manually, I decided to add Jersey for this. Therefore the Maven project looks like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.rieckpil.blog</groupId> <artifactId>telegram-bot-notifications-with-java</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.29</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <release>11</release> </configuration> </plugin> <!-- further plugins to build fat jar --> </plugins> </build> </project> |
The jersey-client
dependency includes the UriBuilder
class, which is used to construct the URI
in a simple way. For accessing the API with HTTP, I'll make use of the Java 11 HttpClient
and HttpRequest
classes.
Sending a message to the private chat with your Telegram bot requires only the chat_id
and your secret bot token
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class TelegramNotifier { private static final String CHAT_ID = "INSERT_HERE"; private static final String TOKEN = "INSERT_HERE"; public static void main(String[] args) throws IOException, InterruptedException { String message = "Hello World from Java 11"; HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .version(HttpClient.Version.HTTP_2) .build(); UriBuilder builder = UriBuilder .fromUri("https://api.telegram.org") .path("/{token}/sendMessage") .queryParam("chat_id", CHAT_ID) .queryParam("text", message); HttpRequest request = HttpRequest.newBuilder() .GET() .uri(builder.build("bot" + TOKEN)) .timeout(Duration.ofSeconds(5)) .build(); HttpResponse<String> response = client .send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); } } |
The HttpClient
is configured to use HTTP 2 and a connect timeout of 5 seconds. Constructing the API endpoint to access is also straightforward as we just have to replace the token
in the path and add two query parameters. Make sure you add the prefix bot
to your token, e.g. botXYZ1kdk1
. In this example, I deserialize the JSON response payload from the Telegram API to a Java String and print to console alongside the returned status code.
With these Telegram bots, you can even do more things like responding to messages, accept payments from other Telegram users, build games, etc. Read more here if you are interested.
You can find the full source code on GitHub.
Have fun using Java to send Telegram notifications,
Phil
Great! You saved me a lot of time 🙂 Thanks!