From e7cb0e6ced328b6db1553d18052809228a4a6f8d Mon Sep 17 00:00:00 2001 From: Chase22 Date: Tue, 24 Nov 2020 17:02:44 +0100 Subject: [PATCH 01/11] Inject bot instance into the reply update consumer Also added deprecated methods to still allow the old behaviour, discarding the bot reference in that case. The condition could have a bot instance injected as well, which would require rewriting the Flag register though. --- .../abilitybots/api/bot/BaseAbilityBot.java | 4 +- .../abilitybots/api/bot/DefaultAbilities.java | 2 +- .../abilitybots/api/objects/Ability.java | 12 ++++ .../abilitybots/api/objects/Reply.java | 56 ++++++++++++++++--- .../abilitybots/api/objects/ReplyFlow.java | 25 ++++++--- .../abilitybots/api/bot/AbilityBotTest.java | 2 +- .../abilitybots/api/bot/DefaultBot.java | 8 +-- .../abilitybots/api/bot/ReplyFlowTest.java | 16 +++--- 8 files changed, 95 insertions(+), 30 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index f8beaab1..d55be864 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -625,7 +625,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return replies.stream() .filter(reply -> runSilently(() -> reply.isOkFor(update), reply.name())) .map(reply -> runSilently(() -> { - reply.actOn(update); + reply.actOn(this, update); updateReplyStats(reply); return false; }, reply.name())) @@ -651,4 +651,4 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return ability.flags().stream() .reduce(true, flagAnd, Boolean::logicalAnd); } -} \ No newline at end of file +} diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java index 0c9f6707..b96f0968 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java @@ -254,7 +254,7 @@ public final class DefaultAbilities implements AbilityExtension { .input(0) .action(ctx -> bot.silent.forceReply( getLocalizedMessage(ABILITY_RECOVER_MESSAGE, ctx.user().getLanguageCode()), ctx.chatId())) - .reply(update -> { + .reply((bot, update) -> { String replyToMsg = update.getMessage().getReplyToMessage().getText(); String recoverMessage = getLocalizedMessage(ABILITY_RECOVER_MESSAGE, AbilityUtils.getUser(update).getLanguageCode()); if (!replyToMsg.equals(recoverMessage)) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Ability.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Ability.java index d3880cb7..92c6d9b2 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Ability.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Ability.java @@ -4,10 +4,12 @@ import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.telegram.abilitybots.api.bot.BaseAbilityBot; import org.telegram.telegrambots.meta.api.objects.Update; import java.util.Arrays; import java.util.List; +import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; @@ -208,12 +210,22 @@ public final class Ability { return this; } + /** + * @deprecated Please use {@link #reply(BiConsumer, Predicate[])} + */ + @Deprecated @SafeVarargs public final AbilityBuilder reply(Consumer action, Predicate... conditions) { replies.add(Reply.of(action, conditions)); return this; } + @SafeVarargs + public final AbilityBuilder reply(BiConsumer action, Predicate... conditions) { + replies.add(Reply.of(action, conditions)); + return this; + } + public final AbilityBuilder reply(Reply reply) { replies.add(reply); return this; diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Reply.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Reply.java index 38677306..457290ed 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Reply.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Reply.java @@ -2,10 +2,12 @@ package org.telegram.abilitybots.api.objects; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import org.telegram.abilitybots.api.bot.BaseAbilityBot; import org.telegram.telegrambots.meta.api.objects.Update; import java.util.List; import java.util.Objects; +import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Predicate; @@ -22,18 +24,41 @@ import static com.google.common.collect.Lists.newArrayList; */ public class Reply { public final List> conditions; - public final Consumer action; + public final BiConsumer action; private boolean statsEnabled; private String name; - Reply(List> conditions, Consumer action) { + Reply(List> conditions, BiConsumer action) { this.conditions = ImmutableList.>builder() - .addAll(conditions) - .build(); + .addAll(conditions) + .build(); this.action = action; statsEnabled = false; } + Reply(List> conditions, BiConsumer action, String name) { + this(conditions, action); + if (Objects.nonNull(name)) { + enableStats(name); + } + } + + /** + * @deprecated Please use {@link #Reply(List, BiConsumer)} + */ + @Deprecated + Reply(List> conditions, Consumer action) { + this.conditions = ImmutableList.>builder() + .addAll(conditions) + .build(); + this.action = ((baseAbilityBot, update) -> action.accept(update)); + statsEnabled = false; + } + + /** + * @deprecated Please use {@link #Reply(List, BiConsumer, String)} + */ + @Deprecated Reply(List> conditions, Consumer action, String name) { this(conditions, action); if (Objects.nonNull(name)) { @@ -41,10 +66,27 @@ public class Reply { } } + public static Reply of(BiConsumer action, List> conditions) { + return new Reply(conditions, action); + } + + @SafeVarargs + public static Reply of(BiConsumer action, Predicate... conditions) { + return Reply.of(action, newArrayList(conditions)); + } + + /** + * @deprecated Please use {@link #of(BiConsumer, List)} + */ + @Deprecated public static Reply of(Consumer action, List> conditions) { return new Reply(conditions, action); } + /** + * @deprecated Please use {@link #of(BiConsumer, Predicate[])} + */ + @Deprecated @SafeVarargs public static Reply of(Consumer action, Predicate... conditions) { return Reply.of(action, newArrayList(conditions)); @@ -56,15 +98,15 @@ public class Reply { return conditions.stream().reduce(true, stateAnd, Boolean::logicalAnd); } - public void actOn(Update update) { - action.accept(update); + public void actOn(BaseAbilityBot bot, Update update) { + action.accept(bot, update); } public List> conditions() { return conditions; } - public Consumer action() { + public BiConsumer action() { return action; } diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyFlow.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyFlow.java index 5b0d8328..9fb5c3c7 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyFlow.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyFlow.java @@ -1,6 +1,7 @@ package org.telegram.abilitybots.api.objects; import org.jetbrains.annotations.NotNull; +import org.telegram.abilitybots.api.bot.BaseAbilityBot; import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.util.AbilityUtils; import org.telegram.telegrambots.meta.api.objects.Update; @@ -10,6 +11,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; @@ -20,7 +22,7 @@ public class ReplyFlow extends Reply { private final Set nextReplies; - private ReplyFlow(List> conditions, Consumer action, Set nextReplies, String name) { + private ReplyFlow(List> conditions, BiConsumer action, Set nextReplies, String name) { super(conditions, action, name); this.nextReplies = nextReplies; } @@ -48,7 +50,7 @@ public class ReplyFlow extends Reply { private final DBContext db; private final int id; private List> conds; - private Consumer action; + private BiConsumer action; private Set nextReplies; private String name; @@ -63,7 +65,16 @@ public class ReplyFlow extends Reply { this(db, replyCounter.getAndIncrement()); } + /** + * @deprecated Please use {@link #action(BiConsumer)} + */ + @Deprecated public ReplyFlowBuilder action(Consumer action) { + this.action = (bot, update) -> action.accept(update); + return this; + } + + public ReplyFlowBuilder action(BiConsumer action) { this.action = action; return this; } @@ -80,7 +91,7 @@ public class ReplyFlow extends Reply { public ReplyFlowBuilder next(Reply nextReply) { List> statefulConditions = toStateful(nextReply.conditions()); - Consumer statefulAction = nextReply.action().andThen(upd -> { + BiConsumer statefulAction = nextReply.action().andThen((unused, upd) -> { Long chatId = AbilityUtils.getChatId(upd); db.getMap(STATES).remove(chatId); }); @@ -100,16 +111,16 @@ public class ReplyFlow extends Reply { public ReplyFlow build() { if (action == null) - action = upd -> {}; + action = (bot, upd) -> {}; - Consumer statefulAction; + BiConsumer statefulAction; if (nextReplies.size() > 0) { - statefulAction = action.andThen(upd -> { + statefulAction = action.andThen((bot, upd) -> { Long chatId = AbilityUtils.getChatId(upd); db.getMap(STATES).put(chatId, id); }); } else { - statefulAction = action.andThen(upd -> { + statefulAction = action.andThen((bot, upd) -> { Long chatId = AbilityUtils.getChatId(upd); db.getMap(STATES).remove(chatId); }); diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java index 9fedf218..078b0322 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java @@ -210,7 +210,7 @@ public class AbilityBotTest { // Support for null parameter matching since due to mocking API changes when(sender.downloadFile(ArgumentMatchers.isNull())).thenReturn(backupFile); - defaultAbs.recoverDB().replies().get(0).actOn(update); + defaultAbs.recoverDB().replies().get(0).actOn(bot, 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"); diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java index 7838d07f..e5da80dd 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java @@ -43,8 +43,8 @@ public class DefaultBot extends AbilityBot { return getDefaultBuilder() .name(DEFAULT) .info("dis iz default command") - .reply(Reply.of(upd -> silent.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply")).enableStats("mustreply")) - .reply(upd -> silent.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY) + .reply(Reply.of((bot, upd) -> silent.send("reply", upd.getMessage().getChatId()), MESSAGE, update -> update.getMessage().getText().equals("must reply")).enableStats("mustreply")) + .reply((bot, upd) -> silent.send("reply", upd.getCallbackQuery().getMessage().getChatId()), CALLBACK_QUERY) .build(); } @@ -75,11 +75,11 @@ public class DefaultBot extends AbilityBot { public Reply channelPostReply() { return Reply.of( - upd -> silent.send("test channel post", upd.getChannelPost().getChatId()), Flag.CHANNEL_POST + (bot, upd) -> silent.send("test channel post", upd.getChannelPost().getChatId()), Flag.CHANNEL_POST ); } public Ability testAbility() { return getDefaultBuilder().build(); } -} \ No newline at end of file +} diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java index 4ca37b06..91b02134 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java @@ -163,19 +163,19 @@ public class ReplyFlowTest { } public ReplyFlow directionFlow() { - Reply saidLeft = Reply.of(upd -> silent.send("Sir, I have gone left.", getChatId(upd)), + Reply saidLeft = Reply.of((bot, upd) -> silent.send("Sir, I have gone left.", getChatId(upd)), hasMessageWith("go left or else")); ReplyFlow leftflow = ReplyFlow.builder(db, 2) - .action(upd -> silent.send("I don't know how to go left.", getChatId(upd))) + .action((bot, upd) -> silent.send("I don't know how to go left.", getChatId(upd))) .onlyIf(hasMessageWith("left")) .next(saidLeft).build(); - Reply saidRight = Reply.of(upd -> silent.send("Sir, I have gone right.", getChatId(upd)), + Reply saidRight = Reply.of((bot, upd) -> silent.send("Sir, I have gone right.", getChatId(upd)), hasMessageWith("right")); return ReplyFlow.builder(db, 1) - .action(upd -> silent.send("Command me to go left or right!", getChatId(upd))) + .action((bot, upd) -> silent.send("Command me to go left or right!", getChatId(upd))) .onlyIf(hasMessageWith("wake up")) .next(leftflow) .next(saidRight) @@ -184,10 +184,10 @@ public class ReplyFlowTest { public Reply errantReply() { return Reply.of( - upd -> { + (bot, upd) -> { throw new RuntimeException("Throwing an exception inside the update consumer"); }, - upd -> { + (upd) -> { throw new RuntimeException("Throwing an exception inside the reply conditions (flags)"); }); } @@ -195,7 +195,7 @@ public class ReplyFlowTest { public Ability replyFlowsWithAbility() { Reply replyWithVk = ReplyFlow.builder(db, 2) .enableStats("SECOND") - .action(upd -> { + .action((bot, upd) -> { silent.send("Second reply", upd.getMessage().getChatId()); }) .onlyIf(hasMessageWith("two")) @@ -203,7 +203,7 @@ public class ReplyFlowTest { Reply replyWithNickname = ReplyFlow.builder(db, 1) .enableStats("FIRST") - .action(upd -> { + .action((bot, upd) -> { silent.send("First reply", upd.getMessage().getChatId()); }) .onlyIf(hasMessageWith("one")) From adb765d739ab63fa6969d047a247b950a3e4d1b4 Mon Sep 17 00:00:00 2001 From: Dhina17 Date: Wed, 9 Dec 2020 15:31:51 +0530 Subject: [PATCH 02/11] wiki: fix code in ability extension example --- TelegramBots.wiki/abilities/Ability-Extensions.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/TelegramBots.wiki/abilities/Ability-Extensions.md b/TelegramBots.wiki/abilities/Ability-Extensions.md index 45481632..83ee9fa5 100644 --- a/TelegramBots.wiki/abilities/Ability-Extensions.md +++ b/TelegramBots.wiki/abilities/Ability-Extensions.md @@ -2,7 +2,7 @@ You have around 100 abilities in your bot and you're looking for a way to refactor that mess into more modular classes. `AbillityExtension` is here to support just that! It's not a secret that AbilityBot uses refactoring backstage to be able to construct all of your abilities and map them accordingly. However, AbilityBot searches initially for all methods that return an `AbilityExtension` type. Then, those extensions will be used to search for declared abilities. Here's an example. ```java public class MrGoodGuy implements AbilityExtension { - public Ability () { + public Ability nice() { return Ability.builder() .name("nice") .privacy(PUBLIC) @@ -13,7 +13,7 @@ public class MrGoodGuy implements AbilityExtension { } public class MrBadGuy implements AbilityExtension { - public Ability () { + public Ability notnice() { return Ability.builder() .name("notnice") .privacy(PUBLIC) @@ -51,4 +51,4 @@ It's also possible to add extensions in the constructor by using the `addExtensi // Override creatorId } -``` \ No newline at end of file +``` From aac8afe209439524efdf21186e0ab7391b9036d7 Mon Sep 17 00:00:00 2001 From: Valentin Afanasiev Date: Mon, 25 Jan 2021 19:57:48 +0300 Subject: [PATCH 03/11] add multiple reply declaration support --- .../abilitybots/api/bot/BaseAbilityBot.java | 84 ++++++++++++------- .../api/objects/ReplyCollection.java | 17 ++++ .../abilitybots/api/bot/AbilityBotTest.java | 64 +++++++++----- .../abilitybots/api/bot/DefaultBot.java | 24 ++++++ 4 files changed, 140 insertions(+), 49 deletions(-) create mode 100644 telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index f8beaab1..95dae8ec 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -248,9 +248,9 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability public Privacy getPrivacy(Update update, int id) { return isCreator(id) ? - CREATOR : isAdmin(id) ? - ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? - GROUP_ADMIN : PUBLIC; + CREATOR : isAdmin(id) ? + ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? + GROUP_ADMIN : PUBLIC; } public boolean isGroupAdmin(Update update, int id) { @@ -260,8 +260,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability public boolean isGroupAdmin(long chatId, int id) { GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) - .orElse(new ArrayList<>()).stream() - .anyMatch(member -> member.getUser().getId() == id); + .orElse(new ArrayList<>()).stream() + .anyMatch(member -> member.getUser().getId() == id); } public boolean isCreator(int id) { @@ -326,17 +326,17 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability DefaultAbilities defaultAbs = new DefaultAbilities(this); Stream defaultAbsStream = stream(DefaultAbilities.class.getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(defaultAbs)) - .filter(ab -> !toggle.isOff(ab)) - .map(toggle::processAbility); + .filter(checkReturnType(Ability.class)) + .map(returnAbility(defaultAbs)) + .filter(ab -> !toggle.isOff(ab)) + .map(toggle::processAbility); // Extract all abilities from every single extension instance abilities = Stream.concat(defaultAbsStream, - extensions.stream() - .flatMap(ext -> stream(ext.getClass().getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(ext)))) + extensions.stream() + .flatMap(ext -> stream(ext.getClass().getMethods()) + .filter(checkReturnType(Ability.class)) + .map(returnAbility(ext)))) // Abilities are immutable, build it respectively .collect(ImmutableMap::builder, (b, a) -> b.put(a.name(), a), @@ -348,7 +348,14 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability .flatMap(ext -> stream(ext.getClass().getMethods()) .filter(checkReturnType(Reply.class)) .map(returnReply(ext))) - .flatMap(Reply::stream); + .flatMap(Reply::stream); + + Stream extensionCollectionReplies = extensions.stream() + .flatMap(extension -> stream(extension.getClass().getMethods()) + .filter(checkReturnType(ReplyCollection.class)) + .map(returnReplyCollection(extension)) + .map(ReplyCollection::getReplies)) + .flatMap(Collection::stream); // Replies can be standalone or attached to abilities, fetch those too Stream abilityReplies = abilities.values().stream() @@ -356,10 +363,12 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability .flatMap(Reply::stream); // Now create the replies registry (list) - replies = Stream.concat(abilityReplies, extensionReplies).collect( - ImmutableList::builder, - Builder::add, - (b1, b2) -> b1.addAll(b2.build())) + replies = Stream.of(abilityReplies, extensionReplies, extensionCollectionReplies) + .flatMap(replyStream -> replyStream) + .collect( + ImmutableList::builder, + Builder::add, + (b1, b2) -> b1.addAll(b2.build())) .build(); } catch (IllegalStateException e) { log.error("Duplicate names found while registering abilities. Make sure that the abilities declared don't clash with the reserved ones.", e); @@ -369,15 +378,15 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability private void initStats() { Set enabledStats = Stream.concat( - replies.stream().filter(Reply::statsEnabled).map(Reply::name), - abilities.entrySet().stream() - .filter(entry -> entry.getValue().statsEnabled()) - .map(Map.Entry::getKey)).collect(toSet()); + replies.stream().filter(Reply::statsEnabled).map(Reply::name), + abilities.entrySet().stream() + .filter(entry -> entry.getValue().statsEnabled()) + .map(Map.Entry::getKey)).collect(toSet()); stats = db.getMap(STATS); Set toBeRemoved = difference(stats.keySet(), enabledStats); toBeRemoved.forEach(stats::remove); enabledStats.forEach(abName -> stats.computeIfAbsent(abName, - name -> createStats(abName, 0))); + name -> createStats(abName, 0))); } /** @@ -439,6 +448,23 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability }; } + /** + * Invokes the method and retrieves its return {@link ReplyCollection}. + * + * @param obj a bot or extension that this method is invoked with + * @return a {@link Function} which returns the {@link ReplyCollection} returned by the given method + */ + private static Function returnReplyCollection(Object obj) { + return method -> { + try { + return (ReplyCollection) method.invoke(obj); + } catch (IllegalAccessException | InvocationTargetException e) { + log.error("Could not add Reply Collection", e); + throw new RuntimeException(e); + } + }; + } + private void postConsumption(Pair pair) { ofNullable(pair.b().postAction()) .ifPresent(consumer -> consumer.accept(pair.a())); @@ -553,12 +579,12 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability String[] tokens; if (allowContinuousText()) { String abName = abilities.keySet().stream() - .filter(name -> msg.getText().startsWith(format("%s%s", getCommandPrefix(), name))) - .max(comparingInt(String::length)) - .orElse(DEFAULT); + .filter(name -> msg.getText().startsWith(format("%s%s", getCommandPrefix(), name))) + .max(comparingInt(String::length)) + .orElse(DEFAULT); tokens = msg.getText() - .replaceFirst(getCommandPrefix() + abName, "") - .split(getCommandRegexSplit()); + .replaceFirst(getCommandPrefix() + abName, "") + .split(getCommandRegexSplit()); ability = abilities.get(abName); } else { tokens = msg.getText().split(getCommandRegexSplit()); @@ -637,7 +663,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return callable.call(); } catch(Exception ex) { log.error(format("Reply [%s] failed to check for conditions. " + - "Make sure you're safeguarding against all possible updates.", name)); + "Make sure you're safeguarding against all possible updates.", name)); } return false; } diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java new file mode 100644 index 00000000..887925b8 --- /dev/null +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java @@ -0,0 +1,17 @@ +package org.telegram.abilitybots.api.objects; + +import java.util.Collection; + +public class ReplyCollection { + + public final Collection replies; + + public ReplyCollection(Collection replies) { + this.replies = replies; + } + + public Collection getReplies() { + return replies; + } + +} diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java index 9fedf218..58f513cf 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java @@ -40,7 +40,7 @@ import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import static org.mockito.internal.verification.VerificationModeFactory.times; -import static org.telegram.abilitybots.api.bot.DefaultBot.getDefaultBuilder; +import static org.telegram.abilitybots.api.bot.DefaultBot.*; import static org.telegram.abilitybots.api.bot.TestUtils.CREATOR; import static org.telegram.abilitybots.api.bot.TestUtils.*; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; @@ -661,27 +661,51 @@ public class AbilityBotTest { verify(silent, times(1)).send(expected, 1); } + @Test + void canProcessRepliesRegisteredInCollection() { + Update firstUpdate = mock(Update.class); + Message firstMessage = mock(Message.class); + when(firstMessage.getText()).thenReturn(FIRST_REPLY_KEY_MESSAGE); + when(firstMessage.getChatId()).thenReturn(1L); + + Update secondUpdate = mock(Update.class); + Message secondMessage = mock(Message.class); + when(secondMessage.getText()).thenReturn(SECOND_REPLY_KEY_MESSAGE); + when(secondMessage.getChatId()).thenReturn(1L); + + mockUser(firstUpdate, firstMessage, USER); + mockUser(secondUpdate, secondMessage, USER); + + + bot.onUpdateReceived(firstUpdate); + bot.onUpdateReceived(secondUpdate); + + verify(silent, times(2)).send(anyString(), anyLong()); + verify(silent, times(1)).send("first reply answer", 1); + verify(silent, times(1)).send("second reply answer", 1); + } + private void handlesAllUpdates(Consumer utilMethod) { Arrays.stream(Update.class.getMethods()) - // filter to all these methods of hasXXX (hasPoll, hasMessage, etc...) - .filter(method -> method.getName().startsWith("has")) - // Gotta filter out hashCode - .filter(method -> method.getReturnType().getName().equals("boolean")) - .forEach(method -> { - Update update = mock(Update.class); - try { - // Mock the method and make sure it returns true so that it gets processed by the following method - when(method.invoke(update)).thenReturn(true); - // Call the function, throws an IllegalStateException if there's an update that can't be processed - utilMethod.accept(update); - } catch (IllegalStateException e) { - throw new RuntimeException( - format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); - } catch (NullPointerException | ReflectiveOperationException e) { - // This is fine, the mock isn't complete and we're only - // looking for IllegalStateExceptions thrown by the method - } - }); + // filter to all these methods of hasXXX (hasPoll, hasMessage, etc...) + .filter(method -> method.getName().startsWith("has")) + // Gotta filter out hashCode + .filter(method -> method.getReturnType().getName().equals("boolean")) + .forEach(method -> { + Update update = mock(Update.class); + try { + // Mock the method and make sure it returns true so that it gets processed by the following method + when(method.invoke(update)).thenReturn(true); + // Call the function, throws an IllegalStateException if there's an update that can't be processed + utilMethod.accept(update); + } catch (IllegalStateException e) { + throw new RuntimeException( + format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); + } catch (NullPointerException | ReflectiveOperationException e) { + // This is fine, the mock isn't complete and we're only + // looking for IllegalStateExceptions thrown by the method + } + }); } private void mockUser(Update update, Message message, User user) { diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java index 7838d07f..6d65e721 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java @@ -5,8 +5,12 @@ import org.telegram.abilitybots.api.objects.Ability; import org.telegram.abilitybots.api.objects.Ability.AbilityBuilder; import org.telegram.abilitybots.api.objects.Flag; import org.telegram.abilitybots.api.objects.Reply; +import org.telegram.abilitybots.api.objects.ReplyCollection; import org.telegram.abilitybots.api.toggle.AbilityToggle; +import java.util.ArrayList; +import java.util.List; + import static org.telegram.abilitybots.api.objects.Ability.builder; import static org.telegram.abilitybots.api.objects.Flag.CALLBACK_QUERY; import static org.telegram.abilitybots.api.objects.Flag.MESSAGE; @@ -15,6 +19,8 @@ import static org.telegram.abilitybots.api.objects.Privacy.ADMIN; import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC; public class DefaultBot extends AbilityBot { + public static final String FIRST_REPLY_KEY_MESSAGE = "first reply key string"; + public static final String SECOND_REPLY_KEY_MESSAGE = "second reply key string"; public DefaultBot(String token, String username, DBContext db) { super(token, username, db); @@ -79,6 +85,24 @@ public class DefaultBot extends AbilityBot { ); } + public ReplyCollection createReplyCollection() { + List replyList = new ArrayList<>(); + replyList.add( + Reply.of( + upd -> silent.send("first reply answer", upd.getMessage().getChatId()), + update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE) + ) + ); + replyList.add( + Reply.of( + upd -> silent.send("second reply answer", upd.getMessage().getChatId()), + update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE) + ) + + ); + return new ReplyCollection(replyList); + } + public Ability testAbility() { return getDefaultBuilder().build(); } From eea4c3adc11dfcc6903b5d25caeace004aed4c1d Mon Sep 17 00:00:00 2001 From: Valentin Afanasiev Date: Tue, 26 Jan 2021 13:33:01 +0300 Subject: [PATCH 04/11] revert indentation changes --- .../abilitybots/api/bot/BaseAbilityBot.java | 48 +++++++++---------- .../abilitybots/api/bot/AbilityBotTest.java | 24 +++++----- 2 files changed, 36 insertions(+), 36 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index 95dae8ec..726e0789 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -248,9 +248,9 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability public Privacy getPrivacy(Update update, int id) { return isCreator(id) ? - CREATOR : isAdmin(id) ? - ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? - GROUP_ADMIN : PUBLIC; + CREATOR : isAdmin(id) ? + ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? + GROUP_ADMIN : PUBLIC; } public boolean isGroupAdmin(Update update, int id) { @@ -260,8 +260,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability public boolean isGroupAdmin(long chatId, int id) { GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) - .orElse(new ArrayList<>()).stream() - .anyMatch(member -> member.getUser().getId() == id); + .orElse(new ArrayList<>()).stream() + .anyMatch(member -> member.getUser().getId() == id); } public boolean isCreator(int id) { @@ -326,17 +326,17 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability DefaultAbilities defaultAbs = new DefaultAbilities(this); Stream defaultAbsStream = stream(DefaultAbilities.class.getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(defaultAbs)) - .filter(ab -> !toggle.isOff(ab)) - .map(toggle::processAbility); + .filter(checkReturnType(Ability.class)) + .map(returnAbility(defaultAbs)) + .filter(ab -> !toggle.isOff(ab)) + .map(toggle::processAbility); // Extract all abilities from every single extension instance abilities = Stream.concat(defaultAbsStream, - extensions.stream() - .flatMap(ext -> stream(ext.getClass().getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(ext)))) + extensions.stream() + .flatMap(ext -> stream(ext.getClass().getMethods()) + .filter(checkReturnType(Ability.class)) + .map(returnAbility(ext)))) // Abilities are immutable, build it respectively .collect(ImmutableMap::builder, (b, a) -> b.put(a.name(), a), @@ -378,15 +378,15 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability private void initStats() { Set enabledStats = Stream.concat( - replies.stream().filter(Reply::statsEnabled).map(Reply::name), - abilities.entrySet().stream() - .filter(entry -> entry.getValue().statsEnabled()) - .map(Map.Entry::getKey)).collect(toSet()); + replies.stream().filter(Reply::statsEnabled).map(Reply::name), + abilities.entrySet().stream() + .filter(entry -> entry.getValue().statsEnabled()) + .map(Map.Entry::getKey)).collect(toSet()); stats = db.getMap(STATS); Set toBeRemoved = difference(stats.keySet(), enabledStats); toBeRemoved.forEach(stats::remove); enabledStats.forEach(abName -> stats.computeIfAbsent(abName, - name -> createStats(abName, 0))); + name -> createStats(abName, 0))); } /** @@ -579,12 +579,12 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability String[] tokens; if (allowContinuousText()) { String abName = abilities.keySet().stream() - .filter(name -> msg.getText().startsWith(format("%s%s", getCommandPrefix(), name))) - .max(comparingInt(String::length)) - .orElse(DEFAULT); + .filter(name -> msg.getText().startsWith(format("%s%s", getCommandPrefix(), name))) + .max(comparingInt(String::length)) + .orElse(DEFAULT); tokens = msg.getText() - .replaceFirst(getCommandPrefix() + abName, "") - .split(getCommandRegexSplit()); + .replaceFirst(getCommandPrefix() + abName, "") + .split(getCommandRegexSplit()); ability = abilities.get(abName); } else { tokens = msg.getText().split(getCommandRegexSplit()); @@ -663,7 +663,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return callable.call(); } catch(Exception ex) { log.error(format("Reply [%s] failed to check for conditions. " + - "Make sure you're safeguarding against all possible updates.", name)); + "Make sure you're safeguarding against all possible updates.", name)); } return false; } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java index 58f513cf..42e87d56 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java @@ -687,25 +687,25 @@ public class AbilityBotTest { private void handlesAllUpdates(Consumer utilMethod) { Arrays.stream(Update.class.getMethods()) - // filter to all these methods of hasXXX (hasPoll, hasMessage, etc...) - .filter(method -> method.getName().startsWith("has")) - // Gotta filter out hashCode - .filter(method -> method.getReturnType().getName().equals("boolean")) - .forEach(method -> { - Update update = mock(Update.class); - try { + // filter to all these methods of hasXXX (hasPoll, hasMessage, etc...) + .filter(method -> method.getName().startsWith("has")) + // Gotta filter out hashCode + .filter(method -> method.getReturnType().getName().equals("boolean")) + .forEach(method -> { + Update update = mock(Update.class); + try { // Mock the method and make sure it returns true so that it gets processed by the following method when(method.invoke(update)).thenReturn(true); // Call the function, throws an IllegalStateException if there's an update that can't be processed utilMethod.accept(update); - } catch (IllegalStateException e) { + } catch (IllegalStateException e) { throw new RuntimeException( - format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); - } catch (NullPointerException | ReflectiveOperationException e) { + format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); + } catch (NullPointerException | ReflectiveOperationException e) { // This is fine, the mock isn't complete and we're only // looking for IllegalStateExceptions thrown by the method - } - }); + } + }); } private void mockUser(Update update, Message message, User user) { From ec4f81b94aaefda671b2032c9c79e11789e09db4 Mon Sep 17 00:00:00 2001 From: Valentin Afanasiev Date: Tue, 26 Jan 2021 13:39:41 +0300 Subject: [PATCH 05/11] revert indentation changes --- .../abilitybots/api/bot/BaseAbilityBot.java | 20 +++++++------- .../abilitybots/api/bot/AbilityBotTest.java | 26 +++++++++---------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index 726e0789..aa2d8605 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -260,8 +260,8 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability public boolean isGroupAdmin(long chatId, int id) { GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) - .orElse(new ArrayList<>()).stream() - .anyMatch(member -> member.getUser().getId() == id); + .orElse(new ArrayList<>()).stream() + .anyMatch(member -> member.getUser().getId() == id); } public boolean isCreator(int id) { @@ -326,17 +326,17 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability DefaultAbilities defaultAbs = new DefaultAbilities(this); Stream defaultAbsStream = stream(DefaultAbilities.class.getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(defaultAbs)) - .filter(ab -> !toggle.isOff(ab)) - .map(toggle::processAbility); + .filter(checkReturnType(Ability.class)) + .map(returnAbility(defaultAbs)) + .filter(ab -> !toggle.isOff(ab)) + .map(toggle::processAbility); // Extract all abilities from every single extension instance abilities = Stream.concat(defaultAbsStream, - extensions.stream() - .flatMap(ext -> stream(ext.getClass().getMethods()) - .filter(checkReturnType(Ability.class)) - .map(returnAbility(ext)))) + extensions.stream() + .flatMap(ext -> stream(ext.getClass().getMethods()) + .filter(checkReturnType(Ability.class)) + .map(returnAbility(ext)))) // Abilities are immutable, build it respectively .collect(ImmutableMap::builder, (b, a) -> b.put(a.name(), a), diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java index 42e87d56..36684043 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java @@ -692,19 +692,19 @@ public class AbilityBotTest { // Gotta filter out hashCode .filter(method -> method.getReturnType().getName().equals("boolean")) .forEach(method -> { - Update update = mock(Update.class); - try { - // Mock the method and make sure it returns true so that it gets processed by the following method - when(method.invoke(update)).thenReturn(true); - // Call the function, throws an IllegalStateException if there's an update that can't be processed - utilMethod.accept(update); - } catch (IllegalStateException e) { - throw new RuntimeException( - format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); - } catch (NullPointerException | ReflectiveOperationException e) { - // This is fine, the mock isn't complete and we're only - // looking for IllegalStateExceptions thrown by the method - } + Update update = mock(Update.class); + try { + // Mock the method and make sure it returns true so that it gets processed by the following method + when(method.invoke(update)).thenReturn(true); + // Call the function, throws an IllegalStateException if there's an update that can't be processed + utilMethod.accept(update); + } catch (IllegalStateException e) { + throw new RuntimeException( + format("Found an update variation that is not handled by the getChatId util method [%s]", method.getName()), e); + } catch (NullPointerException | ReflectiveOperationException e) { + // This is fine, the mock isn't complete and we're only + // looking for IllegalStateExceptions thrown by the method + } }); } From 39a5678543c6710c5bc27b9d633828777b8e8205 Mon Sep 17 00:00:00 2001 From: Valentin Afanasiev Date: Sun, 31 Jan 2021 22:05:52 +0300 Subject: [PATCH 06/11] add comments to BaseAbilityBot.java and static construction method to ReplyCollection.java --- .../abilitybots/api/bot/BaseAbilityBot.java | 6 ++--- .../api/objects/ReplyCollection.java | 15 +++++++++++ .../abilitybots/api/bot/DefaultBot.java | 26 +++++++------------ 3 files changed, 27 insertions(+), 20 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index aa2d8605..8dfa31ac 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -348,14 +348,14 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability .flatMap(ext -> stream(ext.getClass().getMethods()) .filter(checkReturnType(Reply.class)) .map(returnReply(ext))) - .flatMap(Reply::stream); + .flatMap(Reply::stream); + // Extract all replies from extension instances methods, returning ReplyCollection Stream extensionCollectionReplies = extensions.stream() .flatMap(extension -> stream(extension.getClass().getMethods()) .filter(checkReturnType(ReplyCollection.class)) .map(returnReplyCollection(extension)) - .map(ReplyCollection::getReplies)) - .flatMap(Collection::stream); + .flatMap(ReplyCollection::stream)); // Replies can be standalone or attached to abilities, fetch those too Stream abilityReplies = abilities.values().stream() diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java index 887925b8..dbfd91a1 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/ReplyCollection.java @@ -1,7 +1,15 @@ package org.telegram.abilitybots.api.objects; import java.util.Collection; +import java.util.stream.Stream; +import static com.google.common.collect.Lists.newArrayList; + +/** + * A wrapping object containing Replies. Return this in your bot class to get replies registered. + * + * @see Reply + */ public class ReplyCollection { public final Collection replies; @@ -14,4 +22,11 @@ public class ReplyCollection { return replies; } + public Stream stream(){ + return replies.stream(); + } + + public static ReplyCollection of(Reply... replies){ + return new ReplyCollection(newArrayList(replies)); + } } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java index 6d65e721..cf31224d 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java @@ -8,9 +8,6 @@ import org.telegram.abilitybots.api.objects.Reply; import org.telegram.abilitybots.api.objects.ReplyCollection; import org.telegram.abilitybots.api.toggle.AbilityToggle; -import java.util.ArrayList; -import java.util.List; - import static org.telegram.abilitybots.api.objects.Ability.builder; import static org.telegram.abilitybots.api.objects.Flag.CALLBACK_QUERY; import static org.telegram.abilitybots.api.objects.Flag.MESSAGE; @@ -86,21 +83,16 @@ public class DefaultBot extends AbilityBot { } public ReplyCollection createReplyCollection() { - List replyList = new ArrayList<>(); - replyList.add( - Reply.of( - upd -> silent.send("first reply answer", upd.getMessage().getChatId()), - update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE) - ) + return ReplyCollection.of( + Reply.of( + upd -> silent.send("first reply answer", upd.getMessage().getChatId()), + update -> update.getMessage().getText().equalsIgnoreCase(FIRST_REPLY_KEY_MESSAGE) + ), + Reply.of( + upd -> silent.send("second reply answer", upd.getMessage().getChatId()), + update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE) + ) ); - replyList.add( - Reply.of( - upd -> silent.send("second reply answer", upd.getMessage().getChatId()), - update -> update.getMessage().getText().equalsIgnoreCase(SECOND_REPLY_KEY_MESSAGE) - ) - - ); - return new ReplyCollection(replyList); } public Ability testAbility() { From 272be4a79cc2e99d5633b3f2929440a2081cb8f1 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 7 Mar 2021 02:40:17 +0000 Subject: [PATCH 07/11] Fix enforcer rule --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 08cae031..8f39742b 100644 --- a/pom.xml +++ b/pom.xml @@ -67,7 +67,7 @@ ${java.version} ${java.version} - 5.7.0 + 5.7.1 3.6.0 3.6.0 2.11.3 From c7728fbc8acf99c698e5f44270791a5c1424cd7f Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 7 Mar 2021 03:28:24 +0000 Subject: [PATCH 08/11] Fix webhook version and validate username and token is present --- .../api/bot/AbilityWebhookBot.java | 4 +-- .../telegrambots/meta/TelegramBotsApi.java | 27 +++++++++++++-- .../meta/api/methods/updates/SetWebhook.java | 2 +- .../meta/generics/WebhookBot.java | 2 +- .../org/telegram/telegrambots/Constants.java | 4 +-- .../telegrambots/bots/TelegramWebhookBot.java | 2 +- .../updatesreceivers/RestApi.java | 5 +-- .../telegrambots/util/WebhookUtils.java | 33 ++++++++++++++++--- 8 files changed, 62 insertions(+), 17 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityWebhookBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityWebhookBot.java index acbb9f25..c12a3fe2 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityWebhookBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityWebhookBot.java @@ -58,14 +58,14 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo } @Override - public BotApiMethod onWebhookUpdateReceived(Update update) { + public BotApiMethod onWebhookUpdateReceived(Update update) { super.onUpdateReceived(update); return null; } @Override public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { - WebhookUtils.setWebhook(this, setWebhook); + WebhookUtils.setWebhook(this, this, setWebhook); } @Override diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java index 437838fa..b5e72591 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/TelegramBotsApi.java @@ -1,9 +1,11 @@ package org.telegram.telegrambots.meta; +import com.google.common.base.Strings; import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.BotSession; import org.telegram.telegrambots.meta.generics.LongPollingBot; +import org.telegram.telegrambots.meta.generics.TelegramBot; import org.telegram.telegrambots.meta.generics.Webhook; import org.telegram.telegrambots.meta.generics.WebhookBot; @@ -15,8 +17,6 @@ import java.lang.reflect.InvocationTargetException; * Bots manager */ public class TelegramBotsApi { - private static final String webhookUrlFormat = "{0}callback/"; - Class botSessionClass; private boolean useWebhook; ///< True to enable webhook usage private Webhook webhook; ///< Webhook instance @@ -55,6 +55,12 @@ public class TelegramBotsApi { * @param bot the bot to register */ public BotSession registerBot(LongPollingBot bot) throws TelegramApiException { + if (bot == null) { + throw new TelegramApiException("Parameter bot can not be null"); + } + if (!validateBotUsernameAndToken(bot)) { + throw new TelegramApiException("Bot token and username can't be empty"); + } bot.onRegister(); bot.clearWebhook(); BotSession session; @@ -74,18 +80,33 @@ public class TelegramBotsApi { * Register a bot in the api that will receive updates using webhook method * @param bot Bot to register * @param setWebhook Set webhook request to initialize the bot + * + * @apiNote The webhook url will be appended with `/callback/bot.getBotPath()` at the end */ public void registerBot(WebhookBot bot, SetWebhook setWebhook) throws TelegramApiException { if (setWebhook == null) { - throw new TelegramApiException("Parameter setWebhook can not be null or empty"); + throw new TelegramApiException("Parameter setWebhook can not be null"); } if (useWebhook) { if (webhook == null) { throw new TelegramApiException("This instance doesn't support Webhook bot, use correct constructor"); } + if (!validateBotUsernameAndToken(bot)) { + throw new TelegramApiException("Bot token and username can't be empty"); + } bot.onRegister(); webhook.registerWebhook(bot); bot.setWebhook(setWebhook); } } + + /** + * Checks that the username and token are presented + * @param telegramBot bot to register + * @return False if username or token are empty or null, true otherwise + */ + private boolean validateBotUsernameAndToken(TelegramBot telegramBot) { + return !Strings.isNullOrEmpty(telegramBot.getBotToken()) && + !Strings.isNullOrEmpty(telegramBot.getBotUsername()); + } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/SetWebhook.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/SetWebhook.java index 551db122..e660d775 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/SetWebhook.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/SetWebhook.java @@ -50,7 +50,7 @@ public class SetWebhook extends BotApiMethod { @JsonProperty(URL_FIELD) @NonNull - private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration + private String url; ///< HTTPS url to send updates to. Use an empty string to remove webhook integration @JsonProperty(CERTIFICATE_FIELD) private InputFile certificate; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked /** diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/WebhookBot.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/WebhookBot.java index 123099b4..ca00bc35 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/WebhookBot.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/WebhookBot.java @@ -16,7 +16,7 @@ public interface WebhookBot extends TelegramBot { * This method is called when receiving updates via webhook * @param update Update received */ - BotApiMethod onWebhookUpdateReceived(Update update); + BotApiMethod onWebhookUpdateReceived(Update update); /** * Execute setWebhook method to set up the url of the webhook diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java b/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java index b6d13af7..f6766cfe 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/Constants.java @@ -3,9 +3,9 @@ package org.telegram.telegrambots; /** * @author Ruben Bermudez * @version 1.0 - * @brief Constants needed for Telegram Bots API - * @date 20 of June of 2015 + * Constants needed for Telegram Bots API */ public class Constants { public static final int SOCKET_TIMEOUT = 75 * 1000; + public static final String WEBHOOK_URL_PATH = "callback"; } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java index 0cabcee9..5ddee09b 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -23,6 +23,6 @@ public abstract class TelegramWebhookBot extends DefaultAbsSender implements Web @Override public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { - WebhookUtils.setWebhook(this, setWebhook); + WebhookUtils.setWebhook(this, this, setWebhook); } } \ No newline at end of file diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java index a6b4725f..622adecf 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/RestApi.java @@ -2,6 +2,7 @@ package org.telegram.telegrambots.updatesreceivers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -22,7 +23,7 @@ import java.util.concurrent.ConcurrentHashMap; * @version 1.0 * Rest api to for webhook callback function */ -@Path("callback") +@Path(Constants.WEBHOOK_URL_PATH) public class RestApi { private static final Logger log = LoggerFactory.getLogger(RestApi.class); @@ -44,7 +45,7 @@ public class RestApi { public Response updateReceived(@PathParam("botPath") String botPath, Update update) { if (callbacks.containsKey(botPath)) { try { - BotApiMethod response = callbacks.get(botPath).onWebhookUpdateReceived(update); + BotApiMethod response = callbacks.get(botPath).onWebhookUpdateReceived(update); if (response != null) { response.validate(); } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java b/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java index 91a15cc3..15ae6951 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.util; +import com.google.common.base.Strings; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -11,6 +12,7 @@ import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.telegram.telegrambots.Constants; import org.telegram.telegrambots.bots.DefaultAbsSender; import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder; @@ -20,6 +22,7 @@ import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.generics.WebhookBot; import java.io.File; import java.io.IOException; @@ -43,7 +46,7 @@ public final class WebhookUtils { * @apiNote Telegram API parameters will be taken only from SetWebhook object * @apiNote Bot options will be fetched from Bot to set up the HTTP connection */ - public static void setWebhook(DefaultAbsSender bot, SetWebhook setWebhook) throws TelegramApiException { + public static void setWebhook(DefaultAbsSender bot, WebhookBot webhookBot, SetWebhook setWebhook) throws TelegramApiException { setWebhook.validate(); DefaultBotOptions botOptions = bot.getOptions(); @@ -61,7 +64,7 @@ public final class WebhookUtils { HttpPost httppost = new HttpPost(requestUrl); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SetWebhook.URL_FIELD, setWebhook.getUrl(), TEXT_PLAIN_CONTENT_TYPE); + builder.addTextBody(SetWebhook.URL_FIELD, getBotUrl(setWebhook, webhookBot), TEXT_PLAIN_CONTENT_TYPE); if (setWebhook.getMaxConnections() != null) { builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, setWebhook.getMaxConnections().toString(), TEXT_PLAIN_CONTENT_TYPE); } @@ -100,10 +103,10 @@ public final class WebhookUtils { } /** - * @deprecated Use {{@link #setWebhook(DefaultAbsSender, SetWebhook)}} instead + * @deprecated Use {{@link #setWebhook(DefaultAbsSender, WebhookBot, SetWebhook)}} instead */ @Deprecated - public static void setWebhook(DefaultAbsSender bot, String url, String publicCertificatePath) throws TelegramApiRequestException { + public static void setWebhook(DefaultAbsSender bot, WebhookBot webhookBot, String url, String publicCertificatePath) throws TelegramApiRequestException { DefaultBotOptions botOptions = bot.getOptions(); try (CloseableHttpClient httpclient = TelegramHttpClientBuilder.build(botOptions)) { @@ -120,7 +123,7 @@ public final class WebhookUtils { HttpPost httppost = new HttpPost(requestUrl); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addTextBody(SetWebhook.URL_FIELD, url); + builder.addTextBody(SetWebhook.URL_FIELD, getBotUrl(url, webhookBot.getBotPath())); if (botOptions.getMaxWebhookConnections() != null) { builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString()); } @@ -162,4 +165,24 @@ public final class WebhookUtils { throw new TelegramApiRequestException("Error removing old webhook", e); } } + + private static String getBotUrl(SetWebhook setWebhook, WebhookBot webhookBot) { + String externalUrl = setWebhook.getUrl(); + return getBotUrl(externalUrl, webhookBot.getBotPath()); + } + + private static String getBotUrl(String externalUrl, String botPath) { + if (!externalUrl.endsWith("/")) { + externalUrl += "/"; + } + externalUrl += Constants.WEBHOOK_URL_PATH; + if (!Strings.isNullOrEmpty(botPath)) { + if (!botPath.startsWith("/")) { + externalUrl += "/"; + } + externalUrl += botPath; + } + + return externalUrl; + } } From ecca28cedcc9e66dbbfd69d69e630bc320d6d6d5 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 7 Mar 2021 03:29:40 +0000 Subject: [PATCH 09/11] Fix #857 --- .../telegram/telegrambots/meta/api/methods/send/SendAudio.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAudio.java index 1aca6cff..3517fdda 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAudio.java @@ -57,8 +57,6 @@ public class SendAudio extends PartialBotApiMethod { public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; - @NonNull - private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (or Username fro channels) @NonNull @@ -70,6 +68,7 @@ public class SendAudio extends PartialBotApiMethod { private String title; ///< Optional. Title of sent audio private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters private String parseMode; ///< Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + private Integer duration; ///< Integer Duration of the audio in seconds as defined by sender /** * Optional. * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. From 6653ffe9379bac874bbdff63e011f2c825555494 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Tue, 9 Mar 2021 10:59:28 +0000 Subject: [PATCH 10/11] API 5.1 --- TelegramBots.wiki/Changelog.md | 10 +- TelegramBots.wiki/How-To-Update.md | 3 + pom.xml | 2 +- telegrambots-abilities/pom.xml | 4 +- .../abilitybots/api/bot/BaseAbilityBot.java | 24 +-- .../abilitybots/api/bot/DefaultAbilities.java | 26 +-- .../abilitybots/api/objects/Flag.java | 3 + .../abilitybots/api/util/AbilityUtils.java | 22 ++- .../api/bot/AbilityBotI18nTest.java | 6 +- .../abilitybots/api/bot/AbilityBotTest.java | 34 ++-- .../api/bot/ContinuousTextTest.java | 4 +- .../abilitybots/api/bot/DefaultBot.java | 4 +- .../abilitybots/api/bot/ExtensionTest.java | 2 +- .../abilitybots/api/bot/ReplyFlowTest.java | 2 +- .../abilitybots/api/bot/TestUtils.java | 4 +- .../abilitybots/api/db/MapDBContextTest.java | 9 +- telegrambots-chat-session-bot/pom.xml | 4 +- telegrambots-extensions/pom.xml | 4 +- telegrambots-meta/pom.xml | 2 +- .../api/methods/GetUserProfilePhotos.java | 2 +- .../api/methods/SetPassportDataErrors.java | 2 +- .../api/methods/games/GetGameHighScores.java | 2 +- .../meta/api/methods/games/SetGameScore.java | 2 +- .../CreateChatInviteLink.java | 90 +++++++++ .../EditChatInviteLink.java | 98 ++++++++++ .../ExportChatInviteLink.java | 14 +- .../groupadministration/GetChatMember.java | 2 +- .../groupadministration/KickChatMember.java | 15 +- .../PromoteChatMember.java | 21 ++- .../RestrictChatMember.java | 2 +- .../RevokeChatInviteLink.java | 83 +++++++++ .../SetChatAdministratorCustomTitle.java | 2 +- .../groupadministration/UnbanChatMember.java | 2 +- .../meta/api/methods/send/SendDice.java | 12 +- .../api/methods/stickers/AddStickerToSet.java | 2 +- .../methods/stickers/CreateNewStickerSet.java | 2 +- .../methods/stickers/SetStickerSetThumb.java | 2 +- .../methods/stickers/UploadStickerFile.java | 2 +- .../telegrambots/meta/api/objects/Chat.java | 12 +- .../meta/api/objects/ChatInviteLink.java | 53 ++++++ .../meta/api/objects/ChatMember.java | 23 +++ .../meta/api/objects/ChatMemberUpdated.java | 44 +++++ .../meta/api/objects/Contact.java | 9 +- .../telegrambots/meta/api/objects/Dice.java | 6 +- .../meta/api/objects/Message.java | 36 ++++ .../MessageAutoDeleteTimerChanged.java | 29 +++ .../telegrambots/meta/api/objects/Update.java | 26 +++ .../telegrambots/meta/api/objects/User.java | 8 +- .../inlinequery/result/InlineQueryResult.java | 2 + .../api/objects/voicechat/VoiceChatEnded.java | 29 +++ .../VoiceChatParticipantsInvited.java | 33 ++++ .../objects/voicechat/VoiceChatStarted.java | 24 +++ .../meta/test/TestDeserialization.java | 171 ++++++++++++++++-- .../test/apimethods/TestSetGameScore.java | 2 +- telegrambots-spring-boot-starter/pom.xml | 4 +- .../starter/TelegramBotInitializer.java | 5 - telegrambots/pom.xml | 4 +- .../test/BotApiMethodHelperFactory.java | 12 +- 58 files changed, 915 insertions(+), 143 deletions(-) create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/CreateChatInviteLink.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/EditChatInviteLink.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RevokeChatInviteLink.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatInviteLink.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMemberUpdated.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageAutoDeleteTimerChanged.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatEnded.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatParticipantsInvited.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatStarted.java diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index adb8a126..8421a048 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,6 +1,14 @@ +### 5.1.0 ### +1. Update Api version [5.1](https://core.telegram.org/bots/api-changelog#march-9-2021) +2. Bug fixing: #832, #841, #844, #851, #857 +3. Update Spring boot version 2.4.3 +4. Update Gradle docs +5. Added CommandMessage to extensions +6. Abilities: Inject bot instance to reply update consumer support for multiple reply declarations. + ### 5.0.1 ### 1. Fixing couple of bugs from 5.0.0 -2. Buf fixing: #794 +2. Bug fixing: #794 3. Docs updated to reflect usage for version 5.0.0 4. EditMessageText setChatIId(Long) is removed to keep consistency diff --git a/TelegramBots.wiki/How-To-Update.md b/TelegramBots.wiki/How-To-Update.md index 9c1c4733..8bc70685 100644 --- a/TelegramBots.wiki/How-To-Update.md +++ b/TelegramBots.wiki/How-To-Update.md @@ -1,3 +1,6 @@ +### To version 5.1.0 ### +1. All users IDs fields are now Long type as per API guidelines. + ### To version 5.0.0 ### 1. ApiContextInitializer.init(); has been removed and is not required anymore, instead: ```java diff --git a/pom.xml b/pom.xml index 8f39742b..617d75b7 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots pom - 5.0.1 + 5.1.0 telegrambots diff --git a/telegrambots-abilities/pom.xml b/telegrambots-abilities/pom.xml index a5429c14..731661da 100644 --- a/telegrambots-abilities/pom.xml +++ b/telegrambots-abilities/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambots-abilities @@ -84,7 +84,7 @@ org.telegram telegrambots - 5.0.1 + 5.1.0 org.apache.commons diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java index 45975708..d65f0b45 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/BaseAbilityBot.java @@ -113,7 +113,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability // Reply registry private List replies; - public abstract int creatorId(); + public abstract long creatorId(); protected BaseAbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { super(botOptions); @@ -155,28 +155,28 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability /** * @return the map of */ - public Map users() { + public Map users() { return db.getMap(USERS); } /** * @return the map of */ - public Map userIds() { + public Map userIds() { return db.getMap(USER_ID); } /** * @return a blacklist containing all the IDs of the banned users */ - public Set blacklist() { + public Set blacklist() { return db.getSet(BLACKLIST); } /** * @return an admin set of all the IDs of bot administrators */ - public Set admins() { + public Set admins() { return db.getSet(ADMINS); } @@ -246,29 +246,29 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return botUsername; } - public Privacy getPrivacy(Update update, int id) { + public Privacy getPrivacy(Update update, long id) { return isCreator(id) ? CREATOR : isAdmin(id) ? ADMIN : (isGroupUpdate(update) || isSuperGroupUpdate(update)) && isGroupAdmin(update, id) ? GROUP_ADMIN : PUBLIC; } - public boolean isGroupAdmin(Update update, int id) { + public boolean isGroupAdmin(Update update, long id) { return isGroupAdmin(getChatId(update), id); } - public boolean isGroupAdmin(long chatId, int id) { + public boolean isGroupAdmin(long chatId, long id) { GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) .orElse(new ArrayList<>()).stream() .anyMatch(member -> member.getUser().getId() == id); } - public boolean isCreator(int id) { + public boolean isCreator(long id) { return id == creatorId(); } - public boolean isAdmin(Integer id) { + public boolean isAdmin(long id) { return admins().contains(id); } @@ -508,7 +508,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return true; } - int id = user.getId(); + long id = user.getId(); return id == creatorId() || !blacklist().contains(id); } @@ -549,7 +549,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability Update update = trio.a(); User user = AbilityUtils.getUser(update); Privacy privacy; - int id = user.getId(); + long id = user.getId(); privacy = getPrivacy(update, id); diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java index b96f0968..33a211e8 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/DefaultAbilities.java @@ -293,7 +293,7 @@ public final class DefaultAbilities implements AbilityExtension { .input(1) .action(ctx -> { String username = stripTag(ctx.firstArg()); - int userId = getUserIdSendError(username, ctx); + long userId = getUserIdSendError(username, ctx); String bannedUser; // Protection from abuse @@ -304,7 +304,7 @@ public final class DefaultAbilities implements AbilityExtension { bannedUser = addTag(username); } - Set blacklist = bot.blacklist(); + Set blacklist = bot.blacklist(); if (blacklist.contains(userId)) sendMd(ABILITY_BAN_FAIL, ctx, escape(bannedUser)); else { @@ -328,9 +328,9 @@ public final class DefaultAbilities implements AbilityExtension { .input(1) .action(ctx -> { String username = stripTag(ctx.firstArg()); - Integer userId = getUserIdSendError(username, ctx); + Long userId = getUserIdSendError(username, ctx); - Set blacklist = bot.blacklist(); + Set blacklist = bot.blacklist(); if (!blacklist.remove(userId)) bot.silent.sendMd(getLocalizedMessage(ABILITY_UNBAN_FAIL, ctx.user().getLanguageCode(), escape(username)), ctx.chatId()); @@ -352,9 +352,9 @@ public final class DefaultAbilities implements AbilityExtension { .input(1) .action(ctx -> { String username = stripTag(ctx.firstArg()); - Integer userId = getUserIdSendError(username, ctx); + Long userId = getUserIdSendError(username, ctx); - Set admins = bot.admins(); + Set admins = bot.admins(); if (admins.contains(userId)) sendMd(ABILITY_PROMOTE_FAIL, ctx, escape(username)); else { @@ -376,9 +376,9 @@ public final class DefaultAbilities implements AbilityExtension { .input(1) .action(ctx -> { String username = stripTag(ctx.firstArg()); - Integer userId = getUserIdSendError(username, ctx); + Long userId = getUserIdSendError(username, ctx); - Set admins = bot.admins(); + Set admins = bot.admins(); if (admins.remove(userId)) { sendMd(ABILITY_DEMOTE_SUCCESS, ctx, escape(username)); } else { @@ -400,8 +400,8 @@ public final class DefaultAbilities implements AbilityExtension { .privacy(CREATOR) .input(0) .action(ctx -> { - Set admins = bot.admins(); - int id = bot.creatorId(); + Set admins = bot.admins(); + long id = bot.creatorId(); if (admins.contains(id)) send(ABILITY_CLAIM_FAIL, ctx); @@ -420,7 +420,7 @@ public final class DefaultAbilities implements AbilityExtension { * @return the user */ private User getUser(String username) { - Integer id = bot.userIds().get(username.toLowerCase()); + Long id = bot.userIds().get(username.toLowerCase()); if (id == null) { throw new IllegalStateException(format("Could not find ID corresponding to username [%s]", username)); } @@ -434,7 +434,7 @@ public final class DefaultAbilities implements AbilityExtension { * @param id the id of the required user * @return the user */ - private User getUser(int id) { + private User getUser(long id) { User user = bot.users().get(id); if (user == null) { throw new IllegalStateException(format("Could not find user corresponding to id [%d]", id)); @@ -450,7 +450,7 @@ public final class DefaultAbilities implements AbilityExtension { * @param ctx the message context with the originating user * @return the id of the user */ - private int getUserIdSendError(String username, MessageContext ctx) { + private long getUserIdSendError(String username, MessageContext ctx) { try { return getUser(username).getId(); } catch (IllegalStateException ex) { diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Flag.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Flag.java index 9930ad7e..414d08da 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Flag.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/Flag.java @@ -29,6 +29,9 @@ public enum Flag implements Predicate { PRECHECKOUT_QUERY(Update::hasPreCheckoutQuery), POLL(Update::hasPoll), POLL_ANSWER(Update::hasPollAnswer), + MY_CHAT_MEMBER(Update::hasMyChatMember), + CHAT_MEMBER(Update::hasChatMember), + // Message Flags REPLY(upd -> MESSAGE.test(upd) && upd.getMessage().isReply()), diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/util/AbilityUtils.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/util/AbilityUtils.java index 02db0f9a..013ba41d 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/util/AbilityUtils.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/util/AbilityUtils.java @@ -25,7 +25,7 @@ import static org.telegram.abilitybots.api.objects.Flag.*; * Helper and utility methods */ public final class AbilityUtils { - public static User EMPTY_USER = new User(0, "", false); + public static User EMPTY_USER = new User(0L, "", false); private AbilityUtils() { @@ -82,6 +82,10 @@ public final class AbilityUtils { return update.getPreCheckoutQuery().getFrom(); } else if (POLL_ANSWER.test(update)) { return update.getPollAnswer().getUser(); + } else if (MY_CHAT_MEMBER.test(update)) { + return update.getMyChatMember().getFrom(); + } else if (CHAT_MEMBER.test(update)) { + return update.getChatMember().getFrom(); } else if (POLL.test(update)) { return EMPTY_USER; } else { @@ -146,7 +150,7 @@ public final class AbilityUtils { } else if (CALLBACK_QUERY.test(update)) { return update.getCallbackQuery().getMessage().getChatId(); } else if (INLINE_QUERY.test(update)) { - return (long) update.getInlineQuery().getFrom().getId(); + return update.getInlineQuery().getFrom().getId(); } else if (CHANNEL_POST.test(update)) { return update.getChannelPost().getChatId(); } else if (EDITED_CHANNEL_POST.test(update)) { @@ -154,15 +158,19 @@ public final class AbilityUtils { } else if (EDITED_MESSAGE.test(update)) { return update.getEditedMessage().getChatId(); } else if (CHOSEN_INLINE_QUERY.test(update)) { - return (long) update.getChosenInlineQuery().getFrom().getId(); + return update.getChosenInlineQuery().getFrom().getId(); } else if (SHIPPING_QUERY.test(update)) { - return (long) update.getShippingQuery().getFrom().getId(); + return update.getShippingQuery().getFrom().getId(); } else if (PRECHECKOUT_QUERY.test(update)) { - return (long) update.getPreCheckoutQuery().getFrom().getId(); + return update.getPreCheckoutQuery().getFrom().getId(); } else if (POLL_ANSWER.test(update)) { - return (long) update.getPollAnswer().getUser().getId(); + return update.getPollAnswer().getUser().getId(); } else if (POLL.test(update)) { - return (long) EMPTY_USER.getId(); + return EMPTY_USER.getId(); + } else if (MY_CHAT_MEMBER.test(update)) { + return update.getMyChatMember().getChat().getId(); + } else if (CHAT_MEMBER.test(update)) { + return update.getChatMember().getChat().getId(); } else { throw new IllegalStateException("Could not retrieve originating chat ID from update"); } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotI18nTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotI18nTest.java index ada4147f..3175f03d 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotI18nTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotI18nTest.java @@ -19,8 +19,8 @@ import static org.telegram.abilitybots.api.bot.TestUtils.mockContext; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; class AbilityBotI18nTest { - private static final User NO_LANGUAGE_USER = new User(1, "first", false, "last", "username", null, false, false, false); - private static final User ITALIAN_USER = new User(2, "first", false, "last", "username", "it-IT", false, false, false); + private static final User NO_LANGUAGE_USER = new User(1L, "first", false, "last", "username", null, false, false, false); + private static final User ITALIAN_USER = new User(2L, "first", false, "last", "username", "it-IT", false, false, false); private DBContext db; private NoPublicCommandsBot bot; @@ -76,7 +76,7 @@ class AbilityBotI18nTest { } @Override - public int creatorId() { + public long creatorId() { return 1; } } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java index 21f6a6b6..708e54a1 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/AbilityBotTest.java @@ -234,8 +234,8 @@ public class AbilityBotTest { defaultAbs.demoteAdmin().action().accept(context); - Set actual = bot.admins(); - Set expected = emptySet(); + Set actual = bot.admins(); + Set expected = emptySet(); assertEquals(expected, actual, "Could not sudont super-admin"); } @@ -247,8 +247,8 @@ public class AbilityBotTest { defaultAbs.promoteAdmin().action().accept(context); - Set actual = bot.admins(); - Set expected = newHashSet(USER.getId()); + Set actual = bot.admins(); + Set expected = newHashSet(USER.getId()); assertEquals(expected, actual, "Could not sudo user"); } @@ -259,8 +259,8 @@ public class AbilityBotTest { defaultAbs.banUser().action().accept(context); - Set actual = bot.blacklist(); - Set expected = newHashSet(USER.getId()); + Set actual = bot.blacklist(); + Set expected = newHashSet(USER.getId()); assertEquals(expected, actual, "The ban was not emplaced"); } @@ -273,8 +273,8 @@ public class AbilityBotTest { defaultAbs.unbanUser().action().accept(context); - Set actual = bot.blacklist(); - Set expected = newHashSet(); + Set actual = bot.blacklist(); + Set expected = newHashSet(); assertEquals(expected, actual, "The ban was not lifted"); } @@ -290,8 +290,8 @@ public class AbilityBotTest { defaultAbs.banUser().action().accept(context); - Set actual = bot.blacklist(); - Set expected = newHashSet(USER.getId()); + Set actual = bot.blacklist(); + Set expected = newHashSet(USER.getId()); assertEquals(expected, actual, "Impostor was not added to the blacklist"); } @@ -308,8 +308,8 @@ public class AbilityBotTest { defaultAbs.claimCreator().action().accept(context); - Set actual = bot.admins(); - Set expected = newHashSet(CREATOR.getId()); + Set actual = bot.admins(); + Set expected = newHashSet(CREATOR.getId()); assertEquals(expected, actual, "Creator was not properly added to the super admins set"); } @@ -335,8 +335,8 @@ public class AbilityBotTest { bot.addUser(update); - Map expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId()); - Map expectedUsers = ImmutableMap.of(USER.getId(), USER); + Map expectedUserIds = ImmutableMap.of(USER.getUserName(), USER.getId()); + Map expectedUsers = ImmutableMap.of(USER.getId(), USER); assertEquals(expectedUserIds, bot.userIds(), "User was not added"); assertEquals(expectedUsers, bot.users(), "User was not added"); } @@ -350,15 +350,15 @@ public class AbilityBotTest { String newUsername = USER.getUserName() + "-test"; String newFirstName = USER.getFirstName() + "-test"; String newLastName = USER.getLastName() + "-test"; - int sameId = USER.getId(); + long sameId = USER.getId(); User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, "en", false, false, false); mockAlternateUser(update, message, changedUser); bot.addUser(update); - Map expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId()); - Map expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser); + Map expectedUserIds = ImmutableMap.of(changedUser.getUserName(), changedUser.getId()); + Map expectedUsers = ImmutableMap.of(changedUser.getId(), changedUser); assertEquals(bot.userIds(), expectedUserIds, "User was not properly edited"); assertEquals(expectedUsers, expectedUsers, "User was not properly edited"); } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ContinuousTextTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ContinuousTextTest.java index 2604a2ba..381de941 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ContinuousTextTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ContinuousTextTest.java @@ -22,7 +22,7 @@ import static org.telegram.abilitybots.api.objects.Locality.ALL; import static org.telegram.abilitybots.api.objects.Privacy.PUBLIC; public class ContinuousTextTest { - private static final User USER = new User(1, "first", false); + private static final User USER = new User(1L, "first", false); private DBContext db; @@ -71,7 +71,7 @@ public class ContinuousTextTest { } @Override - public int creatorId() { + public long creatorId() { return 1337; } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java index 8330f907..520271f9 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/DefaultBot.java @@ -38,8 +38,8 @@ public class DefaultBot extends AbilityBot { } @Override - public int creatorId() { - return 1337; + public long creatorId() { + return 1337L; } public Ability defaultAbility() { diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ExtensionTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ExtensionTest.java index 6f31c864..67b3e469 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ExtensionTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ExtensionTest.java @@ -47,7 +47,7 @@ class ExtensionTest { } @Override - public int creatorId() { + public long creatorId() { return 0; } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java index 91b02134..30b2e331 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/ReplyFlowTest.java @@ -158,7 +158,7 @@ public class ReplyFlowTest { } @Override - public int creatorId() { + public long creatorId() { return 0; } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/TestUtils.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/TestUtils.java index 5e85b66b..ea36c023 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/TestUtils.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/bot/TestUtils.java @@ -11,8 +11,8 @@ import static org.mockito.Mockito.when; import static org.telegram.abilitybots.api.objects.MessageContext.newContext; public final class TestUtils { - public static final User USER = new User(1, "first", false, "last", "username", null, false, false, false); - public static final User CREATOR = new User(1337, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false); + public static final User USER = new User(1L, "first", false, "last", "username", null, false, false, false); + public static final User CREATOR = new User(1337L, "creatorFirst", false, "creatorLast", "creatorUsername", null, false, false, false); private TestUtils() { diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/db/MapDBContextTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/db/MapDBContextTest.java index 0df5c4c1..20999fa1 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/db/MapDBContextTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/db/MapDBContextTest.java @@ -12,7 +12,6 @@ import java.util.Set; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; -import static com.google.common.collect.Sets.toImmutableEnumSet; import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -59,22 +58,22 @@ class MapDBContextTest { @Test void canRecoverDB() { - Map users = db.getMap(USERS); - Map userIds = db.getMap(USER_ID); + Map users = db.getMap(USERS); + Map 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 originalUsers = newHashMap(users); + Map originalUsers = newHashMap(users); String beforeBackupInfo = db.info(USERS); Object jsonBackup = db.backup(); db.clear(); boolean recovered = db.recover(jsonBackup); - Map recoveredUsers = db.getMap(USERS); + Map recoveredUsers = db.getMap(USERS); String afterRecoveryInfo = db.info(USERS); assertTrue(recovered, "Could not recover database successfully"); diff --git a/telegrambots-chat-session-bot/pom.xml b/telegrambots-chat-session-bot/pom.xml index 4d83e7e2..514ddc1d 100644 --- a/telegrambots-chat-session-bot/pom.xml +++ b/telegrambots-chat-session-bot/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambots-chat-session-bot @@ -84,7 +84,7 @@ org.telegram telegrambots - 5.0.1 + 5.1.0 diff --git a/telegrambots-extensions/pom.xml b/telegrambots-extensions/pom.xml index 6e6fad0d..87388fc1 100644 --- a/telegrambots-extensions/pom.xml +++ b/telegrambots-extensions/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambotsextensions @@ -75,7 +75,7 @@ org.telegram telegrambots - 5.0.1 + 5.1.0 diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index e5b7595e..3a1c883d 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambots-meta diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetUserProfilePhotos.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetUserProfilePhotos.java index b1c3ae5d..11431671 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetUserProfilePhotos.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetUserProfilePhotos.java @@ -41,7 +41,7 @@ public class GetUserProfilePhotos extends BotApiMethod { @JsonProperty(USERID_FIELD) @NonNull - private Integer userId; ///< Unique identifier of the target user + private Long userId; ///< Unique identifier of the target user /** * Optional. Sequential number of the first photo to be returned. By default, all photos are returned. */ diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/SetPassportDataErrors.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/SetPassportDataErrors.java index c8a5eeb3..0cf656e1 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/SetPassportDataErrors.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/SetPassportDataErrors.java @@ -41,7 +41,7 @@ public class SetPassportDataErrors extends BotApiMethod { @JsonProperty(USERID_FIELD) @NonNull - private Integer userId; ///< User identifier + private Long userId; ///< User identifier @JsonProperty(ERRORS_FIELD) @NonNull @Singular diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/GetGameHighScores.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/GetGameHighScores.java index 03422be2..ea117134 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/GetGameHighScores.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/GetGameHighScores.java @@ -74,7 +74,7 @@ public class GetGameHighScores extends BotApiMethod> { private String inlineMessageId; ///< Optional Required if chat_id and message_id are not specified. Identifier of the inline message @JsonProperty(USER_ID_FIELD) @NonNull - private Integer userId; /// { private Boolean disableEditMessage; ///< Optional Pass True, if the game message should not be automatically edited to include the current scoreboard. Defaults to False @JsonProperty(USER_ID_FIELD) @NonNull - private Integer userId; ///< User identifier + private Long userId; ///< User identifier @JsonProperty(SCORE_FIELD) @NonNull private Integer score; ///< New score, must be positive diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/CreateChatInviteLink.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/CreateChatInviteLink.java new file mode 100644 index 00000000..1daad76f --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/CreateChatInviteLink.java @@ -0,0 +1,90 @@ +package org.telegram.telegrambots.meta.api.methods.groupadministration; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.ChatInviteLink; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * Use this method to create an additional invite link for a chat. + * + * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + * + * The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@RequiredArgsConstructor +@Builder +public class CreateChatInviteLink extends BotApiMethod { + public static final String PATH = "createChatInviteLink"; + + private static final String CHATID_FIELD = "chat_id"; + private static final String EXPIREDATE_FIELD = "expire_date"; + private static final String MEMBERLIMIT_FIELD = "member_limit"; + + @JsonProperty(CHATID_FIELD) + @NonNull + private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) + @JsonProperty(EXPIREDATE_FIELD) + private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire + /** + * Optional. + * + * Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + */ + @JsonProperty(MEMBERLIMIT_FIELD) + private Integer memberLimit; + + + @Override + public String getMethod() { + return PATH; + } + + @Override + public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error creating invite link", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null || chatId.isEmpty()) { + throw new TelegramApiValidationException("ChatId can't be empty", this); + } + if (memberLimit != null && (memberLimit < 1 || memberLimit > 99999)) { + throw new TelegramApiValidationException("MemberLimit must be between 1 and 99999", this); + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/EditChatInviteLink.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/EditChatInviteLink.java new file mode 100644 index 00000000..86e8889b --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/EditChatInviteLink.java @@ -0,0 +1,98 @@ +package org.telegram.telegrambots.meta.api.methods.groupadministration; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.base.Strings; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.ChatInviteLink; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * Use this method to edit a non-primary invite link created by the bot. + * + * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + * + * Returns the edited invite link as a ChatInviteLink object. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@RequiredArgsConstructor +@Builder +public class EditChatInviteLink extends BotApiMethod { + public static final String PATH = "createChatInviteLink"; + + private static final String CHATID_FIELD = "chat_id"; + private static final String INVITELINK_FIELD = "invite_link"; + private static final String EXPIREDATE_FIELD = "expire_date"; + private static final String MEMBERLIMIT_FIELD = "member_limit"; + + @JsonProperty(CHATID_FIELD) + @NonNull + private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) + @JsonProperty(INVITELINK_FIELD) + @NonNull + private String inviteLink; ///< The invite link to edit + @JsonProperty(EXPIREDATE_FIELD) + private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire + /** + * Optional. + * + * Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + */ + @JsonProperty(MEMBERLIMIT_FIELD) + private Integer memberLimit; + + + @Override + public String getMethod() { + return PATH; + } + + @Override + public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error creating invite link", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (Strings.isNullOrEmpty(chatId)) { + throw new TelegramApiValidationException("ChatId can't be empty", this); + } + if (Strings.isNullOrEmpty(inviteLink)) { + throw new TelegramApiValidationException("InviteLink can't be empty", this); + } + if (memberLimit != null && (memberLimit < 1 || memberLimit > 99999)) { + throw new TelegramApiValidationException("MemberLimit must be between 1 and 99999", this); + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/ExportChatInviteLink.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/ExportChatInviteLink.java index 3f58b587..231d1e61 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/ExportChatInviteLink.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/ExportChatInviteLink.java @@ -20,8 +20,16 @@ import java.io.IOException; /** * @author Ruben Bermudez * @version 3.1 - * Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the - * chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success. + * Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. + * + * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + * + * Returns the new invite link as String on success. + * + * @apiNote Each administrator in a chat generates their own invite links. + * Bots can't use invite links generated by other administrators. + * If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. + * If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again. */ @EqualsAndHashCode(callSuper = false) @Getter @@ -37,7 +45,7 @@ public class ExportChatInviteLink extends BotApiMethod { @JsonProperty(CHATID_FIELD) @NonNull - private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @Override public String getMethod() { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMember.java index d42252d5..a07631b2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMember.java @@ -42,7 +42,7 @@ public class GetChatMember extends BotApiMethod { private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(USERID_FIELD) @NonNull - private Integer userId; ///< Unique identifier of the target user + private Long userId; ///< Unique identifier of the target user @Override public String getMethod() { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java index 86ca18a8..56fd0326 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java @@ -47,15 +47,28 @@ public class KickChatMember extends BotApiMethod { private static final String CHATID_FIELD = "chat_id"; private static final String USER_ID_FIELD = "user_id"; private static final String UNTILDATE_FIELD = "until_date"; + private static final String REVOKEMESSAGES_FIELD = "revoke_messages"; @JsonProperty(CHATID_FIELD) @NonNull private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(USER_ID_FIELD) @NonNull - private Integer userId; ///< Required. Unique identifier of the target user + private Long userId; ///< Required. Unique identifier of the target user @JsonProperty(UNTILDATE_FIELD) private Integer untilDate; ///< Optional. Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever + /** + * Optional + * + * Pass True to delete all messages from the chat for the user that is being removed. + * + * If False, the user will be able to see messages in the group that were sent before the user was removed. + * + * Always True for supergroups and channels. + */ + @JsonProperty(REVOKEMESSAGES_FIELD) + private Boolean revokeMessages; + @JsonIgnore public void setUntilDateInstant(Instant instant) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/PromoteChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/PromoteChatMember.java index ad8f5116..505691a9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/PromoteChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/PromoteChatMember.java @@ -48,13 +48,15 @@ public class PromoteChatMember extends BotApiMethod { private static final String CANPINMESSAGES_FIELD = "can_pin_messages"; private static final String CANPROMOTEMEMBERS_FIELD = "can_promote_members"; private static final String ISANONYMOUS_FIELD = "is_anonymous"; + private static final String CANMANAGECHAT_FIELD = "can_manage_chat"; + private static final String CANMANAGEVOICECHATS_FIELD = "can_manage_voice_chats"; @JsonProperty(CHATID_FIELD) @NonNull private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(USER_ID_FIELD) @NonNull - private Integer userId; ///< Required. Unique identifier of the target user + private Long userId; ///< Required. Unique identifier of the target user @JsonProperty(CANCHANGEINFORMATION_FIELD) private Boolean canChangeInformation; ///< Optional. Pass True, if the administrator can change chat title, photo and other settings @JsonProperty(CANPOSTMESSAGES_FIELD) @@ -73,6 +75,23 @@ public class PromoteChatMember extends BotApiMethod { private Boolean canPromoteMembers; ///< Optional. Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administators that were appointed by the him) @JsonProperty(ISANONYMOUS_FIELD) private Boolean isAnonymous; ///< Optional. Pass True, if the administrator's presence in the chat is hidden + /** + * Optional + * + * Pass True, if the administrator can access the chat event log, chat statistics, message statistics in channels, + * see channel members, see anonymous administrators in supergoups and ignore slow mode. + * + * Implied by any other administrator privilege + */ + @JsonProperty(CANMANAGECHAT_FIELD) + private Boolean canManageChat; + /** + * Optional. + * + * Pass True, if the administrator can manage voice chats, supergroups only + */ + @JsonProperty(CANMANAGEVOICECHATS_FIELD) + private Boolean canManageVoiceChats; @Override public String getMethod() { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java index d4f8acee..0ea56543 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java @@ -57,7 +57,7 @@ public class RestrictChatMember extends BotApiMethod { private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(USER_ID_FIELD) @NonNull - private Integer userId; ///< Required. Unique identifier of the target user + private Long userId; ///< Required. Unique identifier of the target user /** * Optional * Date when restrictions will be lifted for the user, unix time. diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RevokeChatInviteLink.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RevokeChatInviteLink.java new file mode 100644 index 00000000..f230421e --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RevokeChatInviteLink.java @@ -0,0 +1,83 @@ +package org.telegram.telegrambots.meta.api.methods.groupadministration; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.base.Strings; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.ChatInviteLink; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * Use this method to revoke an invite link created by the bot. + * + * If the primary link is revoked, a new link is automatically generated. + * + * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. + * + * Returns the revoked invite link as ChatInviteLink object. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class RevokeChatInviteLink extends BotApiMethod { + public static final String PATH = "createChatInviteLink"; + + private static final String CHATID_FIELD = "chat_id"; + private static final String INVITELINK_FIELD = "invite_link"; + + @JsonProperty(CHATID_FIELD) + @NonNull + private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) + @JsonProperty(INVITELINK_FIELD) + @NonNull + private String inviteLink; ///< The invite link to revoke + + @Override + public String getMethod() { + return PATH; + } + + @Override + public ChatInviteLink deserializeResponse(String answer) throws TelegramApiRequestException { + try { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>(){}); + if (result.getOk()) { + return result.getResult(); + } else { + throw new TelegramApiRequestException("Error creating invite link", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (Strings.isNullOrEmpty(chatId)) { + throw new TelegramApiValidationException("ChatId can't be empty", this); + } + if (Strings.isNullOrEmpty(inviteLink)) { + throw new TelegramApiValidationException("InviteLink can't be empty", this); + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatAdministratorCustomTitle.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatAdministratorCustomTitle.java index 05e5c7ae..b9e313e2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatAdministratorCustomTitle.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatAdministratorCustomTitle.java @@ -42,7 +42,7 @@ public class SetChatAdministratorCustomTitle extends BotApiMethod { private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(USERID_FIELD) @NonNull - private Integer userId; ///< Unique identifier of the target user + private Long userId; ///< Unique identifier of the target user @JsonProperty(CUSTOMTITLE_FIELD) @NonNull private String customTitle; ///< New custom title for the administrator; 0-16 characters, emoji are not allowed diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/UnbanChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/UnbanChatMember.java index f3b31ea1..5b05e43b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/UnbanChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/UnbanChatMember.java @@ -50,7 +50,7 @@ public class UnbanChatMember extends BotApiMethod { private String chatId; ///< Required. Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(USERID_FIELD) @NonNull - private Integer userId; ///< Required. Unique identifier of the target user + private Long userId; ///< Required. Unique identifier of the target user @JsonProperty(ONLYISBANNED_FIELD) private Boolean onlyIfBanned; ///< Optional. Do nothing if the user is not banned diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDice.java index f18f455b..fbc86a1e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDice.java @@ -37,7 +37,7 @@ import java.util.List; @AllArgsConstructor @Builder public class SendDice extends BotApiMethod { - private static final List VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "πŸ€", "⚽", "🎰")); + private static final List VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "πŸ€", "⚽", "🎳", "🎰")); public static final String PATH = "sendDice"; @@ -52,13 +52,17 @@ public class SendDice extends BotApiMethod { @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) /** + * Optional. + * * Emoji on which the dice throw animation is based. - * Currently, must be one of β€œπŸŽ²β€, β€œπŸŽ―β€, β€œπŸ€β€, β€œβš½β€, or β€œπŸŽ°β€. - * Dice can have values 1-6 for β€œπŸŽ²β€ and β€œπŸŽ―β€, values 1-5 for β€œπŸ€β€ and β€œβš½β€, and values 1-64 for β€œπŸŽ°β€. + * + * Currently, must be one of β€œπŸŽ²β€, β€œπŸŽ―β€, β€œπŸ€β€, β€œβš½β€, β€œπŸŽ³β€, or β€œπŸŽ°β€. + * + * Dice can have values 1-6 for β€œπŸŽ²β€, β€œπŸŽ―β€ and β€œπŸŽ³β€, values 1-5 for β€œπŸ€β€ and β€œβš½β€, and values 1-64 for β€œπŸŽ°β€. + * * Defaults to β€œπŸŽ²β€ */ @JsonProperty(EMOJI_FIELD) - @NonNull private String emoji; @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/AddStickerToSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/AddStickerToSet.java index 7429c625..bbe032ae 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/AddStickerToSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/AddStickerToSet.java @@ -48,7 +48,7 @@ public class AddStickerToSet extends PartialBotApiMethod { public static final String MASKPOSITION_FIELD = "mask_position"; @NonNull - private Integer userId; ///< User identifier of sticker set owner + private Long userId; ///< User identifier of sticker set owner @NonNull private String name; ///< Sticker set name @NonNull diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/CreateNewStickerSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/CreateNewStickerSet.java index e324098e..05232f2a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/CreateNewStickerSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/CreateNewStickerSet.java @@ -47,7 +47,7 @@ public class CreateNewStickerSet extends PartialBotApiMethod { public static final String MASKPOSITION_FIELD = "mask_position"; @NonNull - private Integer userId; ///< User identifier of created sticker set owner + private Long userId; ///< User identifier of created sticker set owner /** * Name of sticker set, to be used in t.me/addstickers/ URLs. * Can contain only english letters, digits and underscores. diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerSetThumb.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerSetThumb.java index 87d8f22e..62836002 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerSetThumb.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerSetThumb.java @@ -40,7 +40,7 @@ public class SetStickerSetThumb extends BotApiMethod { @NonNull private String name; ///< Sticker set name @NonNull - private Integer userId; ///< User identifier of the sticker set owner + private Long userId; ///< User identifier of the sticker set owner /** * A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, * or a TGS animation with the thumbnail up to 32 kilobytes in size; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/UploadStickerFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/UploadStickerFile.java index d64b006b..8dd5b304 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/UploadStickerFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/UploadStickerFile.java @@ -38,7 +38,7 @@ public class UploadStickerFile extends PartialBotApiMethod { public static final String PNGSTICKER_FIELD = "png_sticker"; @NonNull - private Integer userId; ///< User identifier of sticker file owner + private Long userId; ///< User identifier of sticker file owner /** * Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, * and either width or height must be exactly 512px. More info on Sending Files Β» diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Chat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Chat.java index 67da7b76..80c9926f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Chat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Chat.java @@ -45,6 +45,7 @@ public class Chat implements BotApiObject { private static final String SLOWMODEDELAY_FIELD = "slow_mode_delay"; private static final String LINKEDCHATID_FIELD = "linked_chat_id"; private static final String LOCATION_FIELD = "location"; + private static final String MESSAGEAUTODELETETIME_FIELD = "message_auto_delete_time"; private static final String USERCHATTYPE = "private"; private static final String GROUPCHATTYPE = "group"; @@ -80,14 +81,8 @@ public class Chat implements BotApiObject { private ChatPhoto photo; ///< Optional. Chat photo. Returned only in getChat. @JsonProperty(DESCRIPTION_FIELD) private String description; ///< Optional. Description, for groups, supergroups and channel chats. Returned only in getChat. - /** - * Optional. Chat invite link, for groups, supergroups and channel chats. - * Each administrator in a chat generates their own invite links, so the bot must first generate the link using - * exportChatInviteLink. - * Each Returned only in getChat. - */ @JsonProperty(INVITELINK_FIELD) - private String inviteLink; + private String inviteLink; ///< Optional. Primary invite link, for groups, supergroups and channel chats. Returned only in getChat. @JsonProperty(PINNEDMESSAGE_FIELD) private Message pinnedMessage; ///< Optional. The most recent pinned message (by sending date). Returned only in getChat. @JsonProperty(STICKERSETNAME_FIELD) @@ -119,6 +114,9 @@ public class Chat implements BotApiObject { private Long linkedChatId; @JsonProperty(LOCATION_FIELD) private ChatLocation location; ///< Optional. For supergroups, the location to which the supergroup is connected. Returned only in getChat. + @JsonProperty(MESSAGEAUTODELETETIME_FIELD) + private Integer messageAutoDeleteTime; ///< Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat. + @JsonIgnore public Boolean isGroupChat() { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatInviteLink.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatInviteLink.java new file mode 100644 index 00000000..9ebc4210 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatInviteLink.java @@ -0,0 +1,53 @@ +package org.telegram.telegrambots.meta.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * Represents an invite link for a chat. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class ChatInviteLink implements BotApiObject { + private static final String INVITELINK_FIELD = "invite_link"; + private static final String CREATOR_FIELD = "creator"; + private static final String ISPRIMARY_FIELD = "is_primary"; + private static final String ISREVOKED_FIELD = "is_revoked"; + private static final String EXPIREDATE_FIELD = "expire_date"; + private static final String MEMBERLIMIT_FIELD = "member_limit"; + + /** + * The invite link. + * If the link was created by another chat administrator, then the second part of the link will be replaced with β€œβ€¦β€. + */ + @JsonProperty(INVITELINK_FIELD) + private String inviteLink; + @JsonProperty(CREATOR_FIELD) + private User creator; ///< Creator of the link + @JsonProperty(ISPRIMARY_FIELD) + private Boolean isPrimary; ///< True, if the link is primary + @JsonProperty(ISREVOKED_FIELD) + private Boolean isRevoked; ///< True, if the link is revoked + @JsonProperty(EXPIREDATE_FIELD) + private Integer expireDate; ///< Optional. Point in time (Unix timestamp) when the link will expire or has been expired + /** + * Optional. + * + * Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + */ + @JsonProperty(MEMBERLIMIT_FIELD) + private Integer memberLimit; +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java index 66d2e257..99b5e212 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java @@ -43,6 +43,8 @@ public class ChatMember implements BotApiObject { private static final String ISMEMBER_FIELD = "is_member"; private static final String CUSTOMTITLE_FIELD = "custom_title"; private static final String ISANONYMOUS_FIELD = "is_anonymous"; + private static final String CANMANAGECHAT_FIELD = "can_manage_chat"; + private static final String CANMANAGEVOICECHATS_FIELD = "can_manage_voice_chats"; @JsonProperty(USER_FIELD) private User user; ///< Information about the user @@ -84,6 +86,27 @@ public class ChatMember implements BotApiObject { private String customTitle; ///< Optional. Owner and administrators only. Custom title for this user @JsonProperty(ISANONYMOUS_FIELD) private Boolean isAnonymous; ///< Optional. Owner and administrators only. True, if the user's presence in the chat is hidden + /** + * Optional. + * + * Administrators only. + * + * True, if the administrator can access the chat event log, chat statistics, message statistics in channels, + * see channel members, see anonymous administrators in supergoups and ignore slow mode. + * + * Implied by any other administrator privilege + */ + @JsonProperty(CANMANAGECHAT_FIELD) + private Boolean canManageChat; + /** + * Optional. + * + * Administrators only. + * + * True, if the administrator can manage voice chats; groups and supergroups only + */ + @JsonProperty(CANMANAGEVOICECHATS_FIELD) + private Boolean canManageVoiceChats; public Instant getUntilDateAsInstant() { if (untilDate == null) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMemberUpdated.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMemberUpdated.java new file mode 100644 index 00000000..898cdf5c --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMemberUpdated.java @@ -0,0 +1,44 @@ +package org.telegram.telegrambots.meta.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 5.1 + * This object represents changes in the status of a chat member. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class ChatMemberUpdated implements BotApiObject { + private static final String CHAT_FIELD = "chat"; + private static final String FROM_FIELD = "from"; + private static final String DATE_FIELD = "date"; + private static final String OLDCHATMEMBER_FIELD = "old_chat_member"; + private static final String NEWCHATMEMBER_FIELD = "new_chat_member"; + private static final String INVITELINK_FIELD = "invite_link"; + + @JsonProperty(CHAT_FIELD) + private Chat chat; ///< Chat the user belongs to + @JsonProperty(FROM_FIELD) + private User from; ///< Performer of the action, which resulted in the change + @JsonProperty(DATE_FIELD) + private Integer date; ///< Date the change was done in Unix time + @JsonProperty(OLDCHATMEMBER_FIELD) + private ChatMember oldChatMember; ///< Previous information about the chat member + @JsonProperty(NEWCHATMEMBER_FIELD) + private ChatMember newChatMember; ///< New information about the chat member + @JsonProperty(INVITELINK_FIELD) + private ChatInviteLink inviteLink; ///< Optional. Chat invite link, which was used by the user to join the chat; for joining by invite link events only. + +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Contact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Contact.java index 580dbcb5..29f27fc8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Contact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Contact.java @@ -34,8 +34,15 @@ public class Contact implements BotApiObject { private String firstName; ///< Contact's first name @JsonProperty(LASTNAME_FIELD) private String lastName; ///< Optional. Contact's last name + /** + * Optional. + * Contact's user identifier in Telegram. + * + * @apiNote This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. + * But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + */ @JsonProperty(USERID_FIELD) - private Integer userID; ///< Optional. Contact's user identifier in Telegram + private Long userId; ///< Optional. Contact's user identifier in Telegram @JsonProperty(VCARD_FIELD) private String vCard; ///< Optional. Additional data about the contact in the form of a vCard } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Dice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Dice.java index 383ba043..35267579 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Dice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Dice.java @@ -25,9 +25,9 @@ public class Dice implements BotApiObject { private static final String EMOJI_FIELD = "emoji"; /** - * Value of the dice: - * 1-6 for β€œπŸŽ²β€ and β€œπŸŽ―β€ base emoji - * 1-5 for β€œπŸ€β€ and β€œβš½β€ base emoji + * Value of the dice, + * 1-6 for β€œπŸŽ²β€, β€œπŸŽ―β€ and β€œπŸŽ³β€ base emoji, + * 1-5 for β€œπŸ€β€ and β€œβš½β€ base emoji, * 1-64 for β€œπŸŽ°β€ base emoji */ @JsonProperty(VALUE_FIELD) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Message.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Message.java index af516a77..0fda1ac2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Message.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Message.java @@ -17,6 +17,9 @@ import org.telegram.telegrambots.meta.api.objects.payments.SuccessfulPayment; import org.telegram.telegrambots.meta.api.objects.polls.Poll; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.stickers.Sticker; +import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatEnded; +import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatParticipantsInvited; +import org.telegram.telegrambots.meta.api.objects.voicechat.VoiceChatStarted; import java.util.ArrayList; import java.util.List; @@ -84,6 +87,10 @@ public class Message implements BotApiObject { private static final String VIABOT_FIELD = "via_bot"; private static final String SENDERCHAT_FIELD = "sender_chat"; private static final String PROXIMITYALERTTRIGGERED_FIELD = "proximity_alert_triggered"; + private static final String MESSAGEAUTODELETETIMERCHANGED_FIELD = "message_auto_delete_timer_changed\t"; + private static final String VOICECHATSTARTED_FIELD = "voice_chat_started"; + private static final String VOICECHATENDED_FIELD = "voice_chat_ended"; + private static final String VOICECHATPARTICIPANTSINVITED_FIELD = "voice_chat_participants_invited"; @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Integer Unique message identifier @@ -251,6 +258,15 @@ public class Message implements BotApiObject { */ @JsonProperty(PROXIMITYALERTTRIGGERED_FIELD) private ProximityAlertTriggered proximityAlertTriggered; + @JsonProperty(MESSAGEAUTODELETETIMERCHANGED_FIELD) + private MessageAutoDeleteTimerChanged messageAutoDeleteTimerChanged; ///< Optional. Service message: auto-delete timer settings changed in the chat + @JsonProperty(VOICECHATSTARTED_FIELD) + private VoiceChatStarted voiceChatStarted; ///< Optional. Service message: voice chat started + @JsonProperty(VOICECHATENDED_FIELD) + private VoiceChatEnded voiceChatEnded; ///< Optional. Service message: voice chat ended + @JsonProperty(VOICECHATPARTICIPANTSINVITED_FIELD) + private VoiceChatParticipantsInvited voiceChatParticipantsInvited; ///< Optional. Service message: new members invited to a voice chat + public List getEntities() { if (entities != null) { @@ -413,4 +429,24 @@ public class Message implements BotApiObject { public boolean hasReplyMarkup() { return replyMarkup != null; } + + @JsonIgnore + private boolean hasMessageAutoDeleteTimerChanged() { + return messageAutoDeleteTimerChanged != null; + } + + @JsonIgnore + private boolean hasVoiceChatStarted() { + return voiceChatStarted != null; + } + + @JsonIgnore + private boolean hasVoiceChatEnded() { + return voiceChatEnded != null; + } + + @JsonIgnore + private boolean hasVoiceChatParticipantsInvited() { + return voiceChatParticipantsInvited != null; + } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageAutoDeleteTimerChanged.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageAutoDeleteTimerChanged.java new file mode 100644 index 00000000..65c487ab --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageAutoDeleteTimerChanged.java @@ -0,0 +1,29 @@ +package org.telegram.telegrambots.meta.api.objects; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * This object represents a service message about a change in auto-delete timer settings. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class MessageAutoDeleteTimerChanged implements BotApiObject { + private static final String MESSAGEAUTODELETETIME_FIELD = "message_auto_delete_time"; + + @JsonProperty(MESSAGEAUTODELETETIME_FIELD) + private Integer messageAutoDeleteTime; ///< New auto-delete time for messages in the chat +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Update.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Update.java index 6bae4a45..d56697f9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Update.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Update.java @@ -42,6 +42,8 @@ public class Update implements BotApiObject { private static final String PRE_CHECKOUT_QUERY_FIELD = "pre_checkout_query"; private static final String POLL_FIELD = "poll"; private static final String POLLANSWER_FIELD = "poll_answer"; + private static final String MYCHATMEMBER_FIELD = "my_chat_member"; + private static final String CHATMEMBER_FIELD = "chat_member"; @JsonProperty(UPDATEID_FIELD) private Integer updateId; @@ -73,6 +75,22 @@ public class Update implements BotApiObject { */ @JsonProperty(POLLANSWER_FIELD) private PollAnswer pollAnswer; + /** + * Optional. + * + * The bot's chat member status was updated in a chat. + * For private chats, this update is received only when the bot is blocked or unblocked by the user. + */ + @JsonProperty(MYCHATMEMBER_FIELD) + private ChatMemberUpdated myChatMember; + /** + * Optional. + * + * A chat member's status was updated in a chat. + * The bot must be an administrator in the chat and must explicitly specify β€œchat_member” in the list of allowed_updates to receive these updates. + */ + @JsonProperty(CHATMEMBER_FIELD) + private ChatMemberUpdated chatMember; public boolean hasMessage() { return message != null; @@ -117,4 +135,12 @@ public class Update implements BotApiObject { public boolean hasPollAnswer() { return pollAnswer != null; } + + public boolean hasMyChatMember() { + return myChatMember != null; + } + + public boolean hasChatMember() { + return chatMember != null; + } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/User.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/User.java index 28c18079..883fe005 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/User.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/User.java @@ -35,9 +35,15 @@ public class User implements BotApiObject { private static final String CANREADALLGROUPMESSAGES_FIELD = "can_read_all_group_messages"; private static final String SUPPORTINLINEQUERIES_FIELD = "supports_inline_queries"; + /** + * Unique identifier for this user or bot. + * + * @apiNote This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. + * But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. + */ @JsonProperty(ID_FIELD) @NonNull - private Integer id; ///< Unique identifier for this user or bot + private Long id; ///< Unique identifier for this user or bot @JsonProperty(FIRSTNAME_FIELD) @NonNull private String firstName; ///< Userβ€˜s or bot’s first name diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResult.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResult.java index 67d7c6b0..c7b028e6 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResult.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResult.java @@ -9,6 +9,8 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.result.serializati * @author Ruben Bermudez * @version 1.0 * This object represents one result of an inline query. + * + * @apiNote All URLs passed in inline query results will be available to end users and therefore must be assumed to be public. */ @JsonDeserialize(using = InlineQueryResultDeserializer.class) public interface InlineQueryResult extends Validable, BotApiObject { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatEnded.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatEnded.java new file mode 100644 index 00000000..07bc282c --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatEnded.java @@ -0,0 +1,29 @@ +package org.telegram.telegrambots.meta.api.objects.voicechat; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * This object represents a service message about a voice chat ended in the chat. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class VoiceChatEnded implements BotApiObject { + private static final String DURATION_FIELD = "duration"; + + @JsonProperty(DURATION_FIELD) + private Integer duration; ///< Voice chat duration; in seconds +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatParticipantsInvited.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatParticipantsInvited.java new file mode 100644 index 00000000..d35ea25c --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatParticipantsInvited.java @@ -0,0 +1,33 @@ +package org.telegram.telegrambots.meta.api.objects.voicechat; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; +import org.telegram.telegrambots.meta.api.objects.User; + +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * This object represents a service message about new members invited to a voice chat. + * + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class VoiceChatParticipantsInvited implements BotApiObject { + private static final String USERS_FIELD = "users"; + + @JsonProperty(USERS_FIELD) + private List users; ///< Optional. New members that were invited to the voice chat +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatStarted.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatStarted.java new file mode 100644 index 00000000..fe55ef03 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/voicechat/VoiceChatStarted.java @@ -0,0 +1,24 @@ +package org.telegram.telegrambots.meta.api.objects.voicechat; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; + +/** + * @author Ruben Bermudez + * @version 5.1 + * + * This object represents a service message about a voice chat started in the chat. + * + * Currently holds no information. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +public class VoiceChatStarted implements BotApiObject { +} diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestDeserialization.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestDeserialization.java index b89560bb..4c682eda 100644 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestDeserialization.java +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestDeserialization.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.meta.test; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -28,7 +29,9 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -63,12 +66,24 @@ class TestDeserialization { "\"message\":{\"message_id\":6,\"from\":{\"id\":1234567,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"en\"},\"chat\":{\"id\":-1556359722345678,\"title\":\"test group\",\"type\":\"supergroup\"},\"date\":1604163105,\"new_chat_members\":[{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing\",\"username\":\"TestingBot\"}]}}]}"; ArrayList response = new GetUpdates().deserializeResponse(updateText); + assertEquals(11, response.size()); JsonNode realArray = mapper.readTree(updateText).get("result"); + assertUpdates(response, realArray); + } + + private void assertUpdates(ArrayList response, JsonNode realArray) throws JsonProcessingException { + Map updateMap = new HashMap<>(); for (int i = 0; i < realArray.size(); i++) { - JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i))); - JsonNode realUpdate = realArray.get(i); + JsonNode update = realArray.get(i); + updateMap.put(update.get("update_id").asInt(), update); + } + + for (Update update : response) { + Integer updateId = update.getUpdateId(); + JsonNode realUpdate = updateMap.get(updateId); + JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(update)); assertEquals(realUpdate, handledUpdate); } } @@ -84,14 +99,10 @@ class TestDeserialization { "\"message\":{\"message_id\":106,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"Username\",\"language_code\":\"en\"},\"chat\":{\"id\":12345678,\"first_name\":\"FirstName\",\"username\":\"Username\",\"type\":\"private\"},\"date\":1604226480,\"document\":{\"file_name\":\"aaa.txt\",\"mime_type\":\"text/plain\",\"file_id\":\"FILEID\",\"file_unique_id\":\"AgADiQEAAjTe-VQ\",\"file_size\":2}}}]}"; ArrayList response = new GetUpdates().deserializeResponse(updateText); + assertEquals(6, response.size()); JsonNode realArray = mapper.readTree(updateText).get("result"); - - for (int i = 0; i < realArray.size(); i++) { - JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i))); - JsonNode realUpdate = realArray.get(i); - assertEquals(realUpdate, handledUpdate); - } + assertUpdates(response, realArray); } @Test @@ -119,14 +130,14 @@ class TestDeserialization { "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282110,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":83,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894322,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282114,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":95,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894323,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282118,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":99,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894324,\n" + - "\"message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800}}},{\"update_id\":259894325,\n" + - "\"message\":{\"message_id\":10,\"from\":{\"id\":12345678,\"is_bot\":true,\"first_name\":\"Group\",\"username\":\"GroupAnonymousBot\"},\"sender_chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"proximity_alert_triggered\":{\"traveler\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"watcher\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"distance\":0}}},{\"update_id\":259894326,\n" + - "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894327,\n" + + "\"message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800}}},{\"update_id\":259894325,\n" + + "\"message\":{\"message_id\":10,\"from\":{\"id\":12345678,\"is_bot\":true,\"first_name\":\"Group\",\"username\":\"GroupAnonymousBot\"},\"sender_chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"proximity_alert_triggered\":{\"traveler\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"watcher\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"distance\":0}}},{\"update_id\":259894326,\n" + + "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282124,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894327,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282126,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":104,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894328,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":100,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894329,\n" + - "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":101,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894330,\n" + + "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282128,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":101,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894330,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894331,\n" + - "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"Turing\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894332,\n" + + "\"edited_message\":{\"message_id\":9,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"username\":\"Username\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282124,\"edit_date\":1604282132,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894332,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282136,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":102,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894333,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282140,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":106,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894334,\n" + "\"edited_message\":{\"message_id\":8,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"supergroup\"},\"date\":1604282102,\"edit_date\":1604282144,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":99,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894335,\n" + @@ -147,14 +158,134 @@ class TestDeserialization { ArrayList response = new GetUpdates().deserializeResponse(updateText); + assertEquals(47, response.size()); JsonNode realArray = mapper.readTree(updateText).get("result"); + assertUpdates(response, realArray); + } - for (int i = 0; i < realArray.size(); i++) { - JsonNode handledUpdate = mapper.readTree(mapper.writeValueAsString(response.get(i))); - JsonNode realUpdate = realArray.get(i); - assertEquals(realUpdate, handledUpdate); - } + @Test + void TestListUpdatesVoiceChat() throws Exception { + String updateText = "{\n" + + " \"ok\": true,\n" + + " \"result\": [\n" + + " {\n" + + " \"update_id\": 259939677,\n" + + " \"message\": {\n" + + " \"message_id\": 1,\n" + + " \"from\": {\n" + + " \"id\": 1111111111111111,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"TestUser\",\n" + + " \"username\": \"TestUser\"\n" + + " },\n" + + " \"chat\": {\n" + + " \"id\": -552721116,\n" + + " \"title\": \"Random test\",\n" + + " \"type\": \"group\",\n" + + " \"all_members_are_administrators\": false\n" + + " },\n" + + " \"date\": 1615072605,\n" + + " \"group_chat_created\": true\n" + + " }\n" + + " },\n" + + " {\n" + + " \"update_id\": 259939678,\n" + + " \"message\": {\n" + + " \"message_id\": 2,\n" + + " \"from\": {\n" + + " \"id\": 1111111111111111,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"TestUser\",\n" + + " \"username\": \"TestUser\"\n" + + " },\n" + + " \"chat\": {\n" + + " \"id\": -552721116,\n" + + " \"title\": \"Random test\",\n" + + " \"type\": \"group\",\n" + + " \"all_members_are_administrators\": false\n" + + " },\n" + + " \"date\": 1615072631,\n" + + " \"migrate_to_chat_id\": -1001308316775\n" + + " }\n" + + " },\n" + + " {\n" + + " \"update_id\": 259939679,\n" + + " \"message\": {\n" + + " \"message_id\": 2,\n" + + " \"from\": {\n" + + " \"id\": 1111111111111111,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"TestUser\",\n" + + " \"username\": \"TestUser\"\n" + + " },\n" + + " \"chat\": {\n" + + " \"id\": -1001308316775,\n" + + " \"title\": \"Random test\",\n" + + " \"type\": \"supergroup\"\n" + + " },\n" + + " \"date\": 1615072662,\n" + + " \"voice_chat_started\": {}\n" + + " }\n" + + " },\n" + + " {\n" + + " \"update_id\": 259939680,\n" + + " \"message\": {\n" + + " \"message_id\": 3,\n" + + " \"from\": {\n" + + " \"id\": 1111111111111111,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"TestUser\",\n" + + " \"username\": \"TestUser\"\n" + + " },\n" + + " \"chat\": {\n" + + " \"id\": -1001308316775,\n" + + " \"title\": \"Random test\",\n" + + " \"type\": \"supergroup\"\n" + + " },\n" + + " \"date\": 1615072671,\n" + + " \"voice_chat_participants_invited\": {\n" + + " \"users\": [\n" + + " {\n" + + " \"id\": 222222222222222,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"Test\",\n" + + " \"last_name\": \"User\",\n" + + " \"username\": \"TestUser\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + " },\n" + + " {\n" + + " \"update_id\": 259939681,\n" + + " \"message\": {\n" + + " \"message_id\": 4,\n" + + " \"from\": {\n" + + " \"id\": 1111111111111111,\n" + + " \"is_bot\": false,\n" + + " \"first_name\": \"TestUser\",\n" + + " \"username\": \"TestUser\"\n" + + " },\n" + + " \"chat\": {\n" + + " \"id\": -1001308316775,\n" + + " \"title\": \"Random test\",\n" + + " \"type\": \"supergroup\"\n" + + " },\n" + + " \"date\": 1615072919,\n" + + " \"voice_chat_ended\": {\n" + + " \"duration\": 257\n" + + " }\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + ArrayList response = new GetUpdates().deserializeResponse(updateText); + assertEquals(5, response.size()); + + JsonNode realArray = mapper.readTree(updateText).get("result"); + assertUpdates(response, realArray); } @Test @@ -363,7 +494,7 @@ class TestDeserialization { assertNotNull(forwardFrom); assertEquals("ForwardLastname", forwardFrom.getLastName()); assertEquals("ForwardFirstname", forwardFrom.getFirstName()); - assertEquals(Integer.valueOf(222222), forwardFrom.getId()); + assertEquals(Long.valueOf(222222), forwardFrom.getId()); } private void assertPrivateChat(Chat chat) { @@ -413,7 +544,7 @@ class TestDeserialization { private void assertFromUser(User from) { assertNotNull(from); - assertEquals((Integer) 1111111, from.getId()); + assertEquals((Long) 1111111L, from.getId()); assertEquals("Test Lastname", from.getLastName()); assertEquals("Test Firstname", from.getFirstName()); assertEquals("Testusername", from.getUserName()); diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/apimethods/TestSetGameScore.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/apimethods/TestSetGameScore.java index 4c9a2835..29b5fc2f 100644 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/apimethods/TestSetGameScore.java +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/apimethods/TestSetGameScore.java @@ -30,7 +30,7 @@ class TestSetGameScore { setGameScore.setDisableEditMessage(true); setGameScore.setMessageId(54321); setGameScore.setScore(12); - setGameScore.setUserId(98765); + setGameScore.setUserId(98765L); } @Test diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index d9d79ea8..f66b1a69 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambots-spring-boot-starter @@ -70,7 +70,7 @@ UTF-8 UTF-8 - 5.0.1 + 5.1.0 2.4.3 1.6 diff --git a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotInitializer.java b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotInitializer.java index 92540ecf..c188b8b5 100644 --- a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotInitializer.java +++ b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotInitializer.java @@ -4,9 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.telegram.telegrambots.meta.TelegramBotsApi; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.generics.BotSession; import org.telegram.telegrambots.meta.generics.LongPollingBot; @@ -56,9 +54,6 @@ public class TelegramBotInitializer implements InitializingBean { private void handleAnnotatedMethod(Object bot, Method method, BotSession session) { try { - TelegramApiRequestException test = new TelegramApiRequestException("Error getting updates", new ApiResponse()); - log.error(test.getMessage(), test); - if (method.getParameterCount() > 1) { log.warn(format("Method %s of Type %s has too many parameters", method.getName(), method.getDeclaringClass().getCanonicalName())); diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 37143391..e49fbcc9 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.1 + 5.1.0 telegrambots @@ -92,7 +92,7 @@ org.telegram telegrambots-meta - 5.0.1 + 5.1.0 org.projectlombok diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java b/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java index 5034326e..e993fe45 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java @@ -155,7 +155,7 @@ public final class BotApiMethodHelperFactory { return GetChatMember .builder() .chatId("12345") - .userId(98765) + .userId(98765L) .build(); } @@ -178,7 +178,7 @@ public final class BotApiMethodHelperFactory { .builder() .chatId("12345") .messageId(67890) - .userId(98765) + .userId(98765L) .build(); } @@ -189,7 +189,7 @@ public final class BotApiMethodHelperFactory { public static BotApiMethod getGetUserProfilePhotos() { return GetUserProfilePhotos .builder() - .userId(98765) + .userId(98765L) .limit(10) .offset(3) .build(); @@ -203,7 +203,7 @@ public final class BotApiMethodHelperFactory { return KickChatMember .builder() .chatId("12345") - .userId(98765) + .userId(98765L) .build(); } @@ -344,7 +344,7 @@ public final class BotApiMethodHelperFactory { .inlineMessageId("12345") .disableEditMessage(true) .score(12) - .userId(98765) + .userId(98765L) .build(); } @@ -352,7 +352,7 @@ public final class BotApiMethodHelperFactory { return UnbanChatMember .builder() .chatId("12345") - .userId(98765) + .userId(98765L) .build(); } From cea06afcef3ce83e12ed884173d1262518268448 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Tue, 9 Mar 2021 11:10:09 +0000 Subject: [PATCH 11/11] Update wiki --- TelegramBots.wiki/Changelog.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 8421a048..14df1543 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -6,6 +6,8 @@ 5. Added CommandMessage to extensions 6. Abilities: Inject bot instance to reply update consumer support for multiple reply declarations. +**[[How to update to version 5.1.0|How-To-Update#5.1.0]]** + ### 5.0.1 ### 1. Fixing couple of bugs from 5.0.0 2. Bug fixing: #794