### Inline Query Result Examples Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Provides examples of creating various types of inline query results, including photos, articles, GIFs, MPEG4 GIFs, and videos with input content. ```java InlineQueryResult r1 = new InlineQueryResultPhoto("id", "photoUrl", "thumbUrl"); InlineQueryResult r2 = new InlineQueryResultArticle("id", "title", "message text").thumbUrl("url"); InlineQueryResult r3 = new InlineQueryResultGif("id", "gifUrl", "thumbUrl"); InlineQueryResult r4 = new InlineQueryResultMpeg4Gif("id", "mpeg4Url", "thumbUrl"); InlineQueryResult r5 = new InlineQueryResultVideo( "id", "videoUrl", InlineQueryResultVideo.MIME_VIDEO_MP4, "message", "thumbUrl", "video title") .inputMessageContent(new InputLocationMessageContent(21.03f, 105.83f)); ``` -------------------------------- ### Build the Java Telegram Bot API Library Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Use this command to build the project. Ensure you have Gradle installed. ```bash ./gradlew build ``` -------------------------------- ### Get File Information Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates how to retrieve file information using a file ID and construct the full download URL. ```java GetFile request = new GetFile("fileId") GetFileResponse getFileResponse = bot.execute(request); File file = getFileResponse.file(); // com.pengrad.telegrambot.model.File file.fileId(); file.filePath(); // relative path file.fileSize(); String fullPath = bot.getFullFilePath(file); // com.pengrad.telegrambot.model.File ``` -------------------------------- ### Keyboards Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Examples of creating different types of keyboards for user interaction. ```APIDOC ## Keyboards ### ForceReply ```java Keyboard forceReply = new ForceReply(isSelective); // or just new ForceReply(); ``` ### ReplyKeyboardRemove ```java Keyboard replyKeyboardRemove = new ReplyKeyboardRemove(); // new ReplyKeyboardRemove(isSelective) ``` ### ReplyKeyboardMarkup ```java Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup( new String[]{"first row button1", "first row button2"}, new String[]{"second row button1", "second row button2"}) .oneTimeKeyboard(true) // optional .resizeKeyboard(true) // optional .selective(true); // optional ``` ### KeyboardButton ```java Keyboard keyboard = new ReplyKeyboardMarkup( new KeyboardButton[]{ new KeyboardButton("text"), new KeyboardButton("contact").requestContact(true), new KeyboardButton("location").requestLocation(true) }); ``` ### InlineKeyboardMarkup ```java InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup( new InlineKeyboardButton[]{ new InlineKeyboardButton("url").url("www.google.com"), new InlineKeyboardButton("callback_data").callbackData("callback_data"), new InlineKeyboardButton("Switch!").switchInlineQuery("switch_inline_query") }); ``` ``` -------------------------------- ### Get File Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Shows how to request file information using a file ID and how to construct the full download URL. ```APIDOC ## Get File ```java GetFile request = new GetFile("fileId") GetFileResponse getFileResponse = bot.execute(request); File file = getFileResponse.file(); // com.pengrad.telegrambot.model.File file.fileId(); file.filePath(); // relative path file.fileSize(); ``` To get downloading link as `https://api.telegram.org/file//` ```java String fullPath = bot.getFullFilePath(file); // com.pengrad.telegrambot.model.File ``` ``` -------------------------------- ### Chat Action Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Examples of setting chat actions to indicate bot activity. ```APIDOC ## Chat Action ### Description Represents the action a bot is performing in a chat. ### Examples ```java ChatAction action = ChatAction.typing; ChatAction action = ChatAction.upload_photo; ChatAction action = ChatAction.find_location; ``` ``` -------------------------------- ### Get Sticker Set Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Shows how to retrieve information about a sticker set using its name. ```java GetStickerSet getStickerSet = new GetStickerSet(stickerSet); GetStickerSetResponse response = bot.execute(getStickerSet); StickerSet stickerSet = response.stickerSet(); ``` -------------------------------- ### Implement RequestPreprocessor in Java Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Use RequestPreprocessor to inject 'business_connection_id' and log request methods before sending. This setup applies to all subsequent bot.execute calls. ```java TelegramBot bot = new TelegramBot.Builder("BOT_TOKEN") .requestPreprocessor(new RequestPreprocessor() { @Override public , RES extends BaseResponse> void process(@NotNull BaseRequest request) { // Inject business connection id into every request request.getParameters().put("business_connection_id", "biz_conn_123"); // Log the method name System.out.println("Sending: " + request.getMethod()); } }) .build(); // Every subsequent bot.execute(...) call will have business_connection_id injected automatically SendResponse r = bot.execute(new SendMessage(chatId, "Via business connection")); ``` -------------------------------- ### setUpdatesListener() — Long-Polling Update Loop Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Starts a background thread to continuously fetch updates from Telegram using the getUpdates method. It allows for an optional exception handler to manage Telegram API and network errors. ```APIDOC ## setUpdatesListener() — Long-Polling Update Loop `setUpdatesListener` starts a background thread that calls `getUpdates` in a loop. The listener returns the id of the last confirmed update (or the sentinel constants). An optional `ExceptionHandler` distinguishes Telegram API errors from network errors. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); bot.setUpdatesListener(updates -> { for (Update update : updates) { Message message = update.message(); if (message != null && message.text() != null) { long chatId = message.chat().id(); String text = message.text(); if ("/start".equals(text)) { bot.execute(new SendMessage(chatId, "Welcome!")); } else { // Echo back bot.execute(new SendMessage(chatId, "You said: " + text)); } } } // Confirm all processed updates return UpdatesListener.CONFIRMED_UPDATES_ALL; }, e -> { if (e.response() != null) { // Telegram returned an error response System.err.println("TG error " + e.response().errorCode() + ": " + e.response().description()); } else { e.printStackTrace(); // likely a network error } }); // Stop polling // bot.removeGetUpdatesListener(); ``` ``` -------------------------------- ### Get Updates Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Shows how to fetch updates from Telegram, including inline queries, chosen inline results, and callback queries. ```java GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates()); List updates = updatesResponse.updates(); ... InlineQuery inlineQuery = update.inlineQuery(); ChosenInlineResult chosenInlineResult = update.chosenInlineResult(); CallbackQuery callbackQuery = update.callbackQuery(); ``` -------------------------------- ### Start Polling for Updates Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Sets up a listener to receive updates from the Telegram API via polling. The lambda processes incoming updates. ```java bot.setUpdatesListener(updates -> { ... }) ``` -------------------------------- ### Set and Get Bot Commands Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Register global or scoped slash commands for the bot's command menu. Commands can be optionally scoped per user group or language. Also demonstrates retrieving and deleting registered commands. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Set global commands bot.execute(new SetMyCommands( new BotCommand("start", "Start the bot"), new BotCommand("help", "Show help"), new BotCommand("settings", "Open settings") )); // Set commands only for admins in group chats, in English bot.execute(new SetMyCommands( new BotCommand("ban", "Ban a user"), new BotCommand("mute", "Mute a user") ).scope(new BotCommandScopeAllChatAdministrators()).languageCode("en")); // Retrieve currently registered commands GetMyCommandsResponse cmdResponse = bot.execute(new GetMyCommands()); for (BotCommand cmd : cmdResponse.commands()) { System.out.println("/" + cmd.command() + " — " + cmd.description()); } // Remove all commands bot.execute(new DeleteMyCommands()); ``` -------------------------------- ### Synchronous Request Execution Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Executes a request on the calling thread and returns a typed response. The `RequestPreprocessor` is run before sending. This example shows fetching bot information and sending a formatted message with disabled link preview and notifications. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Get bot identity GetMeResponse getMeResponse = bot.execute(new GetMe()); if (getMeResponse.isOk()) { User botUser = getMeResponse.user(); System.out.println("Bot username: @" + botUser.username()); // => Bot username: @MyAwesomeBot } // Send a text message with HTML formatting, link preview disabled long chatId = 123456789L; SendResponse sendResponse = bot.execute( new SendMessage(chatId, "Hello World!") .parseMode(ParseMode.HTML) .disableWebPagePreview(true) .disableNotification(true) ); if (sendResponse.isOk()) { Message sent = sendResponse.message(); System.out.println("Sent message id: " + sent.messageId()); } else { System.err.println("Error " + sendResponse.errorCode() + ": " + sendResponse.description()); } ``` -------------------------------- ### Updating Messages Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Provides examples for editing and deleting messages, including both normal and inline message scenarios. ```APIDOC ### Updating messages Normal message ```java EditMessageText editMessageText = new EditMessageText(chatId, messageId, "new test") .parseMode(ParseMode.HTML) .disableWebPagePreview(true) .replyMarkup(new ReplyKeyboardRemove()); BaseResponse response = bot.execute(editMessageText); ``` Inline message ```java EditMessageText editInlineMessageText = new EditMessageText(inlineMessageId, "new text"); BaseResponse response = bot.execute(editInlineMessageText); ``` Delete message ```java DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId); BaseResponse response = bot.execute(deleteMessage); ``` ``` -------------------------------- ### Asynchronous Request Execution Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Enqueues a request on OkHttp's dispatcher, returning a `Cancellable`. The `onResponse` callback is invoked on the dispatcher thread upon receiving a reply from Telegram, while `onFailure` is called for network or deserialization errors. The example demonstrates sending an asynchronous message and how to cancel it. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); long chatId = 123456789L; SendMessage request = new SendMessage(chatId, "Async message"); Cancellable cancellable = bot.execute(request, new Callback() { @Override public void onResponse(SendMessage req, SendResponse response) { if (response.isOk()) { System.out.println("Delivered, id=" + response.message().messageId()); } } @Override public void onFailure(SendMessage req, IOException e) { System.err.println("Network error: " + e.getMessage()); } }); // Cancel the in-flight call if needed cancellable.cancel(); ``` -------------------------------- ### Start Long-Polling Update Listener Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Starts a background thread to listen for Telegram updates. Handles API and network errors. Confirms processed updates. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); bot.setUpdatesListener(updates -> { for (Update update : updates) { Message message = update.message(); if (message != null && message.text() != null) { long chatId = message.chat().id(); String text = message.text(); if ("/start".equals(text)) { bot.execute(new SendMessage(chatId, "Welcome!")); } else { // Echo back bot.execute(new SendMessage(chatId, "You said: " + text)); } } } // Confirm all processed updates return UpdatesListener.CONFIRMED_UPDATES_ALL; }, e -> { if (e.response() != null) { // Telegram returned an error response System.err.println("TG error " + e.response().errorCode() + ": " + e.response().description()); } else { e.printStackTrace(); // likely a network error } }); // Stop polling // bot.removeGetUpdatesListener(); ``` -------------------------------- ### TelegramBot Initialization Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Demonstrates how to initialize the TelegramBot with a token or with custom configurations using its builder. ```APIDOC ## TelegramBot — Bot Initialization `TelegramBot` is the main entry point. It can be constructed with a bare token or fully customized via `TelegramBot.Builder`, which accepts a custom `OkHttpClient`, a custom API base URL, a test-server flag, a `RequestPreprocessor`, and a custom `UpdatesHandler`. ```java // Minimal construction TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Custom OkHttpClient (e.g., 30-second timeout, logging interceptor) OkHttpClient okClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); TelegramBot customBot = new TelegramBot.Builder("BOT_TOKEN") .okHttpClient(okClient) .debug() // enables HTTP body logging .updateListenerSleep(200) // 200 ms between getUpdates polls .useTestServer(false) // set true to hit api.telegram.org/bot/test/ .build(); // Shut down the underlying OkHttp dispatcher when the app exits customBot.shutdown(); ``` ``` -------------------------------- ### Get Game High Scores via Telegram Bot API Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Use this method to get data about the high scores list. Requires user ID, chat ID, and message ID. ```java GetGameHighScoresResponse response = bot.execute(new GetGameHighScores(userId, chatId, messageId)); GameHighScore[] scores = response.result(); ``` -------------------------------- ### Create and Send Reply and Inline Keyboards Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Shows how to create ReplyKeyboardMarkup and InlineKeyboardMarkup with different button types. Use ReplyKeyboardMarkup for user input suggestions and InlineKeyboardMarkup for interactive callbacks or URLs. ```java Keyboard replyKeyboard = new ReplyKeyboardMarkup( new KeyboardButton[]{ new KeyboardButton("Share Contact").requestContact(true), new KeyboardButton("Share Location").requestLocation(true) }) .resizeKeyboard(true) .oneTimeKeyboard(true) .selective(false); bot.execute(new SendMessage(chatId, "Please share your info:").replyMarkup(replyKeyboard)); // Inline keyboard with mixed buttons InlineKeyboardMarkup inline = new InlineKeyboardMarkup( new InlineKeyboardButton[]{ new InlineKeyboardButton("Open URL").url("https://telegram.org"), new InlineKeyboardButton("Answer CB").callbackData("action_1"), new InlineKeyboardButton("Switch Inline").switchInlineQuery("search query") }); bot.execute(new SendMessage(chatId, "Actions:").replyMarkup(inline)); // Remove keyboard bot.execute(new SendMessage(chatId, "Keyboard removed.").replyMarkup(new ReplyKeyboardRemove())); ``` -------------------------------- ### Create InlineKeyboardMarkup Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Create an InlineKeyboardMarkup with buttons that perform actions like opening URLs or sending callback data. Supports switching inline queries. ```java InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup( new InlineKeyboardButton[]{ new InlineKeyboardButton("url").url("www.google.com"), new InlineKeyboardButton("callback_data").callbackData("callback_data"), new InlineKeyboardButton("Switch!").switchInlineQuery("switch_inline_query") }); ``` -------------------------------- ### SetWebhook Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates how to build and execute a SetWebhook request to receive updates via HTTP POST. ```APIDOC ## SetWebhook ### Description Allows your bot to receive updates via an outgoing webhook. ### Method POST ### Endpoint /setWebhook ### Parameters #### Query Parameters - **url** (String) - Required - URL to send updates to. - **certificate** (byte[]) - Optional - Upload your public key certificates so that the root certificate in the chain can be checked. - **certificate** (File) - Optional - Upload your public key certificates so that the root certificate in the chain can be checked. ### Request Example ```java SetWebhook request = new SetWebhook() .url("url") .certificate(new byte[]{}); // byte[] // or SetWebhook request = new SetWebhook() .url("url") .certificate(new File("path")); // File ``` ### Executing the Request ```java // Synchronous execution BaseResponse response = bot.execute(request); boolean ok = response.isOk(); // Asynchronous execution bot.execute(request, new Callback() { @Override public void onResponse(SetWebhook request, BaseResponse response) { // Handle response } @Override public void onFailure(SetWebhook request, IOException e) { // Handle failure } }); ``` ### Parsing Updates from Webhook ```java // Parse update from String Update update = BotUtils.parseUpdate(stringRequest); // Parse update from Reader Update update = BotUtils.parseUpdate(reader); Message message = update.message(); ``` ``` -------------------------------- ### Initialize TelegramBot Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Demonstrates minimal and custom initialization of the TelegramBot. Customization includes setting a specific OkHttpClient with timeouts and a logging interceptor, enabling debug mode, and configuring the update listener sleep interval. Remember to shut down the bot when your application exits. ```java // Minimal construction TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Custom OkHttpClient (e.g., 30-second timeout, logging interceptor) OkHttpClient okClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); TelegramBot customBot = new TelegramBot.Builder("BOT_TOKEN") .okHttpClient(okClient) .debug() // enables HTTP body logging .updateListenerSleep(200) // 200 ms between getUpdates polls .useTestServer(false) // set true to hit api.telegram.org/bot/test/ .build(); // Shut down the underlying OkHttp dispatcher when the app exits customBot.shutdown(); ``` -------------------------------- ### Download Telegram Files using GetFile Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Demonstrates how to retrieve file metadata using GetFile, construct the download URL with getFullFilePath(), and download file content directly using getFileContent(). Requires a BOT_TOKEN and an update object containing a message with a photo. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Suppose a user sent a photo; get the largest photo size Message photoMessage = update.message(); PhotoSize[] photos = photoMessage.photo(); PhotoSize largest = photos[photos.length - 1]; // 1. Get File metadata GetFileResponse fileResponse = bot.execute(new GetFile(largest.fileId())); File telegramFile = fileResponse.file(); System.out.println("Remote path: " + telegramFile.filePath()); // e.g. photos/file_123.jpg System.out.println("Size: " + telegramFile.fileSize() + " bytes"); // 2. Build the public download URL String downloadUrl = bot.getFullFilePath(telegramFile); // => https://api.telegram.org/file/bot/photos/file_123.jpg // 3. Download bytes directly byte[] content = bot.getFileContent(telegramFile); Files.write(Paths.get("downloaded.jpg"), content); System.out.println("Saved " + content.length + " bytes"); ``` -------------------------------- ### Create ReplyKeyboardMarkup Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Create a ReplyKeyboardMarkup with custom buttons arranged in rows. Options include one-time keyboard, resizing, and selectivity. ```java Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup( new String[]{"first row button1", "first row button2"}, new String[]{"second row button1", "second row button2"}) .oneTimeKeyboard(true) // optional .resizeKeyboard(true) // optional .selective(true); // optional ``` -------------------------------- ### Create a SendMessage Request with Options Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Demonstrates the fluent builder pattern for request classes, allowing setting of parse mode and reply markup. ```java new SendMessage(chatId, text).parseMode(ParseMode.HTML).replyMarkup(keyboard) ``` -------------------------------- ### Get Game High Scores Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Retrieves the high scores for a user in a game. Requires user ID, chat ID, and message ID. ```APIDOC ## Get Game High Scores ### Description Retrieves the high scores for a user in a game. Requires user ID, chat ID, and message ID. ### Method `bot.execute(new GetGameHighScores(userId, chatId, messageId))` ### Parameters #### Path Parameters - **userId** (Integer) - Required - User identifier. - **chatId** (ChatId) - Required - Unique identifier for the target chat or username of the target channel. - **messageId** (Integer) - Required - Identifier of the message with the game. ### Request Example ```java GetGameHighScoresResponse response = bot.execute(new GetGameHighScores(userId, chatId, messageId)); GameHighScore[] scores = response.result(); ``` ### Response #### Success Response (200) - **GetGameHighScoresResponse** - Contains the list of high scores. ``` -------------------------------- ### Build TelegramBot with Default Configuration Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Instantiates the main TelegramBot class with a token. This uses default OkHttp and Gson configurations. ```java new TelegramBot(token) ``` -------------------------------- ### Send Message with Options Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates sending a text message with various options like parse mode, disabling previews, notifications, and adding reply markups. Includes both synchronous and asynchronous execution. ```java SendMessage request = new SendMessage(chatId, "text") .parseMode(ParseMode.HTML) .disableWebPagePreview(true) .disableNotification(true) .replyToMessageId(1) .replyMarkup(new ForceReply()); // sync SendResponse sendResponse = bot.execute(request); boolean ok = sendResponse.isOk(); Message message = sendResponse.message(); // async bot.execute(request, new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { } @Override public void onFailure(SendMessage request, IOException e) { } }); ``` -------------------------------- ### Decrypt Passport Elements Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Iterate through EncryptedPassportElements and decrypt their data using the obtained Credentials. This example shows how to handle different types of decrypted data. ```java EncryptedPassportElement[] encryptedPassportElements = passportData.data(); for (EncryptedPassportElement element : encryptedPassportElements) { DecryptedData decryptedData = element.decryptData(credentials); // DecryptedData can be cast to specific type by checking instanceOf if (decryptedData instanceof PersonalDetails) { PersonalDetails personalDetails = (PersonalDetails) decryptedData; } // Or by checking type of passport element if (element.type() == EncryptedPassportElement.Type.address) { ResidentialAddress address = (ResidentialAddress) decryptedData; } } ``` -------------------------------- ### File Download Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Explains how to retrieve file metadata using `GetFile`, construct the download URL with `getFullFilePath()`, and download file content directly using `getFileContent()`. ```APIDOC ## GetFile / getFullFilePath() / getFileContent() — File Download Retrieve file metadata with `GetFile`, build the download URL with `getFullFilePath()`, or download the bytes directly with `getFileContent()`. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Suppose a user sent a photo; get the largest photo size Message photoMessage = update.message(); PhotoSize[] photos = photoMessage.photo(); PhotoSize largest = photos[photos.length - 1]; // 1. Get File metadata GetFileResponse fileResponse = bot.execute(new GetFile(largest.fileId())); File telegramFile = fileResponse.file(); System.out.println("Remote path: " + telegramFile.filePath()); // e.g. photos/file_123.jpg System.out.println("Size: " + telegramFile.fileSize() + " bytes"); // 2. Build the public download URL String downloadUrl = bot.getFullFilePath(telegramFile); // => https://api.telegram.org/file/bot/photos/file_123.jpg // 3. Download bytes directly byte[] content = bot.getFileContent(telegramFile); Files.write(Paths.get("downloaded.jpg"), content); System.out.println("Saved " + content.length + " bytes"); ``` ``` -------------------------------- ### Get Encrypted Passport Data Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Retrieve encrypted Telegram Passport data from an incoming Update. This is the first step in handling user passport information. ```java PassportData passportData = update.message().passportData(); ``` -------------------------------- ### Editing Messages Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Provides examples for editing the text, caption, media, or reply markup of a previously sent message using `EditMessageText` and `EditMessageReplyMarkup`. It also covers deleting messages with `DeleteMessage`. ```APIDOC ## EditMessageText / EditMessageReplyMarkup / DeleteMessage — Editing Messages Edit the text, caption, media, or reply markup of a previously sent message, or delete it entirely. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); long chatId = 123456789L; int messageId = 42; // Edit text of a regular message BaseResponse editResponse = bot.execute( new EditMessageText(chatId, messageId, "Updated text!") .parseMode(ParseMode.Markdown) .disableWebPagePreview(false) ); System.out.println("Edit ok: " + editResponse.isOk()); // Edit reply markup only (e.g., update button labels) InlineKeyboardMarkup newKeyboard = new InlineKeyboardMarkup( new InlineKeyboardButton[]{new InlineKeyboardButton("Done ✓").callbackData("done")}); bot.execute(new EditMessageReplyMarkup(chatId, messageId).replyMarkup(newKeyboard)); // Edit inline message (from inline mode — uses inlineMessageId instead) bot.execute(new EditMessageText(inlineMessageId, "Inline message updated.")); // Delete a message bot.execute(new DeleteMessage(chatId, messageId)); ``` ``` -------------------------------- ### Inline Mode Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Explains how to handle incoming updates in inline mode and how to construct inline query results. ```APIDOC ### Inline mode Getting updates ```java GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates()); List updates = updatesResponse.updates(); ... InlineQuery inlineQuery = update.inlineQuery(); ChosenInlineResult chosenInlineResult = update.chosenInlineResult(); CallbackQuery callbackQuery = update.callbackQuery(); ``` If using webhook, you can parse request to InlineQuery ```java Update update = BotUtils.parseUpdate(stringRequest); // from String Update update = BotUtils.parseUpdate(reader); // from java.io.Reader InlineQuery inlineQuery = update.inlineQuery(); ``` #### Inline query result ```java InlineQueryResult r1 = new InlineQueryResultPhoto("id", "photoUrl", "thumbUrl"); InlineQueryResult r2 = new InlineQueryResultArticle("id", "title", "message text").thumbUrl("url"); InlineQueryResult r3 = new InlineQueryResultGif("id", "gifUrl", "thumbUrl"); InlineQueryResult r4 = new InlineQueryResultMpeg4Gif("id", "mpeg4Url", "thumbUrl"); InlineQueryResult r5 = new InlineQueryResultVideo( "id", "videoUrl", InlineQueryResultVideo.MIME_VIDEO_MP4, "message", "thumbUrl", "video title") .inputMessageContent(new InputLocationMessageContent(21.03f, 105.83f)); ``` ``` -------------------------------- ### Administer Telegram Chat Members Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Provides examples for banning members (optionally revoking their messages), restricting members by setting chat permissions, promoting members to admin, and setting custom admin titles. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); long chatId = -1001234567890L; // group/channel chat id long targetUserId = 111222333L; // Ban a member (revoke=true removes all their messages) bot.execute(new BanChatMember(chatId, targetUserId) .untilDate((int)(System.currentTimeMillis() / 1000) + 86400) // ban for 24 h .revokeMessages(true)); // Restrict a member (mute them) ChatPermissions noPermissions = new ChatPermissions() .canSendMessages(false) .canSendMediaMessages(false) .canSendPolls(false); bot.execute(new RestrictChatMember(chatId, targetUserId, noPermissions) .untilDate((int)(System.currentTimeMillis() / 1000) + 3600)); // 1 hour // Promote a member to admin bot.execute(new PromoteChatMember(chatId, targetUserId) .canDeleteMessages(true) .canRestrictMembers(true) .canPinMessages(true)); // Set a custom admin title bot.execute(new SetChatAdministratorCustomTitle(chatId, targetUserId, "Head Moderator")); ``` -------------------------------- ### Send Invoice for Payment Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Construct and send an invoice for a payment. This includes details like title, description, price, and optional fields for shipping and user information. It also shows how to add payment buttons. ```java SendInvoice sendInvoice = new SendInvoice(chatId, "title", "desc", "my_payload", "providerToken", "my_start_param", "USD", new LabeledPrice("label", 200)) .needPhoneNumber(true) .needShippingAddress(true) .isFlexible(true) .replyMarkup(new InlineKeyboardMarkup(new InlineKeyboardButton[]{ new InlineKeyboardButton("just pay").pay(), new InlineKeyboardButton("google it").url("www.google.com") })); SendResponse response = bot.execute(sendInvoice); ``` -------------------------------- ### Upload Sticker File Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates uploading a sticker file, which can be provided as a File, byte array, or URL. ```java // File or byte[] or string URL UploadStickerFile uploadStickerFile = new UploadStickerFile(chatId, stickerFile); GetFileResponse response = bot.execute(uploadStickerFile); ``` -------------------------------- ### Create ForceReply Keyboard Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Create a ForceReply keyboard. This prompts the user to reply to the message. It can be made selective. ```java Keyboard forceReply = new ForceReply(isSelective); // or just new ForceReply(); ``` -------------------------------- ### Handle Inline Queries with Java Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Handle user inline queries by parsing updates and building InlineQueryResult objects. Use AnswerInlineQuery to send results back to the user. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); // Parse the inline query from an update InlineQuery inlineQuery = update.inlineQuery(); String query = inlineQuery.query(); // user's search string // Build results InlineQueryResult article = new InlineQueryResultArticle("id1", "Article Title", "This is the message text that will be sent.") .description("Result description shown below title") .thumbUrl("https://example.com/thumb.jpg"); InlineQueryResult photo = new InlineQueryResultPhoto("id2", "https://example.com/photo.jpg", "https://example.com/thumb.jpg") .caption("A photo result"); InlineQueryResult gif = new InlineQueryResultGif("id3", "https://example.com/animation.gif", "https://example.com/thumb.jpg"); InlineQueryResult video = new InlineQueryResultVideo( "id4", "https://example.com/video.mp4", InlineQueryResultVideo.MIME_VIDEO_MP4, "Message text for video", "https://example.com/thumb.jpg", "Video Title") .inputMessageContent(new InputLocationMessageContent(48.8584f, 2.2945f)); BaseResponse response = bot.execute( new AnswerInlineQuery(inlineQuery.id(), article, photo, gif, video) .cacheTime(300) .isPersonal(true) .nextOffset("page2") ); System.out.println("Answer ok: " + response.isOk()); ``` -------------------------------- ### Text Formatting Options Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Shows how to set the parse mode for text formatting, supporting Markdown and HTML. ```java ParseMode parseMode = ParseMode.Markdown; ParseMode parseMode = ParseMode.HTML; ``` -------------------------------- ### Build TelegramBot with Custom Configuration Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Builds the TelegramBot instance using a builder pattern, allowing custom OkHttp and Gson configurations. ```java new TelegramBot.Builder(token).build() ``` -------------------------------- ### Keyboard Types Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Demonstrates the usage of ReplyKeyboardMarkup and InlineKeyboardMarkup for creating interactive keyboards in Telegram messages. It also shows how to remove a keyboard. ```APIDOC ## Keyboard Types — ReplyKeyboardMarkup and InlineKeyboardMarkup The library provides four keyboard types: `ReplyKeyboardMarkup`, `ReplyKeyboardRemove`, `ForceReply`, and `InlineKeyboardMarkup`. All implement the `Keyboard` interface and are passed to any send request via `.replyMarkup(keyboard)`. ```java // Reply keyboard with contact/location request buttons Keyboard replyKeyboard = new ReplyKeyboardMarkup( new KeyboardButton[]{ new KeyboardButton("Share Contact").requestContact(true), new KeyboardButton("Share Location").requestLocation(true) }) .resizeKeyboard(true) .oneTimeKeyboard(true) .selective(false); bot.execute(new SendMessage(chatId, "Please share your info:").replyMarkup(replyKeyboard)); // Inline keyboard with mixed buttons InlineKeyboardMarkup inline = new InlineKeyboardMarkup( new InlineKeyboardButton[]{ new InlineKeyboardButton("Open URL").url("https://telegram.org"), new InlineKeyboardButton("Answer CB").callbackData("action_1"), new InlineKeyboardButton("Switch Inline").switchInlineQuery("search query") }); bot.execute(new SendMessage(chatId, "Actions:").replyMarkup(inline)); // Remove keyboard bot.execute(new SendMessage(chatId, "Keyboard removed.").replyMarkup(new ReplyKeyboardRemove())); ``` ``` -------------------------------- ### Create Telegram Bot with Custom OkHttpClient Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Build a TelegramBot instance using a custom OkHttpClient, allowing for configuration of timeouts, interceptors, or other network settings. ```java TelegramBot bot = new TelegramBot.Builder("BOT_TOKEN").okHttpClient(client).build(); ``` -------------------------------- ### Formatting Options Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Illustrates how to set parsing modes for messages, such as Markdown or HTML. ```APIDOC ## Formatting Options ```java ParseMode parseMode = ParseMode.Markdown; ParseMode parseMode = ParseMode.HTML; ``` ``` -------------------------------- ### Send Sticker Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates sending a sticker, which can be provided as a File, byte array, string file ID, or URL. ```java // File or byte[] or string fileId of existing sticker or string URL SendSticker sendSticker = new SendSticker(chatId, imageFile); SendResponse response = bot.execute(sendSticker); ``` -------------------------------- ### Send Media Group (Album) with Java Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Bundles multiple photos or videos (2-10 items) into a single album message. Media can be provided as file IDs, URLs, File objects, or byte arrays. Requires a BOT_TOKEN and chatId. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); long chatId = 123456789L; InputMediaPhoto photo1 = new InputMediaPhoto("https://example.com/photo1.jpg") .caption("First photo"); InputMediaPhoto photo2 = new InputMediaPhoto(new java.io.File("local_photo.jpg")) .caption("Second photo"); InputMediaVideo video1 = new InputMediaVideo("existing_file_id_xyz"); MessagesResponse response = bot.execute( new SendMediaGroup(chatId, photo1, photo2, video1) .disableNotification(true) ); if (response.isOk()) { for (Message m : response.messages()) { System.out.println("Album message id: " + m.messageId()); } } ``` -------------------------------- ### Create KeyboardButton with Request Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Create a KeyboardButton that requests user contact or location. This allows for special button types in ReplyKeyboardMarkup. ```java Keyboard keyboard = new ReplyKeyboardMarkup( new KeyboardButton[]{ new KeyboardButton("text"), new KeyboardButton("contact").requestContact(true), new KeyboardButton("location").requestLocation(true) }); ``` -------------------------------- ### SetMyCommands / GetMyCommands / DeleteMyCommands Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Manage the bot's command menu, allowing you to set global or scoped commands, retrieve current commands, and remove them. ```APIDOC ## SetMyCommands / GetMyCommands / DeleteMyCommands Register slash commands that appear in the Telegram client's command menu, optionally scoped per user group or language. ### Set global commands ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); bot.execute(new SetMyCommands( new BotCommand("start", "Start the bot"), new BotCommand("help", "Show help"), new BotCommand("settings", "Open settings") )); ``` ### Set commands for specific scopes (e.g., admins in group chats, in English) ```java bot.execute(new SetMyCommands( new BotCommand("ban", "Ban a user"), new BotCommand("mute", "Mute a user") ).scope(new BotCommandScopeAllChatAdministrators()).languageCode("en")); ``` ### Retrieve currently registered commands ```java GetMyCommandsResponse cmdResponse = bot.execute(new GetMyCommands()); for (BotCommand cmd : cmdResponse.commands()) { System.out.println("/" + cmd.command() + " — " + cmd.description()); } ``` ### Remove all commands ```java bot.execute(new DeleteMyCommands()); ``` ``` -------------------------------- ### Run All Tests for Java Telegram Bot API Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Executes all tests, including integration tests. Requires specific environment variables for testing. ```bash ./gradlew clean check ``` -------------------------------- ### Set Webhook Request Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Construct a SetWebhook request. You can provide the certificate as a byte array or a File. Ensure the URL is correctly set. ```java SetWebhook request = new SetWebhook() .url("url") .certificate(new byte[]{}) // byte[] .certificate(new File("path")); // or file ``` -------------------------------- ### Answer Pre-Checkout Query Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md This method is used to respond to pre-checkout queries. It can either confirm the query or indicate an error. ```APIDOC ## Answer Pre-Checkout Query ### Description Sends answers to an incoming pre-checkout query. This method is called by the bot when a user is about to make a payment. ### Method `execute` ### Parameters - `preCheckoutQueryId` (String) - Required - Unique identifier for the query to be answered. - `errorMessage` (String) - Optional - Description of the error if the pre-checkout query cannot be fulfilled. If the query is successful, this parameter should not be provided. ### Request Example ```java AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(preCheckoutQueryId); BaseResponse response = bot.execute(answerCheckout); // answer with error AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(id, "Sorry, item not available"); BaseResponse response = bot.execute(answerCheckout); ``` ### Response #### Success Response (200) - `BaseResponse` - An object indicating the success of the operation. ``` -------------------------------- ### Instantiate a SendMessage Request Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/CLAUDE.md Creates a new SendMessage request object. Requires a chat ID and the message text. ```java new SendMessage(chatId, "text") ``` -------------------------------- ### Create and Register Telegram Bot Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Instantiate a TelegramBot with your bot token and set up an updates listener to process incoming messages. Includes an exception handler for network or API errors. ```java // 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(); } }); ``` -------------------------------- ### Answer Inline Query Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Use this to answer an inline query with a list of results. The full version allows for caching and pagination. ```java BaseResponse response = bot.execute(new AnswerInlineQuery(inlineQuery.id(), r1, r2, r3, r4, r5)); ``` ```java // or full bot.execute( new AnswerInlineQuery(inlineQuery.id(), new InlineQueryResult[]{r1, r2, r3, r4, r5}) .cacheTime(cacheTime) .isPersonal(isPersonal) .nextOffset("offset") .switchPmParameter("pmParam") .switchPmText("pmText") ); ``` -------------------------------- ### GetMe Response Structure Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Defines the structure for the response of the GetMe request, which includes user information. ```java class GetMeResponse { User user(); } ``` -------------------------------- ### Build GetUpdates Request Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Construct a GetUpdates request with parameters to limit the number of updates and set an offset for retrieving specific updates. ```java GetUpdates getUpdates = new GetUpdates().limit(100).offset(0).timeout(0); ``` -------------------------------- ### Execute Webhook Request Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Execute a SetWebhook request synchronously or asynchronously. The asynchronous execution uses a callback to handle responses or failures. ```java // sync BaseResponse response = bot.execute(request); boolean ok = response.isOk(); // async bot.execute(request, new Callback() { @Override public void onResponse(SetWebhook request, BaseResponse response) { } @Override public void onFailure(SetWebhook request, IOException e) { } }); ``` -------------------------------- ### Answer Shipping Query Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Respond to a shipping query by providing available shipping options with prices, or by sending an error message if delivery is not possible. ```java LabeledPrice[] prices = new LabeledPrice[]{ new LabeledPrice("delivery", 100), new LabeledPrice("tips", 50) }; AnswerShippingQuery answerShippingQuery = new AnswerShippingQuery(shippingQueryId, new ShippingOption("1", "VNPT", prices), new ShippingOption("2", "FREE", new LabeledPrice("free delivery", 0)) ); BaseResponse response = bot.execute(answerShippingQuery); ``` ```java // answer with error AnswerShippingQuery answerShippingError = new AnswerShippingQuery(id, "Can't deliver here!"); BaseResponse response = bot.execute(answerShippingError); ``` -------------------------------- ### Add Java Telegram Bot API Dependency (Maven) Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Add this dependency to your Maven pom.xml file to include the Java Telegram Bot API library. ```xml com.github.pengrad java-telegram-bot-api 9.6.0 ``` -------------------------------- ### Answer Pre-Checkout Query Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Acknowledge a pre-checkout query or respond with an error if the order cannot be processed. ```java AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(preCheckoutQueryId); BaseResponse response = bot.execute(answerCheckout); ``` ```java // answer with error AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(id, "Sorry, item not available"); BaseResponse response = bot.execute(answerCheckout); ``` -------------------------------- ### Manage Sticker Sets Source: https://context7.com/pengrad/java-telegram-bot-api/llms.txt Handles sticker set management, including retrieving existing sets, sending stickers, uploading sticker files, and creating new sticker sets or adding stickers to existing ones. ```java TelegramBot bot = new TelegramBot("BOT_TOKEN"); long userId = 123456789L; // Get an existing sticker set GetStickerSetResponse setResponse = bot.execute(new GetStickerSet("Animals")); StickerSet stickerSet = setResponse.stickerSet(); System.out.println("Sticker set: " + stickerSet.title() + " (" + stickerSet.stickers().length + " stickers)"); // Send a sticker by file_id bot.execute(new SendSticker(userId, stickerSet.stickers()[0].fileId())); // Upload a sticker file for later use in CreateNewStickerSet GetFileResponse uploaded = bot.execute( new UploadStickerFile(userId, new java.io.File("sticker.webp")) ); System.out.println("Uploaded file path: " + uploaded.file().filePath()); // Create a new sticker set InputSticker sticker = new InputSticker(uploaded.file().fileId(), InputSticker.Format.static_format, new String[]{"😀"}); bot.execute(new CreateNewStickerSet(userId, "my_pack_by_MyBot", "My Pack", sticker)); // Add another sticker to the set bot.execute(new AddStickerToSet(userId, "my_pack_by_MyBot", new InputSticker("another_file_id", InputSticker.Format.static_format, new String[]{"😎"}))); ``` -------------------------------- ### Send Message Source: https://github.com/pengrad/java-telegram-bot-api/blob/master/README.md Demonstrates how to send a text message with various formatting and notification options. All send requests return a SendResponse object containing a Message. ```APIDOC ## Send Message All send requests **(SendMessage, SendPhoto, SendLocation...)** return **SendResponse** object that contains **Message**. ```java SendMessage request = new SendMessage(chatId, "text") .parseMode(ParseMode.HTML) .disableWebPagePreview(true) .disableNotification(true) .replyToMessageId(1) .replyMarkup(new ForceReply()); // sync SendResponse sendResponse = bot.execute(request); boolean ok = sendResponse.isOk(); Message message = sendResponse.message(); // async bot.execute(request, new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { } @Override public void onFailure(SendMessage request, IOException e) { } }); ``` ```