org.telegram.telegrambots.meta.api.objects.Update Java Examples

The following examples show how to use org.telegram.telegrambots.meta.api.objects.Update. 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: BaseAbilityBot.java    From TelegramBots with MIT License 6 votes vote down vote up
Update addUser(Update update) {
    User endUser = AbilityUtils.getUser(update);
    if (endUser.equals(EMPTY_USER)) {
        // Can't add an empty user, return the update as is
        return update;
    }

    users().compute(endUser.getId(), (id, user) -> {
        if (user == null) {
            updateUserId(user, endUser);
            return endUser;
        }

        if (!user.equals(endUser)) {
            updateUserId(user, endUser);
            return endUser;
        }

        return user;
    });

    return update;
}
 
Example #2
Source File: TestDefaultBotSession.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
public void testBatchUpdates() throws Exception {
    LongPollingBot bot = Mockito.spy(new FakeLongPollingBot());
    session = getDefaultBotSession(bot);
    AtomicInteger flag = new AtomicInteger();
    Update[] updates = createFakeUpdates(9);
    session.setUpdatesSupplier(createFakeUpdatesSupplier(flag, updates));
    session.start();
    Thread.sleep(1000);
    Mockito.verify(bot, Mockito.never()).onUpdateReceived(any());
    flag.compareAndSet(0, 1);
    Thread.sleep(1000);
    Mockito.verify(bot).onUpdatesReceived(Arrays.asList(updates[0], updates[1]));
    flag.compareAndSet(2, 3);
    Thread.sleep(1000);
    Mockito.verify(bot).onUpdatesReceived(Arrays.asList(updates[2], updates[3], updates[4]));
    flag.compareAndSet(4, 5);
    Thread.sleep(1000);
    Mockito.verify(bot).onUpdatesReceived(Arrays.asList(updates[5], updates[6], updates[7], updates[8]));
    session.stop();
}
 
Example #3
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 #4
Source File: AbilityUtils.java    From TelegramBots with MIT License 6 votes vote down vote up
/**
 * A "best-effort" boolean stating whether the update is a group message or not.
 *
 * @param update a Telegram {@link Update}
 * @return whether the update is linked to a group
 */
public static boolean isGroupUpdate(Update update) {
  if (MESSAGE.test(update)) {
    return update.getMessage().isGroupMessage();
  } else if (CALLBACK_QUERY.test(update)) {
    return update.getCallbackQuery().getMessage().isGroupMessage();
  } else if (CHANNEL_POST.test(update)) {
    return update.getChannelPost().isGroupMessage();
  } else if (EDITED_CHANNEL_POST.test(update)) {
    return update.getEditedChannelPost().isGroupMessage();
  } else if (EDITED_MESSAGE.test(update)) {
    return update.getEditedMessage().isGroupMessage();
  } else {
    return false;
  }
}
 
Example #5
Source File: AbilityUtils.java    From TelegramBots with MIT License 6 votes vote down vote up
/**
 * A "best-effort" boolean stating whether the update is a super-group message or not.
 *
 * @param update a Telegram {@link Update}
 * @return whether the update is linked to a group
 */
public static boolean isSuperGroupUpdate(Update update) {
  if (MESSAGE.test(update)) {
    return update.getMessage().isSuperGroupMessage();
  } else if (CALLBACK_QUERY.test(update)) {
    return update.getCallbackQuery().getMessage().isSuperGroupMessage();
  } else if (CHANNEL_POST.test(update)) {
    return update.getChannelPost().isSuperGroupMessage();
  } else if (EDITED_CHANNEL_POST.test(update)) {
    return update.getEditedChannelPost().isSuperGroupMessage();
  } else if (EDITED_MESSAGE.test(update)) {
    return update.getEditedMessage().isSuperGroupMessage();
  } else {
    return false;
  }
}
 
Example #6
Source File: AbilityUtils.java    From TelegramBots with MIT License 6 votes vote down vote up
/**
 * @param update a Telegram {@link Update}
 * @return <tt>true</tt> if the update contains contains a private user message
 */
public static boolean isUserMessage(Update update) {
  if (MESSAGE.test(update)) {
    return update.getMessage().isUserMessage();
  } else if (CALLBACK_QUERY.test(update)) {
    return update.getCallbackQuery().getMessage().isUserMessage();
  } else if (CHANNEL_POST.test(update)) {
    return update.getChannelPost().isUserMessage();
  } else if (EDITED_CHANNEL_POST.test(update)) {
    return update.getEditedChannelPost().isUserMessage();
  } else if (EDITED_MESSAGE.test(update)) {
    return update.getEditedMessage().isUserMessage();
  } else {
    return true;
  }
}
 
Example #7
Source File: CommandsHandler.java    From TelegramBotsExample with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void processNonCommandUpdate(Update update) {

    if (update.hasMessage()) {
        Message message = update.getMessage();

        if (!DatabaseManager.getInstance().getUserStateForCommandsBot(message.getFrom().getId())) {
            return;
        }

        if (message.hasText()) {
            SendMessage echoMessage = new SendMessage();
            echoMessage.setChatId(message.getChatId());
            echoMessage.setText("Hey heres your message:\n" + message.getText());

            try {
                execute(echoMessage);
            } catch (TelegramApiException e) {
                BotLogger.error(LOGTAG, e);
            }
        }
    }
}
 
Example #8
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 6 votes vote down vote up
boolean checkLocality(Trio<Update, Ability, String[]> trio) {
    Update update = trio.a();
    Locality locality = isUserMessage(update) ? USER : GROUP;
    Locality abilityLocality = trio.b().locality();

    boolean isOk = abilityLocality == ALL || locality == abilityLocality;

    if (!isOk)
        silent.send(
                getLocalizedMessage(
                        CHECK_LOCALITY_FAIL,
                        AbilityUtils.getUser(trio.a()).getLanguageCode(),
                        abilityLocality.toString().toLowerCase()),
                getChatId(trio.a()));
    return isOk;
}
 
Example #9
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 6 votes vote down vote up
boolean checkPrivacy(Trio<Update, Ability, String[]> trio) {
    Update update = trio.a();
    User user = AbilityUtils.getUser(update);
    Privacy privacy;
    int id = user.getId();

    privacy = getPrivacy(update, id);

    boolean isOk = privacy.compareTo(trio.b().privacy()) >= 0;

    if (!isOk)
        silent.send(
                getLocalizedMessage(
                        CHECK_PRIVACY_FAIL,
                        AbilityUtils.getUser(trio.a()).getLanguageCode()),
                getChatId(trio.a()));
    return isOk;
}
 
Example #10
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
boolean filterReply(Update update) {
    return replies.stream()
            .filter(reply -> reply.isOkFor(update))
            .map(reply -> {
                reply.actOn(update);
                updateReplyStats(reply);
                return false;
            })
            .reduce(true, Boolean::logicalAnd);
}
 
Example #11
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestSendLocation() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendLocation());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, SendLocation.class);

    assertEquals("{\"chat_id\":\"12345\",\"latitude\":12.5,\"longitude\":21.5,\"reply_to_message_id\":53,\"method\":\"sendlocation\"}", map(result));
}
 
Example #12
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
boolean checkMessageFlags(Trio<Update, Ability, String[]> trio) {
    Ability ability = trio.b();
    Update update = trio.a();

    // The following variable is required to avoid bug #JDK-8044546
    BiFunction<Boolean, Predicate<Update>, Boolean> flagAnd = (flag, nextFlag) -> flag && nextFlag.test(update);
    return ability.flags().stream()
            .reduce(true, flagAnd, Boolean::logicalAnd);
}
 
Example #13
Source File: TestUtils.java    From TelegramBots with MIT License 5 votes vote down vote up
@NotNull
static MessageContext mockContext(User user, long groupId, String... args) {
  Update update = mock(Update.class);
  Message message = mock(Message.class);

  when(update.hasMessage()).thenReturn(true);
  when(update.getMessage()).thenReturn(message);

  when(message.getFrom()).thenReturn(user);
  when(message.hasText()).thenReturn(true);

  return newContext(update, user, groupId, args);
}
 
Example #14
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestGetUserProfilePhotos() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetUserProfilePhotos());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, GetUserProfilePhotos.class);

    assertEquals("{\"user_id\":98765,\"offset\":3,\"limit\":10,\"method\":\"getuserprofilephotos\"}", map(result));
}
 
Example #15
Source File: TelegramLongPollingBotTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void testOnUpdateReceived() {
    TelegramLongPollingBot bot = Mockito.mock(TelegramLongPollingBot.class);
    Mockito.doCallRealMethod().when(bot).onUpdatesReceived(any());
    Update update1 = new Update();
    Update update2 = new Update();
    bot.onUpdatesReceived(asList(update1, update2));
    Mockito.verify(bot).onUpdateReceived(update1);
    Mockito.verify(bot).onUpdateReceived(update2);
}
 
Example #16
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestGetChat() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetChat());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, GetChat.class);

    assertEquals("{\"chat_id\":\"12345\",\"method\":\"getChat\"}", map(result));
}
 
Example #17
Source File: ReplyFlowTest.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void stateIsNotResetOnFaultyReply() {
  Update update = mockFullUpdate(bot, USER, "leffffft");
  long chatId = getChatId(update);
  db.<Long, Integer>getMap(STATES).put(chatId, INITIAL_STATE);

  assertTrue(bot.filterReply(update));

  verify(silent, never()).send("I don't know how to go left.", chatId);
  assertEquals(INITIAL_STATE, db.<Long, Integer>getMap(STATES).get(chatId), "User is no longer in the initial state after faulty reply");
}
 
Example #18
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestGetGameHighScores() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetGameHighScores());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, GetGameHighScores.class);

    assertEquals("{\"chat_id\":\"12345\",\"message_id\":67890,\"user_id\":98765,\"method\":\"getGameHighScores\"}", map(result));
}
 
Example #19
Source File: TestDeserialization.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void TestResponseWithoutErrorDeserialization() throws IOException {
    ApiResponse<ArrayList<Update>> result = mapper.readValue(TelegramBotsHelper.GetResponseWithoutError(), new TypeReference<ApiResponse<ArrayList<Update>>>(){});
    assertNotNull(result);
    assertTrue(result.getOk());
    assertEquals(1, result.getResult().size());
    assertUpdate(result.getResult().get(0));
}
 
Example #20
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
private boolean isGroupAdmin(Update update, int id) {
    GetChatAdministrators admins = new GetChatAdministrators().setChatId(getChatId(update));

    return silent.execute(admins)
            .orElse(new ArrayList<>()).stream()
            .anyMatch(member -> member.getUser().getId() == id);
}
 
Example #21
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
@NotNull
Privacy getPrivacy(Update update, int id) {
    return isCreator(id) ?
            CREATOR : isAdmin(id) ?
            ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ?
            GROUP_ADMIN : PUBLIC;
}
 
Example #22
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestSendChatAction() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendChatAction());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, SendChatAction.class);

    assertEquals("{\"chat_id\":\"12345\",\"action\":\"record_video\",\"method\":\"sendChatAction\"}", map(result));
}
 
Example #23
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestSendInvoice() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendInvoice());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, SendInvoice.class);

    assertEquals("{\"chat_id\":12345,\"title\":\"Random title\",\"description\":\"Random description\"" +
            ",\"payload\":\"Random Payload\",\"provider_token\":\"Random provider token\",\"start_parameter\":" +
            "\"STARTPARAM\",\"currency\":\"EUR\",\"prices\":[{\"label\":\"LABEL\"," +
            "\"amount\":1000}],\"method\":\"sendinvoice\"}", map(result));
}
 
Example #24
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestSetGameScore() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getSetGameScore());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, SetGameScore.class);

    assertEquals("{\"inline_message_id\":\"12345\",\"disable_edit_message\":true,\"user_id\":98765,\"score\":12,\"method\":\"setGameScore\"}", map(result));
}
 
Example #25
Source File: TelegramLongPollingCommandBot.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public final void onUpdateReceived(Update update) {
    if (update.hasMessage()) {
        Message message = update.getMessage();
        if (message.isCommand() && !filter(message)) {
            if (!commandRegistry.executeCommand(this, message)) {
                //we have received a not registered command, handle it as invalid
                processInvalidCommandUpdate(update);
            }
            return;
        }
    }
    processNonCommandUpdate(update);
}
 
Example #26
Source File: TestRestApi.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
public void TestUnbanChatMember() {
    webhookBot.setReturnValue(BotApiMethodHelperFactory.getUnbanChatMember());

    Entity<Update> entity = Entity.json(getUpdate());
    BotApiMethod result =
            target("callback/testbot")
                    .request(MediaType.APPLICATION_JSON)
                    .post(entity, UnbanChatMember.class);

    assertEquals("{\"chat_id\":\"12345\",\"user_id\":98765,\"method\":\"unbanchatmember\"}", map(result));
}
 
Example #27
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * This method contains the stream of actions that are applied on any update.
 * <p>
 * It will correctly handle addition of users into the DB and the execution of abilities and replies.
 *
 * @param update the update received by Telegram's API
 */
public void onUpdateReceived(Update update) {
    log.info(format("[%s] New update [%s] received at %s", botUsername, update.getUpdateId(), now()));
    log.info(update.toString());
    long millisStarted = System.currentTimeMillis();

    Stream.of(update)
            .filter(this::checkGlobalFlags)
            .filter(this::checkBlacklist)
            .map(this::addUser)
            .filter(this::filterReply)
            .filter(this::hasUser)
            .map(this::getAbility)
            .filter(this::validateAbility)
            .filter(this::checkPrivacy)
            .filter(this::checkLocality)
            .filter(this::checkInput)
            .filter(this::checkMessageFlags)
            .map(this::getContext)
            .map(this::consumeUpdate)
            .map(this::updateStats)
            .forEach(this::postConsumption);

    // Commit to DB now after all the actions have been dealt
    db.commit();

    long processingTime = System.currentTimeMillis() - millisStarted;
    log.info(format("[%s] Processing of update [%s] ended at %s%n---> Processing time: [%d ms] <---%n", botUsername, update.getUpdateId(), now(), processingTime));
}
 
Example #28
Source File: TransifexHandlers.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
private void handleUpdate(Update update) throws InvalidObjectException, TelegramApiException {
    if (update.hasMessage() && update.getMessage().hasText()) {
        Message message = update.getMessage();
        if (BuildVars.ADMINS.contains(message.getFrom().getId())) {
            sendTransifexFile(message);
        } else {
            sendMovedToMessage(message);
        }
    }
}
 
Example #29
Source File: TestDeserialization.java    From TelegramBots with MIT License 5 votes vote down vote up
@Test
void TestUpdateDeserializationWithInlineKeyboard() throws Exception {
    Update update = mapper.readValue(TelegramBotsHelper.GetUpdateWithMessageInCallbackQuery(), Update.class);
    assertNotNull(update);
    assertNotNull(update.getCallbackQuery());
    assertNotNull(update.getCallbackQuery().getMessage());
    assertNotNull(update.getCallbackQuery().getMessage().getReplyMarkup());
}
 
Example #30
Source File: TelegramBot.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
@Override
public void processNonCommandUpdate(Update update) {
    if (update == null) {
        LOG.log(Level.WARNING, "Update is null");
        return;
    }

    final String nonCommandMessage = CONFIG.getBotStrings()
            .get("message.noncommand");

    final Message message = update.getMessage();
    final Chat chat = message.getChat();

    if (chat.isUserChat()) {
        sendMessage(chat.getId(), nonCommandMessage);
        return;
    }

    final String text = message.getText();

    try {
        // Skip not direct messages in chats
        if (text.length() < 1 || text.charAt(0) != '@') return;
        final String[] tmp = text.split(" ");
        if (tmp.length < 2 || !CONFIG.getBotName().equals(tmp[0].substring(1, tmp[0].length()))) return;
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Something bad happened while message processing", e);
        return;
    }

    sendMessage(chat.getId(), nonCommandMessage);
}