com.pengrad.telegrambot.model.Message Java Examples

The following examples show how to use com.pengrad.telegrambot.model.Message. 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: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 6 votes vote down vote up
@Test
public void sendSticker() {
    Message message = bot.execute(new SendSticker(chatId, stickerFileAnim)).message();
    MessageTest.checkMessage(message);
    StickerTest.check(message.sticker(), false, true);
    assertTrue(message.sticker().isAnimated());

    message = bot.execute(new SendSticker(chatId, stickerId)).message();
    MessageTest.checkMessage(message);
    StickerTest.check(message.sticker(), true, false);
    assertFalse(message.sticker().isAnimated());

    message = bot.execute(new SendSticker(chatId, imageFile)).message();
    MessageTest.checkMessage(message);
    StickerTest.check(message.sticker(), false, true);

    message = bot.execute(new SendSticker(chatId, imageBytes)).message();
    MessageTest.checkMessage(message);
    StickerTest.check(message.sticker(), false, true);
}
 
Example #2
Source File: ShakeSensitivityCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final long chatId = message.chat().id();
        final SensitivityType sensType = SensitivityType.getByName(message.text());
        String result;
        if (sensType != null) {
            prefs.shakeSensitivity = sensType;
            PrefsController.instance.setPrefs(prefs);
            if (botService.isSensorStarted()) {
                botService.stopSensor();
                botService.startSensor();
            }
            result = botService.getString(R.string.shake_sensitivity_change) + sensType;
            telegramService.sendMessage(chatId, result);
            // TODO: 09.04.2017 mainK
//            telegramService.sendMessage(chatId, result, mainKeyBoard);
            telegramService.notifyToOthers(message.from().id(), botService.getString(R.string.user_switch_shake_sensitivity) + sensType);
            return false;
        } else {
            telegramService.sendMessage(chatId, botService.getString(R.string.select_sensitivity),
                    KeyboardUtils.getKeyboard(SensitivityType.values()));
            return true;
        }
    }
 
Example #3
Source File: MinutesCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final long chatId = message.chat().id();

        try {
            int minutes = Integer.valueOf(message.text());
            prefs.minutesPeriod = minutes;
            PrefsController.instance.setPrefs(prefs);
            botService.getObserver().start(minutes);
            String result = String.format(botService.getString(R.string.time_period_changed), minutes);
            telegramService.sendMessage(chatId, result);
            // TODO: 09.04.2017 mainK
//            telegramService.sendMessage(chatId, result, mainKeyBoard);
            telegramService.notifyToOthers(message.from().id(), String.format(botService.getString(R.string.user_change_time_period), minutes));
            return false;
        } catch (NumberFormatException ex) {
//            result = "Wrong number format: " + phrase[1];
            String[][] keyboardStr = {
                    new String[]{"0", "60", "120"},
                    new String[]{"240", "480", "720"}
            };
            Keyboard keyboard = new ReplyKeyboardMarkup(keyboardStr, true, true, false);
            telegramService.sendMessage(chatId, botService.getString(R.string.select_minutes), keyboard);
            return true;
        }
    }
 
Example #4
Source File: AudioCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(final Message message, Prefs prefs) {
    final long chatId = message.chat().id();
    botService.getAudioRecordController().recordAndTransfer(new AudioRecordController.IAudioRecorder() {
        @Override
        public void onRecordStarted() {
            telegramService.sendMessage(chatId,
                    String.format(botService.getString(R.string.start_audio_record),
                            AudioRecordController.SECONDS));
            telegramService.notifyToOthers(message.from().id(), botService.getString(R.string.user_audio_record));
        }

        @Override
        public void onRecordFinished(File file) {
            telegramService.sendAudio(chatId, file);
        }

        @Override
        public void onRecordBreak() {
            telegramService.sendMessage(chatId, botService.getString(R.string.audio_record_interrupt));
        }
    });
    return false;
}
 
Example #5
Source File: MDSensitivityCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final long chatId = message.chat().id();
        final SensitivityType sensType = SensitivityType.getByName(message.text());
        String result;
        if (sensType != null) {
            botService.getDetector().setSensibility(sensType);
            prefs.sensitivity = sensType;
            PrefsController.instance.setPrefs(prefs);
            result = botService.getString(R.string.md_sensitivity_change) + sensType;
            telegramService.sendMessage(chatId, result);
            // TODO: 09.04.2017 mainK
//            telegramService.sendMessage(chatId, result, mainKeyBoard);
            telegramService.notifyToOthers(message.from().id(), botService.getString(R.string.user_switch_md_sensitivity) + sensType);
            return false;
        } else {
            telegramService.sendMessage(chatId, botService.getString(R.string.select_sensitivity),
                    KeyboardUtils.getKeyboard(SensitivityType.values()));
            return true;
        }
    }
 
Example #6
Source File: CameraModeCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final long chatId = message.chat().id();
        String text = message.text();
        final CameraMode mode = CameraMode.getByName(text);
        if (mode != null) {
            if (FabricUtils.isAvailable(mode)) {
                prefs.cameraMode = mode;
                PrefsController.instance.setPrefs(prefs);
                telegramService.sendMessage(chatId, botService.getString(R.string.camera_mode_changed) + mode);
                // TODO: 09.04.2017 mainK
//                telegramService.sendMessage(chatId, botService.getString(R.string.camera_mode_changed) + mode, mainKeyBoard);
                telegramService.notifyToOthers(message.from().id(), botService.getString(R.string.user_changed_camera_mode) + mode);
            } else {
                telegramService.sendMessage(chatId, botService.getString(R.string.camera_not_supported));
                // TODO: 09.04.2017 mainK
//                telegramService.sendMessage(chatId, botService.getString(R.string.camera_not_supported), mainKeyBoard);
            }
            return false;
        } else {
            telegramService.sendMessage(chatId, botService.getString(R.string.select_camera_mode), KeyboardUtils.getKeyboard(CameraMode.values()));
            return true;
        }
    }
 
Example #7
Source File: ProCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(Message message, Prefs prefs) {
    Long chatId = message.chat().id();
    Prefs.UserPrefs userPrefs = prefs.getUser(message.from().id());
    if (userPrefs != null) {
        StringBuilder result = new StringBuilder();
        result.append(botService.getString(R.string.pro_step_1));
        result.append(botService.getString(R.string.pro_step_2));
        result.append(botService.getString(R.string.pro_step_3));
        result.append(botService.getString(R.string.pro_step_4));


        try {
            String token = FirebaseInstanceId.getInstance().getToken();
            result.append("\nSerial 1: ").append(token).append("\n");
            result.append("\nSerial 2: ").append(Build.SERIAL);
        } catch (Throwable ex) {
            L.e(ex);
        }

        telegramService.sendMessage(chatId, result.toString());
    } else {
        telegramService.sendMessage(chatId, "Incorrect user!");
    }
    return false;
}
 
Example #8
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 6 votes vote down vote up
@Test
public void sendPhoto() {
    Message message = bot.execute(new SendPhoto(chatId, photoFileId)).message();
    MessageTest.checkMessage(message);
    PhotoSizeTest.checkPhotos(false, message.photo());

    message = bot.execute(new SendPhoto(chatId, imageFile)).message();
    MessageTest.checkMessage(message);
    PhotoSizeTest.checkPhotos(message.photo());

    String caption = "caption <b>bold</b>";
    message = bot.execute(new SendPhoto(channelName, imageBytes).caption(caption).parseMode(ParseMode.HTML)).message();
    MessageTest.checkMessage(message);
    assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
    PhotoSizeTest.checkPhotos(message.photo());

    MessageEntity captionEntity = message.captionEntities()[0];
    assertEquals(MessageEntity.Type.bold, captionEntity.type());
    assertEquals((Integer) 8, captionEntity.offset());
    assertEquals((Integer) 4, captionEntity.length());
}
 
Example #9
Source File: AlarmSettingsCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final long chatId = message.chat().id();
        String text = message.text();
        AlarmType alarmType = AlarmType.getByName(text);

        if (alarmType == null) {
            telegramService.sendMessage(chatId, "Choose alarm type", KeyboardUtils.getKeyboard(AlarmType.values()));
            return true;
        } else {
            prefs.alarmType = alarmType;

            telegramService.notifyToOthers(message.from().id(), "set alarm mode to: " + alarmType);
            telegramService.sendMessage(chatId, "Alarm mode now: " + alarmType);
            // TODO: 09.04.2017 mainKeyb
//            telegramService.sendMessage(chatId, "Alarm mode now: " + alarmType, mainKeyBoard);

            PrefsController.instance.setPrefs(prefs);
            return false;
        }
    }
 
Example #10
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 6 votes vote down vote up
@Test
public void sendVoice() {
    Message message = bot.execute(new SendVoice(chatId, voiceFileId)).message();
    MessageTest.checkMessage(message);
    VoiceTest.check(message.voice(), false);

    message = bot.execute(new SendVoice(chatId, audioFile)).message();
    MessageTest.checkMessage(message);
    VoiceTest.check(message.voice());

    String caption = "caption <b>bold</b>";
    Integer duration = 100;
    message = bot.execute(new SendVoice(chatId, audioBytes).caption(caption).parseMode(ParseMode.HTML).duration(duration)).message();
    MessageTest.checkMessage(message);
    assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
    VoiceTest.check(message.voice());
    assertEquals(duration, message.voice().duration());

    MessageEntity captionEntity = message.captionEntities()[0];
    assertEquals(MessageEntity.Type.bold, captionEntity.type());
    assertEquals((Integer) 8, captionEntity.offset());
    assertEquals((Integer) 4, captionEntity.length());
}
 
Example #11
Source File: MessageTest.java    From java-telegram-bot-api with Apache License 2.0 6 votes vote down vote up
public static void checkTextMessage(Message message) {
    checkMessage(message);
    assertNotNull(message.text());
    assertNull(message.newChatMembers());
    assertNull(message.leftChatMember());
    assertNull(message.newChatTitle());
    assertNull(message.newChatPhoto());
    assertNull(message.deleteChatPhoto());
    assertNull(message.groupChatCreated());
    assertNull(message.supergroupChatCreated());
    assertNull(message.channelChatCreated());
    assertNull(message.migrateToChatId());
    assertNull(message.migrateFromChatId());
    assertNull(message.pinnedMessage());
    assertNull(message.successfulPayment());
    assertNull(message.connectedWebsite());
}
 
Example #12
Source File: CommandHelper.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
public void executeCommand(Message message, Prefs prefs) throws NoCommandException {
    final long chatId = message.chat().id();
    String text = message.text();
    Prefs.UserPrefs user = prefs.getUser(message.from());

    ICommand command = findCommand(text);
    if (command == null) {
        command = lastUserCommand.get(user);
        lastUserCommand.remove(user);
        if (command == null) {
            throw new NoCommandException(text);
        }
    }

    L.i("Message from " + message.from().username() + ": " + command.getCommand());
    if (command.execute(message, prefs)) {
        lastUserCommand.put(user, command);
    } else {
        telegramService.sendMessage(chatId, botService.getString(R.string.please_select_command), mainKeyboard);
    }
}
 
Example #13
Source File: TimeStatsCommand.java    From Telephoto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(Message message, Prefs prefs) {
    List<TimeStats> timeStatsList = prefs.getTimeStatsList();
    StringBuilder result = new StringBuilder();
    result.append("Battery stats: ");
    if (!timeStatsList.isEmpty()) {
        int i = 0;
        for (TimeStats timeStats : timeStatsList) {
            i++;
            result.append("\n").append(timeStats.toString());
            if (i >= 15) {
                telegramService.sendMessage(message.chat().id(), result.toString());
                result.setLength(0);
                i = 0;
            }
        }
        if (result.length() > 0) {
            telegramService.sendMessage(message.chat().id(), result.toString());
        }
    } else {
        result.append("empty");
        telegramService.sendMessage(message.chat().id(), result.toString());
    }
    return false;
}
 
Example #14
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void underlineStrikethroughMarkdown() {
    String cap = "__under1__ ~strike1~ __~nested~__";
    ParseMode parseMode = ParseMode.MarkdownV2;
    SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode);
    Message message = bot.execute(sendAudio).message();
    MessageTest.checkMessage(message);

    String htmlCaption = cap.replace("__", "").replace("~", "");
    assertEquals(htmlCaption, message.caption());

    assertEquals(4, message.captionEntities().length);

    MessageEntity captionEntity = message.captionEntities()[0];
    assertEquals(MessageEntity.Type.underline, captionEntity.type());
    assertEquals((Integer) 0, captionEntity.offset());
    assertEquals((Integer) 6, captionEntity.length());

    captionEntity = message.captionEntities()[1];
    assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
    assertEquals((Integer) 7, captionEntity.offset());
    assertEquals((Integer) 7, captionEntity.length());

    captionEntity = message.captionEntities()[2];
    assertEquals(MessageEntity.Type.underline, captionEntity.type());
    assertEquals((Integer) 15, captionEntity.offset());
    assertEquals((Integer) 6, captionEntity.length());

    captionEntity = message.captionEntities()[3];
    assertEquals(MessageEntity.Type.strikethrough, captionEntity.type());
    assertEquals((Integer) 15, captionEntity.offset());
    assertEquals((Integer) 6, captionEntity.length());
}
 
Example #15
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void editMessageCaption() {
    String text = "Update " + System.currentTimeMillis() + " <b>bold</b>";

    SendResponse sendResponse = (SendResponse) bot.execute(new EditMessageCaption(chatId, 8124)
            .caption(text)
            .parseMode(ParseMode.HTML)
            .replyMarkup(new InlineKeyboardMarkup()));
    assertTrue(sendResponse.isOk());

    Message message = sendResponse.message();
    assertEquals(text.replace("<b>", "").replace("</b>", ""), message.caption());

    MessageEntity captionEntity = message.captionEntities()[0];
    assertEquals(MessageEntity.Type.bold, captionEntity.type());
    assertEquals((Integer) 21, captionEntity.offset());
    assertEquals((Integer) 4, captionEntity.length());

    BaseResponse response = bot.execute(new EditMessageCaption(channelName, 511).caption(text));
    assertTrue(response.isOk());

    response = bot.execute(new EditMessageCaption("AgAAAPrwAQCj_Q4D2s-51_8jsuU").caption(text));
    if (!response.isOk()) {
        assertEquals(400, response.errorCode());
        assertEquals("Bad Request: MESSAGE_ID_INVALID", response.description());
    }
}
 
Example #16
Source File: BotHandler.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Override
public Object handle(Request request, Response response) throws Exception {
    Update update = BotUtils.parseUpdate(request.body());
    Message message = update.message();

    if (isStartMessage(message) && onStart(message)) {
        return "ok";
    } else {
        onWebhookUpdate(update);
    }
    return "ok";
}
 
Example #17
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessageToChannel() {
    String url = "https://google.com/";
    SendMessage request = new SendMessage(channelName, "channel message [GG](" + url + ")").parseMode(ParseMode.Markdown);
    SendResponse sendResponse = bot.execute(request);
    Message message = sendResponse.message();
    MessageTest.checkTextMessage(message);
    assertEquals(url, message.entities()[0].url());
}
 
Example #18
Source File: TelegramBotManager.java    From teamcity-telegram-plugin with Apache License 2.0 5 votes vote down vote up
private void addUpdatesListener(TelegramBot bot) {
  bot.setUpdatesListener(updates -> {
    for (Update update: updates) {
      Message message = update.message();
      Long chatId = message.chat().id();
      SendMessage msg = new SendMessage(chatId,
          "Hello! Your chat id is '" + chatId + "'.\n" +
              "If you want to receive notifications about Teamcity events " +
              "please add this chat id in your Teamcity settings");
      bot.execute(msg);
    }
    return UpdatesListener.CONFIRMED_UPDATES_ALL;
  });
}
 
Example #19
Source File: HelpCommand.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(Message message, Prefs prefs) {
    final long chatId = message.chat().id();
    String result = botService.getString(R.string.help_support_group);
    telegramService.sendMessage(chatId, result);
    return false;
}
 
Example #20
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMessageToChannelId() {
    SendMessage request = new SendMessage(channelId, "channel by id message");
    SendResponse sendResponse = bot.execute(request);
    Message message = sendResponse.message();
    MessageTest.checkTextMessage(message);
}
 
Example #21
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void forwardMessage() {
    SendResponse response = bot.execute(new ForwardMessage(chatId, chatId, forwardMessageId).disableNotification(true));
    Message message = response.message();
    MessageTest.checkMessage(message);
    assertNotNull(message.forwardDate());
    assertNotNull(message.forwardSenderName());
    assertNull(message.forwardFrom());
    User viaBot = message.viaBot();
    UserTest.checkUser(viaBot);
    assertEquals("gif", viaBot.username());

    // message from user with open account
    message = bot.execute(new ForwardMessage(chatId, chatId, forwardMessageIdUser)).message();
    MessageTest.checkMessage(message);
    assertNotNull(message.forwardDate());
    assertNull(message.forwardSenderName());
    assertNotNull(message.forwardFrom());

    message = bot.execute(new ForwardMessage(channelName, channelName, 651)).message();
    assertNotNull(message.authorSignature());
    assertNotNull(message.forwardSignature());
    assertEquals(Integer.valueOf(651), message.forwardFromMessageId());
    Chat chat = message.forwardFromChat();
    assertEquals(channelName, "@" + chat.username());
    assertEquals(Chat.Type.channel, chat.type());
    assertNull(message.forwardSenderName());

    message = bot.execute(new ForwardMessage(chatId, groupId, 352)).message();
    assertEquals(MessageEntity.Type.text_mention, message.entities()[0].type());
    assertNotNull(message.entities()[0].user());
    assertNotNull(message.forwardSenderName());
}
 
Example #22
Source File: GpsCommand.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(Message message, Prefs prefs) {
    Location location = botService.getLocationController().getActual();
    Long chatId = message.chat().id();
    if (location != null) {
        telegramService.sendLocation(chatId, location);
        telegramService.notifyToOthers(message.from().id(), botService.getString(R.string.user_gps_location));
    } else {
        telegramService.sendMessage(chatId, "There is no last location. Turn on GPS.");
    }
    return false;
}
 
Example #23
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void preMessageEntity() {
    String cap = "```java\n" +
            "String s = new String();\n" +
            "```";
    ParseMode parseMode = ParseMode.MarkdownV2;
    SendAudio sendAudio = new SendAudio(chatId, audioFileId).caption(cap).parseMode(parseMode);
    Message message = bot.execute(sendAudio).message();
    MessageTest.checkMessage(message);
    assertEquals(1, message.captionEntities().length);
    assertEquals("java", message.captionEntities()[0].language());
}
 
Example #24
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void sendDocument() {
    Message message = bot.execute(new SendDocument(chatId, docFileId)).message();
    MessageTest.checkMessage(message);
    DocumentTest.check(message.document());

    message = bot.execute(new SendDocument(chatId, docBytes).thumb(thumbBytes)).message();
    MessageTest.checkMessage(message);
    DocumentTest.check(message.document());
    assertEquals(thumbSize, message.document().thumb().fileSize());

    String caption = "caption <b>bold</b>", fileName = "my doc.zip";
    ParseMode parseMode = ParseMode.HTML;
    message = bot.execute(
            new SendDocument(chatId, docFile).fileName(fileName).thumb(thumbFile).caption(caption).parseMode(parseMode))
            .message();
    MessageTest.checkMessage(message);
    DocumentTest.check(message.document());
    assertEquals(caption.replace("<b>", "").replace("</b>", ""), message.caption());
    assertEquals(fileName, message.document().fileName());
    assertEquals(thumbSize, message.document().thumb().fileSize());

    MessageEntity captionEntity = message.captionEntities()[0];
    assertEquals(MessageEntity.Type.bold, captionEntity.type());
    assertEquals((Integer) 8, captionEntity.offset());
    assertEquals((Integer) 4, captionEntity.length());
}
 
Example #25
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void sendGame() {
    InlineKeyboardButton[] buttons = {
            new InlineKeyboardButton("inline game").callbackGame("pengrad test game description"),
            new InlineKeyboardButton("inline ok").callbackData("callback ok"),
            new InlineKeyboardButton("cancel").callbackData("callback cancel"),
            new InlineKeyboardButton("url").url(someUrl),
            new InlineKeyboardButton("switch inline").switchInlineQuery("query"),
            new InlineKeyboardButton("switch inline current").switchInlineQueryCurrentChat("query"),
    };

    InlineKeyboardButton[][] inlineKeyboard = new InlineKeyboardButton[1][];
    inlineKeyboard[0] = buttons;
    InlineKeyboardMarkup keyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);

    String desc = "pengrad_test_game";
    Message message = bot.execute(new SendGame(chatId, desc).replyMarkup(keyboardMarkup)).message();
    MessageTest.checkMessage(message);
    Game game = message.game();
    GameTest.check(game);
    assertEquals(desc, game.description());

    InlineKeyboardButton[] actualButtons = message.replyMarkup().inlineKeyboard()[0];
    assertEquals(buttons.length, actualButtons.length);
    assertNotNull(actualButtons[0].callbackGame());
    for (int i = 1; i < buttons.length; i++) {
        assertEquals(buttons[i].text(), actualButtons[i].text());
        assertFalse(buttons[i].isPay());
    }
    assertEquals(buttons[1].callbackData(), actualButtons[1].callbackData());
    assertEquals(buttons[2].callbackData(), actualButtons[2].callbackData());
    assertEquals(buttons[3].url(), actualButtons[3].url());
    assertEquals(buttons[4].switchInlineQuery(), actualButtons[4].switchInlineQuery());
    assertEquals(buttons[5].switchInlineQueryCurrentChat(), actualButtons[5].switchInlineQueryCurrentChat());
}
 
Example #26
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMediaGroup() {
    MessagesResponse response = bot.execute(new SendMediaGroup(chatId,
            new InputMediaPhoto(photoFileId),
            new InputMediaPhoto(imageFile).caption("some caption <b>bold</b>").parseMode(ParseMode.HTML),
            new InputMediaPhoto(imageBytes),
            new InputMediaVideo(videoFileId),
            new InputMediaVideo(videoFile),
            new InputMediaVideo(videoBytes).caption("my video <b>bold</b>").parseMode(ParseMode.HTML)
                    .duration(10).width(11).height(12).supportsStreaming(true)
    ));
    assertTrue(response.isOk());
    assertEquals(6, response.messages().length);

    String mediaGroupId = response.messages()[0].mediaGroupId();
    assertNotNull(mediaGroupId);

    int messagesWithCaption = 0;
    for (Message message : response.messages()) {
        assertEquals(mediaGroupId, message.mediaGroupId());
        if (message.caption() != null) {
            assertEquals(MessageEntity.Type.bold, message.captionEntities()[0].type());
            messagesWithCaption++;
        }
    }
    assertEquals(2, messagesWithCaption);
}
 
Example #27
Source File: TelegramBotTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void multipartNonAscii() {
    String caption = "хорошо";
    Message message = bot.execute(
            new SendPhoto(chatId, imageFile).fileName("файл.txt").caption(caption)
    ).message();
    assertEquals(caption, message.caption());
    MessageTest.checkMessage(message);
    PhotoSizeTest.checkPhotos(message.photo());
}
 
Example #28
Source File: ModelTest.java    From java-telegram-bot-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testEquals() throws IllegalAccessException, InstantiationException, NoSuchFieldException {
    Object callbackQuery = CallbackQuery.class.newInstance();
    Field f = CallbackQuery.class.getDeclaredField("id");
    f.setAccessible(true);
    f.set(callbackQuery, "2");

    Object message = Message.class.newInstance();
    f = Message.class.getDeclaredField("message_id");
    f.setAccessible(true);
    f.set(message, 11);

    Object update = Update.class.newInstance();
    f = Update.class.getDeclaredField("update_id");
    f.setAccessible(true);
    f.set(update, 1);

    for (Class c : classes) {
        EqualsVerifier.forClass(c)
                .usingGetClass()
                .withPrefabValues(Update.class, Update.class.newInstance(), update)
                .withPrefabValues(Message.class, Message.class.newInstance(), message)
                .withPrefabValues(CallbackQuery.class, CallbackQuery.class.newInstance(), callbackQuery)
                .suppress(Warning.STRICT_HASHCODE)
                .suppress(Warning.NONFINAL_FIELDS)
                .verify();
    }
}
 
Example #29
Source File: TtsCommand.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
@Override
    public boolean execute(Message message, Prefs prefs) {
        final CancelCommand cancelCommand = new CancelCommand();
        final long chatId = message.chat().id();
        //@todo
        ICommand command = null;// CommandType.getCommand(message.text());

        if (command != null && command.getClass().equals(TtsCommand.class)) {
            List<ICommand> keyboard = new ArrayList<>();
            keyboard.add(cancelCommand);
            telegramService.sendMessage(chatId, "Type text to say aloud via TTS:", KeyboardUtils.getKeyboard(keyboard));
            return true;
        } else {
            final String textToSpeech = message.text().trim();
            if (!Strings.isNullOrEmpty(textToSpeech)) {
                if (textToSpeech.equals(cancelCommand.getCommand()) || textToSpeech.equals(cancelCommand.getName())) {
                    telegramService.sendMessage(chatId, botService.getString(R.string.operation_cancel));
                    // TODO: 09.04.2017 mainK
//                    telegramService.sendMessage(chatId, botService.getString(R.string.operation_cancel), mainKeyBoard);
                } else if (botService.ttsInitialized) {
                    botService.tts.speak(textToSpeech, TextToSpeech.QUEUE_ADD, null);
                    telegramService.sendMessage(chatId, "I sad '" + textToSpeech + "' using TTS.");
                    // TODO: 09.04.2017 mainK
//                    telegramService.sendMessage(chatId, "I sad '" + textToSpeech + "' using TTS.", mainKeyBoard);
                    telegramService.notifyToOthers(message.from().id(), "used tts to say: " + textToSpeech);
                } else {
                    telegramService.sendMessage(chatId, "Sorry, but TTS is not initialized on your device!");
                    // TODO: 09.04.2017 mainK
//                    telegramService.sendMessage(chatId, "Sorry, but TTS is not initialized on your device!", mainKeyBoard);
                }
            }
            return false;
        }
    }
 
Example #30
Source File: HDPhotoCommand.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(final Message message, Prefs prefs) {
    es.submit(new Runnable() {
        @Override
        public void run() {
            final Long chatId = message.chat().id();
            if (PrefsController.instance.isPro()) {
                final int[] cameraIds = FabricUtils.getSelectedCameras();
                for (int cameraId : cameraIds) {
                    boolean addTaskResult = botService.getCamera().addTask(new CameraTask(cameraId, 10000, 10000) {
                        @Override
                        public void processResult(ImageShot shot) {
                            if (shot != null) {
                                byte[] jpeg = shot.toGoodQuality();
                                telegramService.sendDocument(chatId, jpeg, "image.jpg");
                                telegramService.notifyToOthers(message.from().id(), "took HD photo");
                            } else {
                                telegramService.sendMessage(chatId, botService.getString(R.string.camera_init_error));
                            }
                        }
                    }, false);

                    if (!addTaskResult) {
                        telegramService.sendMessage(chatId, botService.getString(R.string.camera_busy));
                        L.e("Camera busy!");
                    }
                }
            } else {
                telegramService.sendMessage(chatId, botService.getString(R.string.only_pro));
            }
        }
    });
    return false;
}