java-telegram-bot-api

repository·master·Indexed 24 days ago

https://github.com/pengrad/java-telegram-bot-api

A Java library for interacting with the Telegram Bot API, providing full support for Bot API 10.1 methods, including Passport, Payments, and the Gaming Platform. It supports synchronous and asynchronous requests, multiple update retrieval methods (getUpdates, Webhook, and UpdatesListener), and comprehensive tools for managing keyboards, inline mode, and bot command scopes.

Tokens
4K
Snippets
8
Records
23
Agent score
71%

What's inside java-telegram-bot-api

  1. Get updates using getUpdates, Webhook, or UpdatesListener

    master

    There are three ways to receive updates from Telegram:

    1. getUpdates: Manually poll for updates. To confirm updates, use the offset parameter set to last_processed_update_id + 1.
    2. Webhook: Telegram sends requests to your server. Use BotUtils.parseUpdate(stringRequest) or BotUtils.parseUpdate(reader) to convert the incoming request into an Update object.
    3. UpdatesListener: A high-level abstraction that runs a getUpdates loop for you. You implement the process(List<Update> updates) method and return an integer to indicate confirmation status.
    // UpdatesListener example
    bot.setUpdatesListener(new UpdatesListener() {
        @Override
        public int process(List<Update> updates) {
            // process updates
            return UpdatesListener.CONFIRMED_UPDATES_ALL;
        }
    }, new ExceptionHandler() {
        @Override
        public void onException(TelegramException e) {
            // handle exception
        }
    });
    
    // To stop receiving updates
    bot.removeGetUpdatesListener();
  2. Handle Telegram Passport data

    master

    When a user authorizes via Telegram Passport, you receive an Update containing PassportData.

    1. Decrypt Credentials: Use the private key (uploaded to @BotFather) to decrypt EncryptedCredentials into Credentials.
    2. Decrypt Elements: Use the Credentials to decrypt EncryptedPassportElement objects into specific types like PersonalDetails or ResidentialAddress.
    3. Download Files: The library provides element.decryptFile(file, credentials, bot) to download and decrypt PassportFile objects directly into a byte[].
  3. Implement Inline Mode

    master

    Inline mode allows users to access your bot from any chat by typing its username.

    1. Detecting Queries: Listen for InlineQuery or ChosenInlineResult in your updates.
    2. Providing Results: Use AnswerInlineQuery to send a list of InlineQueryResult objects (e.g., InlineQueryResultPhoto, InlineQueryResultArticle, InlineQueryResultVideo).
  4. Handle exceptions in the UpdatesListener

    master

    When registering an UpdatesListener, you can provide an exception handler to manage errors. The handler receives an exception object e which allows you to distinguish between two types of errors:

    1. Telegram API Errors: If e.response() is not null, the error came from Telegram's servers. You can access e.response().errorCode() and e.response().description() to debug the specific API issue.
    2. Network/System Errors: If e.response() is null, the error is likely a network issue or a local exception.
    }, e -> {
        if (e.response() != null) {
            // got bad response from telegram
            e.response().errorCode();
            e.response().description();
        } else {
            // probably network error
            e.printStackTrace();
        }
    });
  5. Install the Java Telegram Bot API

    master

    You can add the library to your project using Gradle or Maven. The current version is 10.1.0.

    Gradle: Add the following to your build.gradle file:

    implementation 'com.github.pengrad:java-telegram-bot-api:10.1.0'

    Maven: Add the following to your pom.xml file:

    <dependency>
      <groupId>com.github.pengrad</groupId>
      <artifactId>java-telegram-bot-api</artifactId>
      <version>10.1.0</version>
    </dependency>

    Alternatively, you can download a JAR containing all dependencies from the official release page.

    implementation 'com.github.pengrad:java-telegram-bot-api:10.1.0'
  6. Basic usage of the TelegramBot class

    master

    To interact with Telegram, instantiate a TelegramBot using the token provided by @BotFather. You can then register an UpdatesListener to handle incoming updates and use the execute method to send requests (like SendMessage).

    When implementing the UpdatesListener, you must return the ID of the last processed update or use UpdatesListener.CONFIRMED_UPDATES_ALL to confirm all received updates.

    // Create your bot passing the token received from @BotFather
    TelegramBot bot = new TelegramBot("BOT_TOKEN");
    
    // Register for updates
    bot.setUpdatesListener(updates -> {
        // ... process updates
        // return id of last processed update or confirm them all
        return UpdatesListener.CONFIRMED_UPDATES_ALL;
    // Create Exception Handler
    }, e -> {
        if (e.response() != null) {
            // got bad response from telegram
            e.response().errorCode();
            e.response().description();
        } else {
            // probably network error
            e.printStackTrace();
        }
    });
    
    // Send messages
    long chatId = update.message().chat().id();
    SendResponse response = bot.execute(new SendMessage(chatId, "Hello!"));
  7. Download files from Telegram

    master

    To download a file, first use GetFile with the fileId. This returns a GetFileResponse containing a File object. Use bot.getFullFilePath(file) to construct the full download URL: https://api.telegram.org/file/<BOT_TOKEN>/<FILE_PATH>.

    GetFile request = new GetFile("fileId");
    GetFileResponse getFileResponse = bot.execute(request);
    File file = getFileResponse.file();
    
    String fullPath = bot.getFullFilePath(file);
  8. Send messages and use formatting

    master

    Use SendMessage to send text to a chat. You can chain methods to set ParseMode (HTML or Markdown), disable web page previews, or reply to a specific message. Most send requests (like SendPhoto, SendLocation) return a SendResponse which contains the resulting Message object.

    SendMessage request = new SendMessage(chatId, "text")
            .parseMode(ParseMode.HTML)
            .disableWebPagePreview(true)
            .replyToMessageId(1)
            .replyMarkup(new ForceReply());
    
    SendResponse sendResponse = bot.execute(request);
    Message message = sendResponse.message();
  9. Make synchronous and asynchronous requests

    master

    The library supports both synchronous and asynchronous execution of requests.

    • Synchronous: Use bot.execute(request) which returns a response object immediately.
    • Asynchronous: Use bot.execute(request, callback) which uses a Callback to handle the response or failure on a separate thread.
    // Synchronous
    BaseResponse response = bot.execute(request);
    
    // Asynchronous
    bot.execute(request, new Callback() {
        @Override
        public void onResponse(BaseRequest request, BaseResponse response) {
            // Handle success
        }
        @Override
        public void onFailure(BaseRequest request, IOException e) {
            // Handle error
        }
    });
  10. Configure Keyboards (Reply and Inline)

    master

    The library provides several classes for creating interactive keyboards:

    • ReplyKeyboardMarkup: A traditional keyboard that replaces the user's input field. Use KeyboardButton to add buttons with text, contact requests, or location requests.
    • InlineKeyboardMarkup: A keyboard attached to a specific message. Use InlineKeyboardButton to provide URLs, callback data, or switch to inline mode.
    • ForceReply / ReplyKeyboardRemove: Used to control how the user's reply interface behaves.
    // ReplyKeyboardMarkup with buttons
    Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup(
                    new String[]{"first row button1", "first row button2"},
                    new String[]{"second row button1", "second row button2"})
                    .oneTimeKeyboard(true)
                    .resizeKeyboard(true);
    
    // InlineKeyboardMarkup
    InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(
            new InlineKeyboardButton[]{                
                    new InlineKeyboardButton("url").url("www.google.com"),
                    new InlineKeyboardButton("callback_data").callbackData("callback_data")
            });
  11. Configure InputChecklist options

    master

    When creating an InputChecklist, you can use the following methods to configure optional fields:

    • parseMode(parseMode: String): Sets the text parsing mode (e.g., "HTML" or "MarkdownV2") for the checklist title.
    • titleEntities(titleEntities: Array<MessageEntity>): Sets the MessageEntity array for the checklist title.
    • othersCanAddTasks(othersCanAddTasks: Boolean): Determines if other users can add tasks to the checklist.
    • othersCanMarkTasksAsDone(othersCanMarkTasksAsDone: Boolean): Determines if other users can mark tasks as done.