org.telegram.telegrambots.meta.exceptions.TelegramApiException Java Examples

The following examples show how to use org.telegram.telegrambots.meta.exceptions.TelegramApiException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UnsubCommand.java    From telegram-notifications-plugin with MIT License 6 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
    Subscribers subscribers = Subscribers.getInstance();
    String ans;

    Long id = chat.getId();

    boolean isSubscribed = subscribers.isSubscribed(id);

    if (isSubscribed) {
        subscribers.unsubscribe(id);
        ans = botStrings.get("message.unsub.success");
    } else {
        ans = botStrings.get("message.unsub.alreadyunsub");
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(ans);

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        LOGGER.error(LOG_TAG, e);
    }
}
 
Example #2
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 6 votes vote down vote up
@Override
public Boolean execute(SetChatPhoto setChatPhoto) throws TelegramApiException {
    assertParamNotNull(setChatPhoto, "setChatPhoto");
    setChatPhoto.validate();

    try {
        String url = getBaseUrl() + SetChatPhoto.PATH;
        HttpPost httppost = configuredHttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SetChatPhoto.CHATID_FIELD, setChatPhoto.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
        if (setChatPhoto.getPhoto() != null) {
            builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, setChatPhoto.getPhoto());
        } else if (setChatPhoto.getPhotoStream() != null) {
            builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, setChatPhoto.getPhotoStream(), ContentType.APPLICATION_OCTET_STREAM, setChatPhoto.getPhotoName());
        }
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return setChatPhoto.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to set chat photo", e);
    }
}
 
Example #3
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
void testAsyncException() throws TelegramApiException {
    final ArgumentCaptor<Exception> exceptionArgumentCaptor = ArgumentCaptor.forClass(Exception.class);

    when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 500, "emptyString"));

    telegramFileDownloader.downloadFileAsync("someFilePath", downloadFileCallbackMock);

    verify(downloadFileCallbackMock, timeout(100)
            .times(1))
            .onException(any(), exceptionArgumentCaptor.capture());

    Exception e = exceptionArgumentCaptor.getValue();
    assertThat(e, instanceOf(TelegramApiException.class));
    assertEquals(e.getCause().getCause().getMessage(), "Unexpected Status code while downloading file. Expected 200 got 500");
}
 
Example #4
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 6 votes vote down vote up
@Override
public Boolean execute(SetStickerSetThumb setStickerSetThumb) throws TelegramApiException {
    assertParamNotNull(setStickerSetThumb, "setStickerSetThumb");
    setStickerSetThumb.validate();
    try {
        String url = getBaseUrl() + AddStickerToSet.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SetStickerSetThumb.USERID_FIELD, setStickerSetThumb.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(SetStickerSetThumb.NAME_FIELD, setStickerSetThumb.getName(), TEXT_PLAIN_CONTENT_TYPE);
        addInputFile(builder, setStickerSetThumb.getThumb(), SetStickerSetThumb.THUMB_FIELD, true);
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return setStickerSetThumb.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to add sticker to set", e);
    }
}
 
Example #5
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 6 votes vote down vote up
@Override
public File execute(UploadStickerFile uploadStickerFile) throws TelegramApiException {
    assertParamNotNull(uploadStickerFile, "uploadStickerFile");
    uploadStickerFile.validate();
    try {
        String url = getBaseUrl() + UploadStickerFile.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(UploadStickerFile.USERID_FIELD, uploadStickerFile.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        addInputFile(builder, uploadStickerFile.getPngSticker(), UploadStickerFile.PNGSTICKER_FIELD, true);
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return uploadStickerFile.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to upload new sticker file", e);
    }
}
 
Example #6
Source File: ExampleBot.java    From telegram-spring-boot-starter-example with MIT License 6 votes vote down vote up
@Override
public void onUpdateReceived(Update update) {
	if (update.hasMessage()) {
		Message message = update.getMessage();
		SendMessage response = new SendMessage();
		Long chatId = message.getChatId();
		response.setChatId(chatId);
		String text = message.getText();
		response.setText(text);
		try {
			execute(response);
			logger.info("Sent message \"{}\" to {}", text, chatId);
		} catch (TelegramApiException e) {
			logger.error("Failed to send message \"{}\" to {} due to error: {}", text, chatId, e.getMessage());
		}
	}
}
 
Example #7
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 6 votes vote down vote up
public final void downloadFileAsync(File file, DownloadFileCallback<File> callback) throws TelegramApiException {
    if (file == null) {
        throw new TelegramApiException("Parameter file can not be null");
    }
    if (callback == null) {
        throw new TelegramApiException("Parameter callback can not be null");
    }
    String url = file.getFileUrl(botTokenSupplier.get());
    String tempFileName = file.getFileId();

    getFileDownloadFuture(url, getTempFile(tempFileName))
            .thenAccept(output -> callback.onResult(file, output))
            .exceptionally(throwable -> {
                callback.onException(file, new TelegramApiException("Error downloading file", throwable));
                return null;
            });

}
 
Example #8
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 6 votes vote down vote up
public final void downloadFileAsync(String filePath, DownloadFileCallback<String> callback) throws TelegramApiException {
    if (filePath == null || filePath.isEmpty()) {
        throw new TelegramApiException("Parameter filePath can not be null");
    }
    if (callback == null) {
        throw new TelegramApiException("Parameter callback can not be null");
    }
    String url = File.getFileUrl(botTokenSupplier.get(), filePath);
    String tempFileName = Long.toString(System.currentTimeMillis());

    getFileDownloadFuture(url, getTempFile(tempFileName))
            .thenAccept(output -> callback.onResult(filePath, output))
            .exceptionally(throwable -> {
                // Unwrap java.util.concurrent.CompletionException
                if (throwable instanceof CompletionException) {
                    callback.onException(filePath, new TelegramApiException("Error downloading file", throwable.getCause()));
                } else {
                    callback.onException(filePath, new TelegramApiException("Error downloading file", throwable));
                }
                return null;
            });
}
 
Example #9
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void testDownloadException() {
    when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 500, "emptyString"));

    Assertions.assertThrows(TelegramApiException.class,
            () -> telegramFileDownloader.downloadFile("someFilePath"));
}
 
Example #10
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public Boolean execute(AddStickerToSet addStickerToSet) throws TelegramApiException {
    assertParamNotNull(addStickerToSet, "addStickerToSet");
    addStickerToSet.validate();
    try {
        String url = getBaseUrl() + AddStickerToSet.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(AddStickerToSet.USERID_FIELD, addStickerToSet.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(AddStickerToSet.NAME_FIELD, addStickerToSet.getName(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(AddStickerToSet.EMOJIS_FIELD, addStickerToSet.getEmojis(), TEXT_PLAIN_CONTENT_TYPE);
        if (addStickerToSet.getPngSticker() != null) {
            addInputFile(builder, addStickerToSet.getPngSticker(), AddStickerToSet.PNGSTICKER_FIELD, true);
        } else {
            addInputFile(builder, addStickerToSet.getTgsSticker(), AddStickerToSet.TGSSTICKER_FIELD, true);
        }

        if (addStickerToSet.getMaskPosition() != null) {
            builder.addTextBody(AddStickerToSet.MASKPOSITION_FIELD, objectMapper.writeValueAsString(addStickerToSet.getMaskPosition()), TEXT_PLAIN_CONTENT_TYPE);
        }
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return addStickerToSet.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to add sticker to set", e);
    }
}
 
Example #11
Source File: TelegramBot.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
public void sendMessage(Long chatId, String message) {
    final SendMessage sendMessageRequest = new SendMessage();

    sendMessageRequest.setChatId(chatId.toString());
    sendMessageRequest.setText(message);
    sendMessageRequest.enableMarkdown(true);

    try {
        execute(sendMessageRequest);
    } catch (TelegramApiException e) {
        LOG.log(Level.SEVERE, String.format(
                "TelegramBot: Error while sending message: %s%n%s", chatId, message), e);
    }
}
 
Example #12
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * Sends a voice note using Send Voice method (https://core.telegram.org/bots/api#sendvoice)
 * For this to work, your audio must be in an .ogg file encoded with OPUS
 * @param sendVoice Information to send
 * @return If success, the sent Message is returned
 * @throws TelegramApiException If there is any error sending the audio
 */
@Override
public final Message execute(SendVoice sendVoice) throws TelegramApiException {
    assertParamNotNull(sendVoice, "sendVoice");
    sendVoice.validate();
    try {
        String url = getBaseUrl() + SendVoice.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
        addInputFile(builder, sendVoice.getVoice(), SendVoice.VOICE_FIELD, true);

        if (sendVoice.getReplyMarkup() != null) {
            builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVoice.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendVoice.getReplyToMessageId() != null) {
            builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendVoice.getDisableNotification() != null) {
            builder.addTextBody(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendVoice.getDuration() != null) {
            builder.addTextBody(SendVoice.DURATION_FIELD, sendVoice.getDuration().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendVoice.getCaption() != null) {
            builder.addTextBody(SendVoice.CAPTION_FIELD, sendVoice.getCaption(), TEXT_PLAIN_CONTENT_TYPE);
            if (sendVoice.getParseMode() != null) {
                builder.addTextBody(SendVoice.PARSEMODE_FIELD, sendVoice.getParseMode(), TEXT_PLAIN_CONTENT_TYPE);
            }
        }
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return sendVoice.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to send voice", e);
    }
}
 
Example #13
Source File: StatusCommand.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
    Subscribers subscribers = Subscribers.getInstance();
    String toSend;

    Long id = chat.getId();

    boolean isSubscribed = subscribers.isSubscribed(id);

    if (isSubscribed) {
        boolean isApproved = subscribers.isApproved(id);

        if (CONFIG.getApprovalType() == UserApprover.ApprovalType.ALL) {
            toSend = botStrings.get("message.status.approved");
        } else {
            toSend = isApproved
                    ? botStrings.get("message.status.approved")
                    : botStrings.get("message.status.unapproved");
        }
    } else {
        toSend = botStrings.get("message.status.unsubscribed");
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(toSend);

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        LOGGER.error(LOG_TAG, e);
    }
}
 
Example #14
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public List<Message> execute(SendMediaGroup sendMediaGroup) throws TelegramApiException {
    assertParamNotNull(sendMediaGroup, "sendMediaGroup");
    sendMediaGroup.validate();

    try {
        String url = getBaseUrl() + SendMediaGroup.PATH;
        HttpPost httppost = configuredHttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SendMediaGroup.CHATID_FIELD, sendMediaGroup.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
        addInputData(builder, sendMediaGroup.getMedia(), SendMediaGroup.MEDIA_FIELD);

        if (sendMediaGroup.getDisableNotification() != null) {
            builder.addTextBody(SendMediaGroup.DISABLENOTIFICATION_FIELD, sendMediaGroup.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }

        if (sendMediaGroup.getReplyToMessageId() != null) {
            builder.addTextBody(SendMediaGroup.REPLYTOMESSAGEID_FIELD, sendMediaGroup.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }


        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return sendMediaGroup.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to set chat photo", e);
    }
}
 
Example #15
Source File: HelpCommand.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(botStrings.get("message.help"));

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        LOGGER.error(LOG_TAG, e);
    }
}
 
Example #16
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 5 votes vote down vote up
public final java.io.File downloadFile(String filePath, java.io.File outputFile) throws TelegramApiException {
    if (filePath == null || filePath.isEmpty()) {
        throw new TelegramApiException("Parameter file can not be null");
    }
    String url = File.getFileUrl(botTokenSupplier.get(), filePath);
    return downloadToFile(url, outputFile);
}
 
Example #17
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public Boolean execute(CreateNewStickerSet createNewStickerSet) throws TelegramApiException {
    assertParamNotNull(createNewStickerSet, "createNewStickerSet");
    createNewStickerSet.validate();
    try {
        String url = getBaseUrl() + CreateNewStickerSet.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(CreateNewStickerSet.USERID_FIELD, createNewStickerSet.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(CreateNewStickerSet.NAME_FIELD, createNewStickerSet.getName(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(CreateNewStickerSet.TITLE_FIELD, createNewStickerSet.getTitle(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(CreateNewStickerSet.EMOJIS_FIELD, createNewStickerSet.getEmojis(), TEXT_PLAIN_CONTENT_TYPE);
        builder.addTextBody(CreateNewStickerSet.CONTAINSMASKS_FIELD, createNewStickerSet.getContainsMasks().toString(), TEXT_PLAIN_CONTENT_TYPE);
        if (createNewStickerSet.getPngSticker() != null) {
            addInputFile(builder, createNewStickerSet.getPngSticker(), CreateNewStickerSet.PNGSTICKER_FIELD, true);
        } else {
            addInputFile(builder, createNewStickerSet.getTgsSticker(), CreateNewStickerSet.TGSSTICKER_FIELD, true);
        }

        if (createNewStickerSet.getMaskPosition() != null) {
            builder.addTextBody(CreateNewStickerSet.MASKPOSITION_FIELD, objectMapper.writeValueAsString(createNewStickerSet.getMaskPosition()), TEXT_PLAIN_CONTENT_TYPE);
        }
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return createNewStickerSet.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to create new sticker set", e);
    }
}
 
Example #18
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void testAsyncDownload() throws TelegramApiException, IOException {
    final ArgumentCaptor<File> fileArgumentCaptor = ArgumentCaptor.forClass(File.class);

    telegramFileDownloader.downloadFileAsync("someFilePath", downloadFileCallbackMock);

    verify(downloadFileCallbackMock, timeout(100)
            .times(1))
            .onResult(any(), fileArgumentCaptor.capture());

    String content = readFileToString(fileArgumentCaptor.getValue(), defaultCharset());
    assertEquals("Some File Content", content);
}
 
Example #19
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public Serializable execute(EditMessageMedia editMessageMedia) throws TelegramApiException {
    assertParamNotNull(editMessageMedia, "editMessageMedia");
    editMessageMedia.validate();
    try {
        String url = getBaseUrl() + EditMessageMedia.PATH;
        HttpPost httppost = configuredHttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        if (editMessageMedia.getInlineMessageId() == null) {
            builder.addTextBody(EditMessageMedia.CHATID_FIELD, editMessageMedia.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
            builder.addTextBody(EditMessageMedia.MESSAGEID_FIELD, editMessageMedia.getMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);

        } else {
            builder.addTextBody(EditMessageMedia.INLINE_MESSAGE_ID_FIELD, editMessageMedia.getInlineMessageId(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (editMessageMedia.getReplyMarkup() != null) {
            builder.addTextBody(EditMessageMedia.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(editMessageMedia.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
        }

        addInputData(builder, editMessageMedia.getMedia(), EditMessageMedia.MEDIA_FIELD, true);

        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return editMessageMedia.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to edit message media", e);
    }
}
 
Example #20
Source File: StartCommand.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(botStrings.get("message.help"));

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        LOGGER.error(LOG_TAG, e);
    }
}
 
Example #21
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 5 votes vote down vote up
private java.io.File getTempFile(String tempFileName) throws TelegramApiException {
    try {
        return java.io.File.createTempFile(tempFileName, ".tmp");
    } catch (IOException e) {
        throw new TelegramApiException("Error downloading file", e);
    }
}
 
Example #22
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public final Message execute(SendSticker sendSticker) throws TelegramApiException {
    assertParamNotNull(sendSticker, "sendSticker");

    sendSticker.validate();
    try {
        String url = getBaseUrl() + SendSticker.PATH;
        HttpPost httppost = configuredHttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setLaxMode();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.addTextBody(SendSticker.CHATID_FIELD, sendSticker.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
        addInputFile(builder, sendSticker.getSticker(), SendSticker.STICKER_FIELD, true);

        if (sendSticker.getReplyMarkup() != null) {
            builder.addTextBody(SendSticker.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendSticker.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendSticker.getReplyToMessageId() != null) {
            builder.addTextBody(SendSticker.REPLYTOMESSAGEID_FIELD, sendSticker.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        if (sendSticker.getDisableNotification() != null) {
            builder.addTextBody(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
        }
        HttpEntity multipart = builder.build();
        httppost.setEntity(multipart);

        return sendSticker.deserializeResponse(sendHttpPostRequest(httppost));
    } catch (IOException e) {
        throw new TelegramApiException("Unable to send sticker", e);
    }
}
 
Example #23
Source File: TelegramFileDownloaderTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void testFileDownload() throws TelegramApiException, IOException {
    File returnFile = telegramFileDownloader.downloadFile("someFilePath");
    String content = readFileToString(returnFile, defaultCharset());

    assertEquals("Some File Content", content);
}
 
Example #24
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 5 votes vote down vote up
private CompletableFuture<InputStream> getFileDownloadStreamFuture(final String url) {
    return CompletableFuture.supplyAsync(() -> {
        try {
            HttpResponse response = httpClient.execute(new HttpGet(url));
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == SC_OK) {
                return response.getEntity().getContent();
            } else {
                throw new TelegramApiException("Unexpected Status code while downloading file. Expected 200 got " + statusCode);
            }
        } catch (IOException | TelegramApiException e) {
            throw new DownloadFileException("Error downloading file", e);
        }
    });
}
 
Example #25
Source File: WebhookUtils.java    From TelegramBots with MIT License 5 votes vote down vote up
public static void clearWebhook(DefaultAbsSender bot) throws TelegramApiRequestException {
  try {
    boolean result = bot.execute(new DeleteWebhook());
    if (!result) {
      throw new TelegramApiRequestException("Error removing old webhook");
    }
  } catch (TelegramApiException e) {
    throw new TelegramApiRequestException("Error removing old webhook", e);
  }
}
 
Example #26
Source File: SilentSender.java    From TelegramBots with MIT License 5 votes vote down vote up
public <T extends Serializable, Method extends BotApiMethod<T>> Optional<T> execute(Method method) {
  try {
    return Optional.ofNullable(sender.execute(method));
  } catch (TelegramApiException e) {
    log.error("Could not execute bot API method", e);
    return Optional.empty();
  }
}
 
Example #27
Source File: AbsSender.java    From TelegramBots with MIT License 5 votes vote down vote up
public <T extends Serializable, Method extends BotApiMethod<T>, Callback extends SentCallback<T>> void executeAsync(Method method, Callback callback) throws TelegramApiException {
    if (method == null) {
        throw new TelegramApiException("Parameter method can not be null");
    }
    if (callback == null) {
        throw new TelegramApiException("Parameter callback can not be null");
    }
    sendApiMethodAsync(method, callback);
}
 
Example #28
Source File: SilentSender.java    From TelegramBots with MIT License 5 votes vote down vote up
public <T extends Serializable, Method extends BotApiMethod<T>, Callback extends SentCallback<T>> void
executeAsync(Method method, Callback callable) {
  try {
    sender.executeAsync(method, callable);
  } catch (TelegramApiException e) {
    log.error("Could not execute bot API method", e);
  }
}
 
Example #29
Source File: TelegramFileDownloader.java    From TelegramBots with MIT License 5 votes vote down vote up
public final java.io.File downloadFile(File file, java.io.File outputFile) throws TelegramApiException {
    if (file == null) {
        throw new TelegramApiException("Parameter file can not be null");
    }
    String url = file.getFileUrl(botTokenSupplier.get());
    return downloadToFile(url, outputFile);
}
 
Example #30
Source File: AbilityBotTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void canRecoverDB() throws TelegramApiException, IOException {
  Update update = mockBackupUpdate();
  Object backup = getDbBackup();
  java.io.File backupFile = createBackupFile(backup);

  // Support for null parameter matching since due to mocking API changes
  when(sender.downloadFile(ArgumentMatchers.<File>isNull())).thenReturn(backupFile);

  defaultAbs.recoverDB().replies().get(0).actOn(update);

  verify(silent, times(1)).send(RECOVER_SUCCESS, GROUP_ID);
  assertEquals(db.getSet(TEST), newHashSet(TEST), "Bot recovered but the DB is still not in sync");
  assertTrue(backupFile.delete(), "Could not delete backup file");
}