Telegram4J

Reactive Java library for the Telegram API

68
9
Java

Telegram4J

Telegram Group
Javadoc
Build Status

Reactive Java library for Telegram MTProto API written with Java 17.

Installation

Gradle

repositories {
    mavenCentral()
    // This repository is necessary to use the snapshot version
    maven("https://s01.oss.sonatype.org/content/repositories/snapshots")
}

dependencies {
    implementation("com.telegram4j:telegram4j-core:0.1.0-SNAPSHOT")
}

Maven

<repositories>
  <repository>
    <id>s01.oss.sonatype.org-snapshot</id>
    <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
  </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>com.telegram4j</groupId>
    <artifactId>telegram4j-core</artifactId>
    <version>0.1.0-SNAPSHOT</version>
  </dependency>
</dependencies>

Example usage

Example of a bot that will respond to a message with text !ping reply with the text pong!

public class ExampleReplyBot {
    public static void main(String[] args) {
        // values from https://core.telegram.org/api/obtaining_api_id#obtaining-api-id
        int apiId = "<api id>";
        String apiHash = "<api hash>";
        // value from https://t.me/BotFather DM
        String botAuthToken = "<bot auth token>";
        MTProtoTelegramClient client = MTProtoTelegramClient.create(apiId, apiHash, botAuthToken).connect().block();
        
        client.on(SendMessageEvent.class)
                .filter(e -> e.getMessage().getContent().equals("!ping"))
                .flatMap(e -> Mono.justOrEmpty(e.getChat())
                        // telegram api may not deliver chat info and in this situation it's necessary to retrieve chat
                        .switchIfEmpty(e.getMessage().getChat())
                        .flatMap(c -> c.sendMessage(SendMessageSpec.of("pong!")
                                .withReplyTo(ReplyToMessageSpec.of(e.getMessage())))))
                .subscribe();

        // wait until the client is stopped through `client.disconnect()`
        client.onDisconnect().block();
    }
}

For additional examples, check this packages in the repository