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

The following examples show how to use org.telegram.telegrambots.meta.api.objects.User. 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 7 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: HelpCommand.java    From TelegramBotsExample with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {

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

    StringBuilder helpMessageBuilder = new StringBuilder("<b>Help</b>\n");
    helpMessageBuilder.append("These are the registered commands for this Bot:\n\n");

    for (IBotCommand botCommand : commandRegistry.getRegisteredCommands()) {
        helpMessageBuilder.append(botCommand.toString()).append("\n\n");
    }

    SendMessage helpMessage = new SendMessage();
    helpMessage.setChatId(chat.getId().toString());
    helpMessage.enableHtml(true);
    helpMessage.setText(helpMessageBuilder.toString());

    try {
        absSender.execute(helpMessage);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}
 
Example #3
Source File: StopCommand.java    From TelegramBotsExample with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {
    DatabaseManager dbManager = DatabaseManager.getInstance();

    if (dbManager.getUserStateForCommandsBot(user.getId())) {
        dbManager.setUserStateForCommandsBot(user.getId(), false);
        String userName = user.getFirstName() + " " + user.getLastName();

        SendMessage answer = new SendMessage();
        answer.setChatId(chat.getId().toString());
        answer.setText("Good bye " + userName + "\n" + "Hope to see you soon!");

        try {
            absSender.execute(answer);
        } catch (TelegramApiException e) {
            BotLogger.error(LOGTAG, e);
        }
    }
}
 
Example #4
Source File: StartCommand.java    From TelegramBotsExample with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) {
    DatabaseManager databseManager = DatabaseManager.getInstance();
    StringBuilder messageBuilder = new StringBuilder();

    String userName = user.getFirstName() + " " + user.getLastName();

    if (databseManager.getUserStateForCommandsBot(user.getId())) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("i think we know each other already!");
    } else {
        databseManager.setUserStateForCommandsBot(user.getId(), true);
        messageBuilder.append("Welcome ").append(userName).append("\n");
        messageBuilder.append("this bot will demonstrate you the command feature of the Java TelegramBots API!");
    }

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

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}
 
Example #5
Source File: TestUtils.java    From TelegramBots with MIT License 6 votes vote down vote up
@NotNull
static Update mockFullUpdate(AbilityBot bot, User user, String args) {
  bot.users().put(USER.getId(), USER);
  bot.users().put(CREATOR.getId(), CREATOR);
  bot.userIds().put(CREATOR.getUserName(), CREATOR.getId());
  bot.userIds().put(USER.getUserName(), USER.getId());

  bot.admins().add(CREATOR.getId());

  Update update = mock(Update.class);
  when(update.hasMessage()).thenReturn(true);
  Message message = mock(Message.class);
  when(message.getFrom()).thenReturn(user);
  when(message.getText()).thenReturn(args);
  when(message.hasText()).thenReturn(true);
  when(message.isUserMessage()).thenReturn(true);
  when(message.getChatId()).thenReturn((long) user.getId());
  when(update.getMessage()).thenReturn(message);
  return update;
}
 
Example #6
Source File: MapDBContextTest.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
void canGetAndSetVariables() {
  String varName = "somevar";
  Var<User> var = db.getVar(varName);
  var.set(CREATOR);
  db.commit();

  var = db.getVar(varName);
  assertEquals(var.get(), CREATOR);

  var.set(USER);
  db.commit();

  Var<User> changedVar = db.getVar(varName);
  assertEquals(changedVar.get(), USER);
}
 
Example #7
Source File: MapDBContextTest.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
void canFallbackDBIfRecoveryFails() {
  Set<User> users = db.getSet(USERS);
  users.add(CREATOR);
  users.add(USER);

  Set<User> originalSet = newHashSet(users);
  Object jsonBackup = db.backup();
  String corruptBackup = "!@#$" + jsonBackup;
  boolean recovered = db.recover(corruptBackup);

  Set<User> recoveredSet = db.getSet(USERS);

  assertFalse(recovered, "Recovery was successful from a CORRUPT backup");
  assertEquals(originalSet, recoveredSet, "Set before and after corrupt recovery are not equal");
}
 
Example #8
Source File: MapDBContextTest.java    From TelegramBots with MIT License 6 votes vote down vote up
@Test
void canRecoverDB() {
  Map<Integer, User> users = db.getMap(USERS);
  Map<String, Integer> userIds = db.getMap(USER_ID);
  users.put(CREATOR.getId(), CREATOR);
  users.put(USER.getId(), USER);
  userIds.put(CREATOR.getUserName(), CREATOR.getId());
  userIds.put(USER.getUserName(), USER.getId());

  db.getSet("AYRE").add(123123);
  Map<Integer, User> originalUsers = newHashMap(users);
  String beforeBackupInfo = db.info(USERS);

  Object jsonBackup = db.backup();
  db.clear();
  boolean recovered = db.recover(jsonBackup);

  Map<Integer, User> recoveredUsers = db.getMap(USERS);
  String afterRecoveryInfo = db.info(USERS);

  assertTrue(recovered, "Could not recover database successfully");
  assertEquals(beforeBackupInfo, afterRecoveryInfo, "Map info before and after recovery is different");
  assertEquals(originalUsers, recoveredUsers, "Map before and after recovery are not equal");
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: SubCommand.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 ans;

    Long id = chat.getId();
    String name = chat.isUserChat() ? user.toString() : chat.toString();

    boolean isSubscribed = subscribers.isSubscribed(id);

    if (!isSubscribed) {
        subscribers.subscribe(name, id);
        ans = botStrings.get("message.sub.success");
    } else {
        ans = botStrings.get("message.sub.alreadysub");
    }

    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 #15
Source File: HelloCommand.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

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

    String userName = chat.getUserName();
    if (userName == null || userName.isEmpty()) {
        userName = user.getFirstName() + " " + user.getLastName();
    }

    StringBuilder messageTextBuilder = new StringBuilder("Hello ").append(userName);
    if (arguments != null && arguments.length > 0) {
        messageTextBuilder.append("\n");
        messageTextBuilder.append("Thank you so much for your kind words:\n");
        messageTextBuilder.append(String.join(" ", arguments));
    }

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

    try {
        absSender.execute(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}
 
Example #16
Source File: TestDeserialization.java    From TelegramBots with MIT License 5 votes vote down vote up
private void assertFromUser(User from) {
    assertNotNull(from);
    assertEquals((Integer) 1111111, from.getId());
    assertEquals("Test Lastname", from.getLastName());
    assertEquals("Test Firstname", from.getFirstName());
    assertEquals("Testusername", from.getUserName());
}
 
Example #17
Source File: GetMe.java    From TelegramBots with MIT License 5 votes vote down vote up
@Override
public User deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<User> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<User>>() {
                });
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error getting me", result);
        }
    } catch (IOException e2) {
        throw new TelegramApiRequestException("Unable to deserialize response", e2);
    }
}
 
Example #18
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 #19
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 5 votes vote down vote up
private void updateUserId(User oldUser, User newUser) {
    if (oldUser != null && oldUser.getUserName() != null) {
        // Remove old username -> ID
        userIds().remove(oldUser.getUserName());
    }

    if (newUser.getUserName() != null) {
        // Add new mapping with the new username
        userIds().put(newUser.getUserName().toLowerCase(), newUser.getId());
    }
}
 
Example #20
Source File: DefaultAbilities.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * Gets the user with the specified ID.
 *
 * @param id the id of the required user
 * @return the user
 */
private User getUser(int id) {
  User user = bot.users().get(id);
  if (user == null) {
    throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id));
  }

  return user;
}
 
Example #21
Source File: AbilityUtils.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * Fetches the user who caused the update.
 *
 * @param update a Telegram {@link Update}
 * @return the originating user
 * @throws IllegalStateException if the user could not be found
 */
public static User getUser(Update update) {
  if (MESSAGE.test(update)) {
    return update.getMessage().getFrom();
  } else if (CALLBACK_QUERY.test(update)) {
    return update.getCallbackQuery().getFrom();
  } else if (INLINE_QUERY.test(update)) {
    return update.getInlineQuery().getFrom();
  } else if (CHANNEL_POST.test(update)) {
    return update.getChannelPost().getFrom();
  } else if (EDITED_CHANNEL_POST.test(update)) {
    return update.getEditedChannelPost().getFrom();
  } else if (EDITED_MESSAGE.test(update)) {
    return update.getEditedMessage().getFrom();
  } else if (CHOSEN_INLINE_QUERY.test(update)) {
    return update.getChosenInlineQuery().getFrom();
  } else if (SHIPPING_QUERY.test(update)) {
    return update.getShippingQuery().getFrom();
  } else if (PRECHECKOUT_QUERY.test(update)) {
    return update.getPreCheckoutQuery().getFrom();
  } else if (POLL_ANSWER.test(update)) {
    return update.getPollAnswer().getUser();
  } else if (POLL.test(update)) {
    return EMPTY_USER;
  } else {
    throw new IllegalStateException("Could not retrieve originating user from update");
  }
}
 
Example #22
Source File: DefaultAbilities.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * Gets the user with the specified username.
 *
 * @param username the username of the required user
 * @return the user
 */
private User getUser(String username) {
  Integer id = bot.userIds().get(username.toLowerCase());
  if (id == null) {
    throw new IllegalStateException(format("Could not find ID corresponding to username [%s]", username));
  }

  return getUser(id);
}
 
Example #23
Source File: AbilityUtils.java    From TelegramBots with MIT License 5 votes vote down vote up
/**
 * The full name is identified as the concatenation of the first and last name, separated by a space.
 * This method can return an empty name if both first and last name are empty.
 *
 * @return the full name of the user
 * @param user
 */
public static String fullName(User user) {
  StringJoiner name = new StringJoiner(" ");

  if (!isEmpty(user.getFirstName()))
    name.add(user.getFirstName());
  if (!isEmpty(user.getLastName()))
    name.add(user.getLastName());

  return name.toString();
}
 
Example #24
Source File: BaseAbilityBot.java    From TelegramBots with MIT License 4 votes vote down vote up
/**
 * @return the map of <ID,User>
 */
protected Map<Integer, User> users() {
    return db.getMap(USERS);
}
 
Example #25
Source File: DefaultSender.java    From TelegramBots with MIT License 4 votes vote down vote up
@Override
public User getMe() throws TelegramApiException {
  return bot.getMe();
}
 
Example #26
Source File: DefaultSender.java    From TelegramBots with MIT License 4 votes vote down vote up
@Override
public void getMeAsync(SentCallback<User> sentCallback) throws TelegramApiException {
  bot.getMeAsync(sentCallback);
}
 
Example #27
Source File: TestDeserialization.java    From TelegramBots with MIT License 4 votes vote down vote up
private void assertForwardFrom(User forwardFrom) {
    assertNotNull(forwardFrom);
    assertEquals("ForwardLastname", forwardFrom.getLastName());
    assertEquals("ForwardFirstname", forwardFrom.getFirstName());
    assertEquals(Integer.valueOf(222222), forwardFrom.getId());
}
 
Example #28
Source File: PollAnswer.java    From TelegramBots with MIT License 4 votes vote down vote up
public void setUser(User user) {
    this.user = user;
}
 
Example #29
Source File: PollAnswer.java    From TelegramBots with MIT License 4 votes vote down vote up
public User getUser() {
    return user;
}
 
Example #30
Source File: GameHighScore.java    From TelegramBots with MIT License 4 votes vote down vote up
public User getUser() {
    return user;
}