Telegram is widely adopted as a messenger app and a good alternative to WhatsApp. With Telegram, you are not limited to chatting with humans but can also interact 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 which you can easily integrate into your Java project.
With this blog post, I'll demonstrate 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.
To get started, open a chat with @BotFather
inside 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 the 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 (first replace $TOKEN
with your token) with either Postman or your Browser (it's HTTP GET).
As part of the JSON response body 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, // this is the important id "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 client libraries (java-telegram-bot-api, TelegramBots, etc.) available Telegram. These libraries offer a convenient way to access the different Telegram APIs. However, for this example we're not using any of those libraries as it's just a HTTP GET call.
To conveniently construct and encode the HTTP URI, I decided to add Jersey. For the HTTP client, I'm using client that comes with the JDK (available since Java 11).
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 it to the 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.
You can find further inspiration for the possible Telegram bot use cases here.
The source code for this example is available on GitHub.
Have fun sending Telegram notifications with Java,
Phil