From b79911b45ff99d7fd7c366acb5714d417d82e3f0 Mon Sep 17 00:00:00 2001 From: Andy Costanza Date: Tue, 11 Aug 2020 12:17:33 +0200 Subject: [PATCH 01/45] fix(javadoc): add missing configuration to generate javadoc the error message before this fix was: Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.1.0:jar (default) on project telegrambots-meta: MavenReportException: Error while generating Javadoc: Unable to find javadoc command: The environment variable JAVA_HOME is not correctly set. --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 91026843..523f4dfd 100644 --- a/pom.xml +++ b/pom.xml @@ -190,6 +190,7 @@ none + ${java.home}/bin/javadoc From 3c5163990be84d425874dbe736fec0bc1830f806 Mon Sep 17 00:00:00 2001 From: Andy Costanza Date: Tue, 11 Aug 2020 12:29:35 +0200 Subject: [PATCH 02/45] feat(spring boot): Upgrade spring boot dependency to 2.3.2.RELEASE I'll fix UT too because in Spring Boot 2.3.X, ApplicationContextRunner disables bean overriding by default. To enable it, I set withAllowBeanDefinitionOverriding to true. https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#applicationcontextrunner-disables-bean-overriding-by-default for more informations --- telegrambots-spring-boot-starter/pom.xml | 41 +++-- .../TestTelegramBotStarterConfiguration.java | 166 +++++++++--------- ...stTelegramBotStarterRegistrationHooks.java | 91 +++++----- 3 files changed, 159 insertions(+), 139 deletions(-) diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index 7155c80e..46b5b2c2 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -70,8 +70,21 @@ UTF-8 UTF-8 + 4.9.1 + 2.3.2.RELEASE + 3.14.0 - 2.2.2.RELEASE + 1.6 + 1.6.8 + 3.1.0 + 3.1.1 + 3.1.0 + 3.1.0 + 0.8.4 + 3.0.0-M2 + 3.1.1 + 3.0.0-M3 + 3.8.1 @@ -79,7 +92,7 @@ org.telegram telegrambots - 4.9.1 + ${telegrambots.version} org.springframework.boot @@ -104,7 +117,7 @@ org.assertj assertj-core test - 3.14.0 + ${assertj-core.version} @@ -118,7 +131,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.6 + ${maven-gpg-plugin.version} sign-artifacts @@ -132,7 +145,7 @@ org.sonatype.plugins nexus-staging-maven-plugin - 1.6.8 + ${nexus-staging-maven-plugin.version} true ossrh @@ -142,7 +155,7 @@ maven-clean-plugin - 3.1.0 + ${maven-clean-plugin.version} clean-project @@ -155,7 +168,7 @@ maven-assembly-plugin - 3.1.1 + ${maven-assembly-plugin.version} jar-with-dependencies @@ -174,7 +187,7 @@ org.apache.maven.plugins maven-source-plugin - 3.1.0 + ${maven-source-plugin.version} @@ -186,7 +199,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.0 + ${maven-javadoc-plugin.version} @@ -201,7 +214,7 @@ org.jacoco jacoco-maven-plugin - 0.8.4 + ${jacoco-maven-plugin.version} @@ -220,7 +233,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0-M2 + ${maven-enforcer-plugin.version} enforce-versions @@ -238,7 +251,7 @@ org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + ${maven-dependency-plugin.version} copy @@ -249,7 +262,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + ${maven-surefire-plugin.version} @@ -257,7 +270,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + ${maven-compiler-plugin.version} ${java.version} ${java.version} diff --git a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java index 42a2d1cc..09cbec19 100644 --- a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java +++ b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java @@ -10,92 +10,96 @@ import org.telegram.telegrambots.meta.generics.LongPollingBot; import org.telegram.telegrambots.meta.generics.WebhookBot; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.*; class TestTelegramBotStarterConfiguration { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockTelegramBotsApi.class, TelegramBotStarterConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withAllowBeanDefinitionOverriding(true) + .withConfiguration(AutoConfigurations.of(MockTelegramBotsApi.class, + TelegramBotStarterConfiguration.class)); - @Test - void createMockTelegramBotsApiWithDefaultSettings() { - this.contextRunner.run((context) -> { - assertThat(context).hasSingleBean(TelegramBotsApi.class); - assertThat(context).hasSingleBean(TelegramBotInitializer.class); - assertThat(context).doesNotHaveBean(LongPollingBot.class); - assertThat(context).doesNotHaveBean(WebhookBot.class); - verifyNoMoreInteractions(context.getBean(TelegramBotsApi.class)); - }); - } - - @Test - void createOnlyLongPollingBot() { - this.contextRunner.withUserConfiguration(LongPollingBotConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(LongPollingBot.class); - assertThat(context).doesNotHaveBean(WebhookBot.class); - - TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); - - verify(telegramBotsApi, times(1)).registerBot( context.getBean(LongPollingBot.class) ); - verifyNoMoreInteractions(telegramBotsApi); - }); - } - - @Test - void createOnlyWebhookBot() { - this.contextRunner.withUserConfiguration(WebhookBotConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(WebhookBot.class); - assertThat(context).doesNotHaveBean(LongPollingBot.class); - - TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); - - verify(telegramBotsApi, times(1)).registerBot( context.getBean(WebhookBot.class) ); - verifyNoMoreInteractions(telegramBotsApi); - }); - } - - @Test - void createLongPoolingBotAndWebhookBot() { - this.contextRunner.withUserConfiguration(LongPollingBotConfig.class, WebhookBotConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(LongPollingBot.class); - assertThat(context).hasSingleBean(WebhookBot.class); + @Test + void createMockTelegramBotsApiWithDefaultSettings() { + this.contextRunner.run((context) -> { + assertThat(context).hasSingleBean(TelegramBotsApi.class); + assertThat(context).hasSingleBean(TelegramBotInitializer.class); + assertThat(context).doesNotHaveBean(LongPollingBot.class); + assertThat(context).doesNotHaveBean(WebhookBot.class); + verifyNoMoreInteractions(context.getBean(TelegramBotsApi.class)); + }); + } - TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); - - verify(telegramBotsApi, times(1)).registerBot( context.getBean(LongPollingBot.class) ); - verify(telegramBotsApi, times(1)).registerBot( context.getBean(WebhookBot.class) ); - //verifyNoMoreInteractions(telegramBotsApi); - }); - } + @Test + void createOnlyLongPollingBot() { + this.contextRunner.withUserConfiguration(LongPollingBotConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(LongPollingBot.class); + assertThat(context).doesNotHaveBean(WebhookBot.class); - @Configuration - static class MockTelegramBotsApi{ + TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); - @Bean - public TelegramBotsApi telegramBotsApi() { - return mock(TelegramBotsApi.class); - } - } - - @Configuration - static class LongPollingBotConfig{ - @Bean - public LongPollingBot longPollingBot() { - return mock(LongPollingBot.class); - } - } - - @Configuration - static class WebhookBotConfig{ - @Bean - public WebhookBot webhookBot() { - return mock(WebhookBot.class); - } - } + verify(telegramBotsApi, + times(1)).registerBot(context.getBean(LongPollingBot.class)); + verifyNoMoreInteractions(telegramBotsApi); + }); + } + + @Test + void createOnlyWebhookBot() { + this.contextRunner.withUserConfiguration(WebhookBotConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(WebhookBot.class); + assertThat(context).doesNotHaveBean(LongPollingBot.class); + + TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); + + verify(telegramBotsApi, + times(1)).registerBot(context.getBean(WebhookBot.class)); + verifyNoMoreInteractions(telegramBotsApi); + }); + } + + @Test + void createLongPoolingBotAndWebhookBot() { + this.contextRunner.withUserConfiguration(LongPollingBotConfig.class, + WebhookBotConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(LongPollingBot.class); + assertThat(context).hasSingleBean(WebhookBot.class); + + TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); + + verify(telegramBotsApi, + times(1)).registerBot(context.getBean(LongPollingBot.class)); + verify(telegramBotsApi, + times(1)).registerBot(context.getBean(WebhookBot.class)); + //verifyNoMoreInteractions(telegramBotsApi); + }); + } + + @Configuration + static class MockTelegramBotsApi { + + @Bean + public TelegramBotsApi telegramBotsApi() { + return mock(TelegramBotsApi.class); + } + } + + @Configuration + static class LongPollingBotConfig { + @Bean + public LongPollingBot longPollingBot() { + return mock(LongPollingBot.class); + } + } + + @Configuration + static class WebhookBotConfig { + @Bean + public WebhookBot webhookBot() { + return mock(WebhookBot.class); + } + } } diff --git a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java index 2f108d81..1764c4ad 100644 --- a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java +++ b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java @@ -14,27 +14,22 @@ import org.telegram.telegrambots.meta.generics.LongPollingBot; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; class TestTelegramBotStarterRegistrationHooks { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockTelegramBotsApi.class, TelegramBotStarterConfiguration.class)); - - // Terrible workaround for mockito loosing annotations on methods - private static boolean hookCalled = false; - private static boolean hookCalledWithSession = false; - private static final DefaultBotSession someBotSession = new DefaultBotSession(); - - private static final TelegramBotsApi mockTelegramBotsApi = mock(TelegramBotsApi.class); + private static final DefaultBotSession someBotSession = new DefaultBotSession(); + private static final TelegramBotsApi mockTelegramBotsApi = mock(TelegramBotsApi.class); + // Terrible workaround for mockito loosing annotations on methods + private static boolean hookCalled = false; + private static boolean hookCalledWithSession = false; + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withAllowBeanDefinitionOverriding(true) + .withConfiguration(AutoConfigurations.of(MockTelegramBotsApi.class, + TelegramBotStarterConfiguration.class)); @Test - void longPollingBotWithAnnotatedMethodshouldBeCalled() throws TelegramApiRequestException { + void longPollingBotWithAnnotatedMethodshouldBeCalled() throws TelegramApiRequestException { when(mockTelegramBotsApi.registerBot(any(LongPollingBot.class))).thenReturn(someBotSession); @@ -45,48 +40,56 @@ class TestTelegramBotStarterRegistrationHooks { final LongPollingBot bot = context.getBean(LongPollingBot.class); final TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); - assertThat(hookCalled).isTrue(); - assertThat(hookCalledWithSession).isTrue(); - verify(telegramBotsApi, times(1)).registerBot(bot); - verifyNoMoreInteractions(telegramBotsApi); + assertThat(hookCalled).isTrue(); + assertThat(hookCalledWithSession).isTrue(); + verify(telegramBotsApi, + times(1)).registerBot(bot); + verifyNoMoreInteractions(telegramBotsApi); }); } - @Configuration - static class MockTelegramBotsApi{ + @Configuration + static class MockTelegramBotsApi { - @Bean - public TelegramBotsApi telegramBotsApi() { - return mockTelegramBotsApi; - } - } - - @Configuration - static class LongPollingBotConfig{ - @Bean - public LongPollingBot longPollingBot() { return new AnnotatedLongPollingBot(); } - } + @Bean + public TelegramBotsApi telegramBotsApi() { + return mockTelegramBotsApi; + } + } - static class AnnotatedLongPollingBot extends TelegramLongPollingBot { + @Configuration + static class LongPollingBotConfig { + @Bean + public LongPollingBot longPollingBot() { + return new AnnotatedLongPollingBot(); + } + } - @Override - public void onUpdateReceived(final Update update) {} + static class AnnotatedLongPollingBot extends TelegramLongPollingBot { - @Override - public String getBotUsername() { return null; } + @Override + public void onUpdateReceived(final Update update) { + } - @Override - public String getBotToken() { return null; } + @Override + public String getBotUsername() { + return null; + } - @AfterBotRegistration - public void afterBotHook() { + @Override + public String getBotToken() { + return null; + } + + @AfterBotRegistration + public void afterBotHook() { hookCalled = true; } @AfterBotRegistration - public void afterBotHookWithSession(BotSession session) { + public void afterBotHookWithSession(BotSession session) { hookCalledWithSession = session.equals(someBotSession); } - } + } } From f3626b7bf155642b036dc0858b1b1896abaabcde Mon Sep 17 00:00:00 2001 From: Andy Costanza Date: Tue, 25 Aug 2020 17:25:36 +0200 Subject: [PATCH 03/45] feat(spring boot): Upgrade spring boot dependency to 2.3.3.RELEASE --- telegrambots-spring-boot-starter/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index 46b5b2c2..90b989ab 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -71,7 +71,7 @@ UTF-8 4.9.1 - 2.3.2.RELEASE + 2.3.3.RELEASE 3.14.0 1.6 From 6fcd4d85c10c75c926b02dceb27243554c96c1a6 Mon Sep 17 00:00:00 2001 From: Mouamle Date: Sat, 5 Sep 2020 03:53:42 +0300 Subject: [PATCH 04/45] Made webhook bots print exceptions stacktrace to stderr instead of silently swallowing them. --- .../DefaultExceptionMapper.java | 20 +++++++++++++++++++ .../updatesreceivers/DefaultWebhook.java | 1 + 2 files changed, 21 insertions(+) create mode 100644 telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java new file mode 100644 index 00000000..1732fa53 --- /dev/null +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java @@ -0,0 +1,20 @@ +package org.telegram.telegrambots.updatesreceivers; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * Prints exceptions in webhook bots to stderr + * + * @author Mouamle + * @version 1.0 + */ +public class DefaultExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(Throwable exception) { + exception.printStackTrace(); + return Response.serverError().build(); + } + +} diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java index 4a8c4d31..c27806f4 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java @@ -52,6 +52,7 @@ public class DefaultWebhook implements Webhook { ResourceConfig rc = new ResourceConfig(); rc.register(restApi); rc.register(JacksonFeature.class); + rc.register(DefaultExceptionMapper.class); final HttpServer grizzlyServer; if (keystoreServerFile != null && keystoreServerPwd != null) { From 13f6b1f336a402d50f443127dbcb3113cc5afb28 Mon Sep 17 00:00:00 2001 From: Mouamle Date: Tue, 8 Sep 2020 01:18:18 +0300 Subject: [PATCH 05/45] used slf4j for logging instead of `exception.printStackTrace()` --- .../updatesreceivers/DefaultExceptionMapper.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java index 1732fa53..7fa69be3 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultExceptionMapper.java @@ -1,5 +1,8 @@ package org.telegram.telegrambots.updatesreceivers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; @@ -10,11 +13,11 @@ import javax.ws.rs.ext.ExceptionMapper; * @version 1.0 */ public class DefaultExceptionMapper implements ExceptionMapper { + private static final Logger log = LoggerFactory.getLogger(DefaultExceptionMapper.class); @Override public Response toResponse(Throwable exception) { - exception.printStackTrace(); + log.error("Exception caught: ", exception); return Response.serverError().build(); } - } From 2009ef411dfbc9891ddbe2483e8f5b5e49e2ef3a Mon Sep 17 00:00:00 2001 From: Chase22 Date: Mon, 21 Sep 2020 19:31:50 +0200 Subject: [PATCH 06/45] Add timeout and update limit for long-polling updates to DefaultBotOptions Just a little commit to make the long-polling timeout and long-polling limit configurable via the BotOptions. Mainly for Testing --- .../telegrambots/bots/DefaultBotOptions.java | 20 +++++++++++++++++++ .../updatesreceivers/DefaultBotSession.java | 4 ++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java index 7e2e59af..2f59d7d2 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultBotOptions.java @@ -26,6 +26,8 @@ public class DefaultBotOptions implements BotOptions { private ProxyType proxyType; private String proxyHost; private int proxyPort; + private int getUpdatesTimeout; + private int getUpdatesLimit; public enum ProxyType { NO_PROXY, @@ -39,6 +41,8 @@ public class DefaultBotOptions implements BotOptions { baseUrl = ApiConstants.BASE_URL; httpContext = HttpClientContext.create(); proxyType = ProxyType.NO_PROXY; + getUpdatesLimit = ApiConstants.GETUPDATES_TIMEOUT; + getUpdatesLimit = 100; } @Override @@ -129,4 +133,20 @@ public class DefaultBotOptions implements BotOptions { public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } + + public int getGetUpdatesTimeout() { + return getUpdatesTimeout; + } + + public void setGetUpdatesTimeout(int getUpdatesTimeout) { + this.getUpdatesTimeout = getUpdatesTimeout; + } + + public int getGetUpdatesLimit() { + return getUpdatesLimit; + } + + public void setGetUpdatesLimit(int getUpdatesLimit) { + this.getUpdatesLimit = getUpdatesLimit; + } } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index da98f1b8..804181c0 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -236,8 +236,8 @@ public class DefaultBotSession implements BotSession { private List getUpdatesFromServer() throws IOException { GetUpdates request = new GetUpdates() - .setLimit(100) - .setTimeout(ApiConstants.GETUPDATES_TIMEOUT) + .setLimit(options.getGetUpdatesLimit()) + .setTimeout(options.getGetUpdatesTimeout()) .setOffset(lastReceivedUpdate + 1); if (options.getAllowedUpdates() != null) { From a106e3190c5d308ce119923d162f09da2de9ecda Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Fri, 2 Oct 2020 21:57:57 +0200 Subject: [PATCH 07/45] Be able to access AbilityBot via MessageContext --- .../abilitybots/api/bot/BaseAbilityBot.java | 23 ++++++++++++++++++- .../api/objects/MessageContext.java | 16 ++++++++++--- .../abilitybots/api/bot/AbilityBotTest.java | 6 ++--- .../abilitybots/api/bot/TestUtils.java | 3 ++- 4 files changed, 40 insertions(+), 8 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 317f222f..12073632 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 @@ -128,6 +128,27 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability initStats(); } + /** + * @return the database of this bot + */ + public DBContext db() { + return db; + } + + /** + * @return the message sender for this bot + */ + public MessageSender sender() { + return sender; + } + + /** + * @return the silent sender for this bot + */ + public SilentSender silent() { + return silent; + } + /** * @return the map of */ @@ -437,7 +458,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability Update update = trio.a(); User user = AbilityUtils.getUser(update); - return Pair.of(newContext(update, user, getChatId(update), trio.c()), trio.b()); + return Pair.of(newContext(update, user, getChatId(update), this, trio.c()), trio.b()); } boolean checkBlacklist(Update update) { diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/MessageContext.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/MessageContext.java index c9fc2398..fc650f85 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/MessageContext.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/objects/MessageContext.java @@ -2,6 +2,7 @@ package org.telegram.abilitybots.api.objects; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; +import org.telegram.abilitybots.api.bot.BaseAbilityBot; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; @@ -19,16 +20,18 @@ public class MessageContext { private final Long chatId; private final String[] arguments; private final Update update; + private final BaseAbilityBot bot; - private MessageContext(Update update, User user, Long chatId, String[] arguments) { + private MessageContext(Update update, User user, Long chatId, BaseAbilityBot bot, String[] arguments) { this.user = user; this.chatId = chatId; this.update = update; + this.bot = bot; this.arguments = arguments; } - public static MessageContext newContext(Update update, User user, Long chatId, String... arguments) { - return new MessageContext(update, user, chatId, arguments); + public static MessageContext newContext(Update update, User user, Long chatId, BaseAbilityBot bot, String... arguments) { + return new MessageContext(update, user, chatId, bot, arguments); } /** @@ -45,6 +48,13 @@ public class MessageContext { return chatId; } + /** + * @return the bot in which this message is executed + */ + public BaseAbilityBot bot() { + return bot; + } + /** * If there's no message in the update, then this will an empty array. * 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 f6823690..54ff772e 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 @@ -503,7 +503,7 @@ public class AbilityBotTest { mockUser(update, message, USER); Pair actualPair = bot.getContext(trio); - Pair expectedPair = Pair.of(newContext(update, USER, GROUP_ID, TEXT), ability); + Pair expectedPair = Pair.of(newContext(update, USER, GROUP_ID, bot, TEXT), ability); assertEquals(expectedPair, actualPair, "Unexpected result when fetching for context"); } @@ -619,7 +619,7 @@ public class AbilityBotTest { when(update.hasMessage()).thenReturn(true); when(update.getMessage()).thenReturn(message); when(message.hasText()).thenReturn(true); - MessageContext creatorCtx = newContext(update, CREATOR, GROUP_ID); + MessageContext creatorCtx = newContext(update, CREATOR, GROUP_ID, bot); defaultAbs.commands().action().accept(creatorCtx); @@ -636,7 +636,7 @@ public class AbilityBotTest { when(update.getMessage()).thenReturn(message); when(message.hasText()).thenReturn(true); - MessageContext userCtx = newContext(update, USER, GROUP_ID); + MessageContext userCtx = newContext(update, USER, GROUP_ID, bot); defaultAbs.commands().action().accept(userCtx); 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 19c531da..bf1c3479 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 @@ -43,6 +43,7 @@ public final class TestUtils { static MessageContext mockContext(User user, long groupId, String... args) { Update update = mock(Update.class); Message message = mock(Message.class); + BaseAbilityBot bot = mock(BaseAbilityBot.class); when(update.hasMessage()).thenReturn(true); when(update.getMessage()).thenReturn(message); @@ -50,7 +51,7 @@ public final class TestUtils { when(message.getFrom()).thenReturn(user); when(message.hasText()).thenReturn(true); - return newContext(update, user, groupId, args); + return newContext(update, user, groupId, bot, args); } @NotNull From 74e305c2a75965b0882d4508210e8617592e7ae2 Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Mon, 5 Oct 2020 16:59:39 +0200 Subject: [PATCH 08/45] Load abilities when bot gets registered --- .../abilitybots/api/bot/AbilityBot.java | 69 ++++++++------- .../api/bot/AbilityWebhookBot.java | 83 ++++++++++--------- .../abilitybots/api/bot/BaseAbilityBot.java | 2 + .../api/bot/AbilityBotI18nTest.java | 1 + .../abilitybots/api/bot/AbilityBotTest.java | 1 + .../api/bot/ContinuousTextTest.java | 1 + .../abilitybots/api/bot/ExtensionTest.java | 1 + .../abilitybots/api/bot/ReplyFlowTest.java | 1 + .../api/toggle/BareboneToggleTest.java | 1 + .../api/toggle/CustomToggleTest.java | 5 +- .../api/toggle/DefaultToggleTest.java | 82 +++++++++--------- .../telegrambots/meta/TelegramBotsApi.java | 2 + .../meta/generics/LongPollingBot.java | 12 +-- .../meta/generics/TelegramBot.java | 24 ++++++ .../meta/generics/WebhookBot.java | 14 +--- 15 files changed, 160 insertions(+), 139 deletions(-) create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/TelegramBot.java diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java index cdad9f55..f1b17012 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java @@ -18,45 +18,50 @@ import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance; * @author Abbas Abou Daya */ public abstract class AbilityBot extends BaseAbilityBot implements LongPollingBot { - protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { - super(botToken, botUsername, db, toggle, botOptions); - } + protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { + super(botToken, botUsername, db, toggle, botOptions); + } - protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle, DefaultBotOptions options) { - this(botToken, botUsername, onlineInstance(botUsername), toggle, options); - } + protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle, DefaultBotOptions options) { + this(botToken, botUsername, onlineInstance(botUsername), toggle, options); + } - protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle) { - this(botToken, botUsername, db, toggle, new DefaultBotOptions()); - } + protected AbilityBot(String botToken, String botUsername, DBContext db, AbilityToggle toggle) { + this(botToken, botUsername, db, toggle, new DefaultBotOptions()); + } - protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions options) { - this(botToken, botUsername, db, new DefaultToggle(), options); - } + protected AbilityBot(String botToken, String botUsername, DBContext db, DefaultBotOptions options) { + this(botToken, botUsername, db, new DefaultToggle(), options); + } - protected AbilityBot(String botToken, String botUsername, DefaultBotOptions botOptions) { - this(botToken, botUsername, onlineInstance(botUsername), botOptions); - } + protected AbilityBot(String botToken, String botUsername, DefaultBotOptions botOptions) { + this(botToken, botUsername, onlineInstance(botUsername), botOptions); + } - protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle) { - this(botToken, botUsername, onlineInstance(botUsername), toggle); - } + protected AbilityBot(String botToken, String botUsername, AbilityToggle toggle) { + this(botToken, botUsername, onlineInstance(botUsername), toggle); + } - protected AbilityBot(String botToken, String botUsername, DBContext db) { - this(botToken, botUsername, db, new DefaultToggle()); - } + protected AbilityBot(String botToken, String botUsername, DBContext db) { + this(botToken, botUsername, db, new DefaultToggle()); + } - protected AbilityBot(String botToken, String botUsername) { - this(botToken, botUsername, onlineInstance(botUsername)); - } + protected AbilityBot(String botToken, String botUsername) { + this(botToken, botUsername, onlineInstance(botUsername)); + } - @Override - public void onUpdateReceived(Update update) { - super.onUpdateReceived(update); - } + @Override + public void onRegister() { + super.onRegister(); + } - @Override - public void clearWebhook() throws TelegramApiRequestException { - WebhookUtils.clearWebhook(this); - } + @Override + public void onUpdateReceived(Update update) { + super.onUpdateReceived(update); + } + + @Override + public void clearWebhook() throws TelegramApiRequestException { + WebhookUtils.clearWebhook(this); + } } \ No newline at end of file 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 2c9b3db6..a4bbc2c7 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 @@ -21,54 +21,59 @@ import static org.telegram.abilitybots.api.db.MapDBContext.onlineInstance; @SuppressWarnings("WeakerAccess") public abstract class AbilityWebhookBot extends BaseAbilityBot implements WebhookBot { - private final String botPath; + private final String botPath; - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { - super(botToken, botUsername, db, toggle, botOptions); - this.botPath = botPath; - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle, DefaultBotOptions botOptions) { + super(botToken, botUsername, db, toggle, botOptions); + this.botPath = botPath; + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle, DefaultBotOptions options) { - this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle, options); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle, DefaultBotOptions options) { + this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle, options); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle) { - this(botToken, botUsername, botPath, db, toggle, new DefaultBotOptions()); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, AbilityToggle toggle) { + this(botToken, botUsername, botPath, db, toggle, new DefaultBotOptions()); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, DefaultBotOptions options) { - this(botToken, botUsername, botPath, db, new DefaultToggle(), options); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db, DefaultBotOptions options) { + this(botToken, botUsername, botPath, db, new DefaultToggle(), options); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DefaultBotOptions botOptions) { - this(botToken, botUsername, botPath, onlineInstance(botUsername), botOptions); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DefaultBotOptions botOptions) { + this(botToken, botUsername, botPath, onlineInstance(botUsername), botOptions); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle) { - this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, AbilityToggle toggle) { + this(botToken, botUsername, botPath, onlineInstance(botUsername), toggle); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db) { - this(botToken, botUsername, botPath, db, new DefaultToggle()); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath, DBContext db) { + this(botToken, botUsername, botPath, db, new DefaultToggle()); + } - protected AbilityWebhookBot(String botToken, String botUsername, String botPath) { - this(botToken, botUsername, botPath, onlineInstance(botUsername)); - } + protected AbilityWebhookBot(String botToken, String botUsername, String botPath) { + this(botToken, botUsername, botPath, onlineInstance(botUsername)); + } - @Override - public BotApiMethod onWebhookUpdateReceived(Update update) { - super.onUpdateReceived(update); - return null; - } + @Override + public void onRegister() { + super.onRegister(); + } - @Override - public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { - WebhookUtils.setWebhook(this, url, publicCertificatePath); - } + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + super.onUpdateReceived(update); + return null; + } - @Override - public String getBotPath() { - return botPath; - } + @Override + public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { + WebhookUtils.setWebhook(this, url, publicCertificatePath); + } + + @Override + public String getBotPath() { + return botPath; + } } \ No newline at end of file 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 317f222f..03af7599 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 @@ -123,7 +123,9 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability this.toggle = toggle; this.sender = new DefaultSender(this); silent = new SilentSender(sender); + } + public void onRegister() { registerAbilities(); initStats(); } 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 6915d30d..5b320898 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 @@ -33,6 +33,7 @@ class AbilityBotI18nTest { void setUp() { db = offlineInstance("db"); bot = new NoPublicCommandsBot(EMPTY, EMPTY, db); + bot.onRegister(); defaultAbs = new DefaultAbilities(bot); sender = mock(MessageSender.class); 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 f6823690..f16334d2 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 @@ -71,6 +71,7 @@ public class AbilityBotTest { void setUp() { db = offlineInstance("db"); bot = new DefaultBot(EMPTY, EMPTY, db); + bot.onRegister(); defaultAbs = new DefaultAbilities(bot); sender = mock(MessageSender.class); 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 6e204625..a2e5b18f 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 @@ -33,6 +33,7 @@ public class ContinuousTextTest { void setUp() { db = offlineInstance("db"); bot = new ContinuousTextBot(EMPTY, EMPTY, db); + bot.onRegister(); silent = mock(SilentSender.class); bot.silent = silent; } 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 8be53c13..06b85e6d 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 @@ -19,6 +19,7 @@ class ExtensionTest { @BeforeEach void setUp() { bot = new ExtensionUsingBot(); + bot.onRegister(); } @AfterEach 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 b117ab7a..4ca37b06 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 @@ -39,6 +39,7 @@ public class ReplyFlowTest { void setUp() { db = offlineInstance("db"); bot = new ReplyFlowBot(EMPTY, EMPTY, db); + bot.onRegister(); sender = mock(MessageSender.class); silent = mock(SilentSender.class); diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/BareboneToggleTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/BareboneToggleTest.java index 9adca9d4..1d67e640 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/BareboneToggleTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/BareboneToggleTest.java @@ -26,6 +26,7 @@ public class BareboneToggleTest { db = offlineInstance("db"); toggle = new BareboneToggle(); bareboneBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + bareboneBot.onRegister(); defaultAbs = new DefaultAbilities(bareboneBot); } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/CustomToggleTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/CustomToggleTest.java index aeac3c8a..098533ea 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/CustomToggleTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/CustomToggleTest.java @@ -1,7 +1,6 @@ package org.telegram.abilitybots.api.toggle; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.telegram.abilitybots.api.bot.DefaultAbilities; @@ -18,12 +17,10 @@ class CustomToggleTest { private DBContext db; private AbilityToggle toggle; private DefaultBot customBot; - private DefaultAbilities defaultAbs; @BeforeEach void setUp() { db = offlineInstance("db"); - defaultAbs = new DefaultAbilities(customBot); } @AfterEach @@ -36,6 +33,7 @@ class CustomToggleTest { public void canTurnOffAbilities() { toggle = new CustomToggle().turnOff(DefaultAbilities.CLAIM); customBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + customBot.onRegister(); assertFalse(customBot.abilities().containsKey(DefaultAbilities.CLAIM)); } @@ -44,6 +42,7 @@ class CustomToggleTest { String targetName = DefaultAbilities.CLAIM + "1toggle"; toggle = new CustomToggle().toggle(DefaultAbilities.CLAIM, targetName); customBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + customBot.onRegister(); assertTrue(customBot.abilities().containsKey(targetName)); } diff --git a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/DefaultToggleTest.java b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/DefaultToggleTest.java index 8095d6fa..90d4ef90 100644 --- a/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/DefaultToggleTest.java +++ b/telegrambots-abilities/src/test/java/org/telegram/abilitybots/api/toggle/DefaultToggleTest.java @@ -3,7 +3,6 @@ package org.telegram.abilitybots.api.toggle; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.telegram.abilitybots.api.bot.DefaultAbilities; import org.telegram.abilitybots.api.bot.DefaultBot; import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.objects.Ability; @@ -18,52 +17,53 @@ import static org.telegram.abilitybots.api.bot.DefaultAbilities.*; import static org.telegram.abilitybots.api.db.MapDBContext.offlineInstance; class DefaultToggleTest { - private DBContext db; - private AbilityToggle toggle; - private DefaultBot defaultBot; - private DefaultAbilities defaultAbs; + private DBContext db; + private AbilityToggle toggle; + private DefaultBot defaultBot; - @BeforeEach - void setUp() { - db = offlineInstance("db"); - defaultAbs = new DefaultAbilities(defaultBot); - } + @BeforeEach + void setUp() { + db = offlineInstance("db"); + } - @AfterEach - void tearDown() throws IOException { - db.clear(); - db.close(); - } + @AfterEach + void tearDown() throws IOException { + db.clear(); + db.close(); + } - @Test - public void claimsEveryAbilityIsOn() { - Ability random = DefaultBot.getDefaultBuilder() - .name("randomsomethingrandom").build(); - toggle = new DefaultToggle(); - defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + @Test + public void claimsEveryAbilityIsOn() { + Ability random = DefaultBot.getDefaultBuilder() + .name("randomsomethingrandom").build(); + toggle = new DefaultToggle(); + defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + defaultBot.onRegister(); - assertFalse(toggle.isOff(random)); - } + assertFalse(toggle.isOff(random)); + } - @Test - public void passedSameAbilityRefOnProcess() { - Ability random = DefaultBot.getDefaultBuilder() - .name("randomsomethingrandom").build(); - toggle = new DefaultToggle(); - defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + @Test + public void passedSameAbilityRefOnProcess() { + Ability random = DefaultBot.getDefaultBuilder() + .name("randomsomethingrandom").build(); + toggle = new DefaultToggle(); + defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + defaultBot.onRegister(); - assertSame(random, toggle.processAbility(random), "Toggle returned a different ability"); - } + assertSame(random, toggle.processAbility(random), "Toggle returned a different ability"); + } - @Test - public void allAbilitiesAreRegistered() { - toggle = new DefaultToggle(); - defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); - Set defaultNames = newHashSet( - CLAIM, BAN, UNBAN, - PROMOTE, DEMOTE, RECOVER, - BACKUP, REPORT, COMMANDS); + @Test + public void allAbilitiesAreRegistered() { + toggle = new DefaultToggle(); + defaultBot = new DefaultBot(EMPTY, EMPTY, db, toggle); + defaultBot.onRegister(); + Set defaultNames = newHashSet( + CLAIM, BAN, UNBAN, + PROMOTE, DEMOTE, RECOVER, + BACKUP, REPORT, COMMANDS); - assertTrue(defaultBot.abilities().keySet().containsAll(defaultNames), "Toggle returned a different ability"); - } + assertTrue(defaultBot.abilities().keySet().containsAll(defaultNames), "Toggle returned a different ability"); + } } \ No newline at end of file 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 ae8b5185..04f5b694 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 @@ -117,6 +117,7 @@ public class TelegramBotsApi { * @param bot the bot to register */ public BotSession registerBot(LongPollingBot bot) throws TelegramApiRequestException { + bot.onRegister(); bot.clearWebhook(); BotSession session = ApiContext.getInstance(BotSession.class); session.setToken(bot.getBotToken()); @@ -132,6 +133,7 @@ public class TelegramBotsApi { */ public void registerBot(WebhookBot bot) throws TelegramApiRequestException { if (useWebhook) { + bot.onRegister(); webhook.registerWebhook(bot); bot.setWebhook(externalUrl + bot.getBotPath(), pathToCertificate); } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/LongPollingBot.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/LongPollingBot.java index 7d76c100..ae965910 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/LongPollingBot.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/LongPollingBot.java @@ -11,7 +11,7 @@ import java.util.List; * @brief Callback to handle updates. * @date 20 of June of 2015 */ -public interface LongPollingBot { +public interface LongPollingBot extends TelegramBot { /** * This method is called when receiving updates via GetUpdates method * @param update Update received @@ -27,16 +27,6 @@ public interface LongPollingBot { updates.forEach(this::onUpdateReceived); } - /** - * Return bot username of this bot - */ - String getBotUsername(); - - /** - * Return bot token to access Telegram API - */ - String getBotToken(); - /** * Gets options for current bot * @return BotOptions object with options information diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/TelegramBot.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/TelegramBot.java new file mode 100644 index 00000000..ab8fc5f3 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/TelegramBot.java @@ -0,0 +1,24 @@ +package org.telegram.telegrambots.meta.generics; + +/** + * Main interface for telegram bots. + */ +public interface TelegramBot { + + /** + * Return username of this bot + */ + String getBotUsername(); + + /** + * Return bot token to access Telegram API + */ + String getBotToken(); + + /** + * Is called when bot gets registered + */ + default void onRegister() { + } + +} 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 a66cde5f..696a7268 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 @@ -10,25 +10,13 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; * @brief Callback to handle updates. * @date 20 of June of 2015 */ -public interface WebhookBot { +public interface WebhookBot extends TelegramBot { /** * This method is called when receiving updates via webhook * @param update Update received */ BotApiMethod onWebhookUpdateReceived(Update update); - /** - * Gets bot username of this bot - * @return Bot username - */ - String getBotUsername(); - - /** - * Gets bot token to access Telegram API - * @return Bot token - */ - String getBotToken(); - /** * Execute setWebhook method to set up the url of the webhook * @param url Url for the webhook From b715f2a154d904810e9a2cf3e184b8161241d88d Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Mon, 5 Oct 2020 18:05:25 +0200 Subject: [PATCH 09/45] Be able to add AbilityExtensions in Bot constructor --- .../org/telegram/abilitybots/api/bot/BaseAbilityBot.java | 5 +++-- 1 file changed, 3 insertions(+), 2 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 317f222f..01b18da4 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 @@ -106,6 +106,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability private final String botUsername; // Ability registry + protected final List extensions = new ArrayList<>(); private Map abilities; private Map stats; @@ -280,10 +281,10 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability private void registerAbilities() { try { // Collect all classes that implement AbilityExtension declared in the bot - List extensions = stream(getClass().getMethods()) + extensions.addAll(stream(getClass().getMethods()) .filter(checkReturnType(AbilityExtension.class)) .map(returnExtension(this)) - .collect(Collectors.toList()); + .collect(Collectors.toList())); // Add the bot itself as it is an AbilityExtension extensions.add(this); From 1855a27d132a71a70304fcf0ad2513a54788383d Mon Sep 17 00:00:00 2001 From: Daniil547 <72149318+Daniil547@users.noreply.github.com> Date: Tue, 6 Oct 2020 15:46:18 +0000 Subject: [PATCH 10/45] Update Ability.java --- .../java/org/telegram/abilitybots/api/objects/Ability.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 0b6691bb..fbb319bc 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 @@ -50,9 +50,8 @@ public final class Ability { @SafeVarargs private Ability(String name, String info, Locality locality, Privacy privacy, int argNum, boolean statsEnabled, Consumer action, Consumer postAction, List replies, Predicate... flags) { - checkArgument(!isEmpty(name), "Method name cannot be empty"); - checkArgument(!containsWhitespace(name), "Method name cannot contain spaces"); - checkArgument(isAlphanumeric(name), "Method name can only be alpha-numeric", name); + checkArgument(isValidCommandName(name), "Method name can only contain alpha-numeric characters and underscores," + + " cannot be longer than 31 characters, empty or null", name); this.name = name; this.info = info; From fe79de9bb7cc3dc8933f05a1182d9b467550c825 Mon Sep 17 00:00:00 2001 From: Daniil547 <72149318+Daniil547@users.noreply.github.com> Date: Tue, 6 Oct 2020 15:49:49 +0000 Subject: [PATCH 11/45] Update AbilityUtils.java --- .../abilitybots/api/util/AbilityUtils.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) 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 6b8ca9ce..e639682e 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 @@ -269,4 +269,29 @@ public final class AbilityUtils { public static String escape(String username) { return username.replace("_", "\\_"); } -} \ No newline at end of file + + /** + * Checks if the passed string is a valid bot command according to the requirements of Telegram Bot API: + * "A command must always start with the '/' symbol and may not be longer than 32 characters. + * Commands can use latin letters, numbers and underscores." + * (https://core.telegram.org/bots#commands) + * + * @param command String representation of a command to be checked for validity + * @return whether the command is valid + */ + public static boolean isValidCommand(String command){ + if (command == null || command.length() > 32) return false; + return command.matches("/[A-Za-z_0-9]+"); + } + + /** + * Checks if the passed String is a valid command name. Command name is text of a command without leading '/' + * + * @param commandName the command's name to be checked for validity + * @return whether the command's name is valid + */ + public static boolean isValidCommandName(String commandName){ + if (commandName == null || commandName.length() > 31) return false; + return commandName.matches("[A-Za-z_0-9]+"); + } +} From 5d8d10b02d212a5c54224070ab69a54c72e50e0a Mon Sep 17 00:00:00 2001 From: Daniil547 <72149318+Daniil547@users.noreply.github.com> Date: Tue, 6 Oct 2020 16:08:44 +0000 Subject: [PATCH 12/45] Update AbilityUtils.java --- .../java/org/telegram/abilitybots/api/util/AbilityUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e639682e..b38f5ab0 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 @@ -287,8 +287,8 @@ public final class AbilityUtils { /** * Checks if the passed String is a valid command name. Command name is text of a command without leading '/' * - * @param commandName the command's name to be checked for validity - * @return whether the command's name is valid + * @param commandName the command name to be checked for validity + * @return whether the command name is valid */ public static boolean isValidCommandName(String commandName){ if (commandName == null || commandName.length() > 31) return false; From 5b465e79f3e65224c5777c4d1833df8785d19897 Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Thu, 8 Oct 2020 15:07:14 +0200 Subject: [PATCH 13/45] Removed unnecessary onRegister() overrides --- .../java/org/telegram/abilitybots/api/bot/AbilityBot.java | 5 ----- .../org/telegram/abilitybots/api/bot/AbilityWebhookBot.java | 5 ----- 2 files changed, 10 deletions(-) diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java index f1b17012..321cafd9 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/bot/AbilityBot.java @@ -50,11 +50,6 @@ public abstract class AbilityBot extends BaseAbilityBot implements LongPollingBo this(botToken, botUsername, onlineInstance(botUsername)); } - @Override - public void onRegister() { - super.onRegister(); - } - @Override public void onUpdateReceived(Update update) { super.onUpdateReceived(update); 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 a4bbc2c7..a50aa81d 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 @@ -56,11 +56,6 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo this(botToken, botUsername, botPath, onlineInstance(botUsername)); } - @Override - public void onRegister() { - super.onRegister(); - } - @Override public BotApiMethod onWebhookUpdateReceived(Update update) { super.onUpdateReceived(update); From a1034707e3e80146289a5617e32457a23de78ee6 Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Thu, 8 Oct 2020 15:33:30 +0200 Subject: [PATCH 14/45] Updated wiki --- TelegramBots.wiki/abilities/Advanced.md | 13 ++++++++++++- TelegramBots.wiki/abilities/Bot-Testing.md | 4 ++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/TelegramBots.wiki/abilities/Advanced.md b/TelegramBots.wiki/abilities/Advanced.md index ec2f4617..49cd2016 100644 --- a/TelegramBots.wiki/abilities/Advanced.md +++ b/TelegramBots.wiki/abilities/Advanced.md @@ -64,4 +64,15 @@ protected boolean allowContinuousText() { Please note that this may cause ability overlap. If multiple abilities can match the same command, the longest match will be taken. For example, if you have two abilities `do` and `do1`, the command `/do1` will trigger the `do1` ability. ## Statistics -AbilityBot can accrue basic statistics about the usage of your abilities and replies. Simply `enableStats()` on an Ability builder or `enableStats()` on replies to activate this feature. Once activated, you may call `/stats` and the bot will print a basic list of statistics. At the moment, AbilityBot only tracks hits. In the future, this will be enhanced to track more stats. \ No newline at end of file +AbilityBot can accrue basic statistics about the usage of your abilities and replies. Simply `enableStats()` on an Ability builder or `enableStats()` on replies to activate this feature. Once activated, you may call `/stats` and the bot will print a basic list of statistics. At the moment, AbilityBot only tracks hits. In the future, this will be enhanced to track more stats. + +## Execute code on bot registration +If you want to execute custom logic to initialize your bot, but you can't do it in the constructor, +you can override the `onRegister()` method: +``` +@Override +public void onRegister() { + super.onRegister(); + // Execute custom initialize logic here +} +``` diff --git a/TelegramBots.wiki/abilities/Bot-Testing.md b/TelegramBots.wiki/abilities/Bot-Testing.md index 4713518d..18993f46 100644 --- a/TelegramBots.wiki/abilities/Bot-Testing.md +++ b/TelegramBots.wiki/abilities/Bot-Testing.md @@ -104,6 +104,8 @@ public class ExampleBotTest { public void setUp() { // Create your bot bot = new ExampleBot(); + // Call onRegister() to initialize abilities etc. + bot.onRegister(); // Create a new sender as a mock silent = mock(SilentSender.class); // Set your bot silent sender to the mocked sender @@ -156,6 +158,7 @@ public class ExampleBotTest { // Offline instance will get deleted at JVM shutdown db = MapDBContext.offlineInstance("test"); bot = new ExampleBot(db); + bot.onRegister(); ... } @@ -180,6 +183,7 @@ public class ExampleBotTest { @Before public void setUp() { bot = new ExampleBot(db); + bot.onRegister(); sender = mock(MessageSender.class); SilentSender silent = new SilentSender(sender); // Create setter in your bot From 247ca5f984b6371d79c4742d1ca066fbef1d39fd Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Thu, 8 Oct 2020 15:46:31 +0200 Subject: [PATCH 15/45] Don't expose extensions in BaseAbilityBot --- .../abilitybots/api/bot/BaseAbilityBot.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) 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 01b18da4..455a43ae 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 @@ -106,7 +106,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability private final String botUsername; // Ability registry - protected final List extensions = new ArrayList<>(); + private final List extensions = new ArrayList<>(); private Map abilities; private Map stats; @@ -273,6 +273,18 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability return false; } + protected void addExtension(AbilityExtension extension) { + this.extensions.add(extension); + } + + protected void addExtensions(AbilityExtension... extensions) { + this.extensions.addAll(Arrays.asList(extensions)); + } + + protected void addExtensions(Collection extensions) { + this.extensions.addAll(extensions); + } + /** * Registers the declared abilities using method reflection. Also, replies are accumulated using the built abilities and standalone methods that return a Reply. *

From 3f07bfdff11b1f38945af7c6218f80122534fa29 Mon Sep 17 00:00:00 2001 From: Christian Blos Date: Thu, 8 Oct 2020 16:11:45 +0200 Subject: [PATCH 16/45] Updated ExtensionTest and wiki --- TelegramBots.wiki/abilities/Ability-Extensions.md | 14 ++++++++++++++ .../abilitybots/api/bot/ExtensionTest.java | 2 ++ 2 files changed, 16 insertions(+) diff --git a/TelegramBots.wiki/abilities/Ability-Extensions.md b/TelegramBots.wiki/abilities/Ability-Extensions.md index 60f5a482..45481632 100644 --- a/TelegramBots.wiki/abilities/Ability-Extensions.md +++ b/TelegramBots.wiki/abilities/Ability-Extensions.md @@ -35,6 +35,20 @@ public class MrBadGuy implements AbilityExtension { return new MrBadGuy(); } + // Override creatorId + } +``` + +It's also possible to add extensions in the constructor by using the `addExtension()` or `addExtensions()` method: + +```java + public class YourAwesomeBot implements AbilityBot { + + public YourAwesomeBot() { + super(/* pass required args ... */); + addExtensions(new MrGoodGuy(), new MrBadGuy()); + } + // Override creatorId } ``` \ No newline at end of file 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 8be53c13..2593c696 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 @@ -32,6 +32,7 @@ class ExtensionTest { assertTrue(hasAbilityNamed("direct"), "Failed to find Ability in directly declared in root extension/bot"); assertTrue(hasAbilityNamed("returningSuperClass0abc"), "Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension class"); assertTrue(hasAbilityNamed("returningSubClass0abc"), "Failed to find Ability in directly declared in extension returned by method returning the AbilityExtension subclass"); + assertTrue(hasAbilityNamed("addedInConstructor0abc"), "Failed to find Ability in directly declared in extension added in the constructor"); } private boolean hasAbilityNamed(String name) { @@ -41,6 +42,7 @@ class ExtensionTest { public static class ExtensionUsingBot extends AbilityBot { ExtensionUsingBot() { super("", "", offlineInstance("testing")); + addExtension(new AbilityBotExtension("addedInConstructor")); } @Override From 30fa92cd8b09792d4cc1f1ed98d6061de698a8ee Mon Sep 17 00:00:00 2001 From: Grig Alex Date: Tue, 20 Oct 2020 20:41:34 +0300 Subject: [PATCH 17/45] Replace botUsername with botUsernameSupplier --- .../commandbot/TelegramLongPollingCommandBot.java | 2 +- .../bots/commandbot/commands/CommandRegistry.java | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java index 05de2c72..24aadaf0 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java @@ -53,7 +53,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB */ public TelegramLongPollingCommandBot(DefaultBotOptions options, boolean allowCommandsWithUsername) { super(options); - this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this.getBotUsername()); + this.commandRegistry = new CommandRegistry(allowCommandsWithUsername, this::getBotUsername); } @Override diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java index f06e15fb..8277503d 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java @@ -7,7 +7,9 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.function.BiConsumer; +import java.util.function.Supplier; import java.util.regex.Pattern; /** @@ -19,17 +21,17 @@ public final class CommandRegistry implements ICommandRegistry { private final Map commandRegistryMap = new HashMap<>(); private final boolean allowCommandsWithUsername; - private final String botUsername; + private final Supplier botUsernameSupplier; private BiConsumer defaultConsumer; /** * Creates a Command registry * @param allowCommandsWithUsername True to allow commands with username, false otherwise - * @param botUsername Bot username + * @param botUsernameSupplier Bot username supplier */ - public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { + public CommandRegistry(boolean allowCommandsWithUsername, Supplier botUsernameSupplier) { this.allowCommandsWithUsername = allowCommandsWithUsername; - this.botUsername = botUsername; + this.botUsernameSupplier = botUsernameSupplier; } @Override @@ -123,6 +125,7 @@ public final class CommandRegistry implements ICommandRegistry { */ private String removeUsernameFromCommandIfNeeded(String command) { if (allowCommandsWithUsername) { + String botUsername = Objects.requireNonNull(botUsernameSupplier.get(), "Bot username must not be null"); return command.replaceAll("(?i)@" + Pattern.quote(botUsername), "").trim(); } return command; From 323d7607d6200f5dfab9f8d3ecbac9c162aa85c9 Mon Sep 17 00:00:00 2001 From: Grig Alex Date: Tue, 20 Oct 2020 22:10:06 +0300 Subject: [PATCH 18/45] Create tests for CommandRegistry --- .../commands/CommandRegistryTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java diff --git a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java new file mode 100644 index 00000000..232ea85b --- /dev/null +++ b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java @@ -0,0 +1,42 @@ +package org.telegram.telegrambots.extensions.bots.commandbot.commands; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.bots.AbsSender; + +class CommandRegistryTest { + + @Test + void should_executes_commandWithBotUsername() { + CommandRegistry registry = new CommandRegistry(true, () -> "BotUsername"); + IBotCommand command = Mockito.mock(IBotCommand.class); + Mockito.when(command.getCommandIdentifier()).thenReturn("command"); + registry.register(command); + AbsSender absSender = Mockito.mock(AbsSender.class); + Message message = Mockito.mock(Message.class); + Mockito.when(message.hasText()).thenReturn(true); + Mockito.when(message.getText()).thenReturn("/command@BotUsername I'll be test!"); + Assertions.assertTrue(registry.executeCommand(absSender, message), "Command must be executed"); + Mockito.verify(message).hasText(); + Mockito.verify(message).getText(); + Mockito.verify(command).processMessage( + Mockito.same(absSender), Mockito.same(message), Mockito.eq(new String[]{"I'll", "be", "test!"})); + } + + @Test + void should_throws_NPE_on_executes_commandWithNullableBotUsername() { + CommandRegistry registry = new CommandRegistry(true, () -> null); + IBotCommand command = Mockito.mock(IBotCommand.class); + Mockito.when(command.getCommandIdentifier()).thenReturn("command"); + registry.register(command); + AbsSender absSender = Mockito.mock(AbsSender.class); + Message message = Mockito.mock(Message.class); + Mockito.when(message.hasText()).thenReturn(true); + Mockito.when(message.getText()).thenReturn("/command@BotUsername ignore"); + NullPointerException exception = Assertions.assertThrows( + NullPointerException.class, () -> registry.executeCommand(absSender, message), "Bot username is null"); + Assertions.assertEquals("Bot username must not be null", exception.getMessage(), "Invalid exception message"); + } +} \ No newline at end of file From 5ea6fc9f09722af55336db94b800738fa8cc8662 Mon Sep 17 00:00:00 2001 From: Grig Alex Date: Wed, 21 Oct 2020 22:16:38 +0300 Subject: [PATCH 19/45] Add constructor with bot username --- .../bots/commandbot/commands/CommandRegistry.java | 12 ++++++++++++ .../commandbot/commands/CommandRegistryTest.java | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java index 8277503d..b7e9d2a2 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java @@ -24,6 +24,18 @@ public final class CommandRegistry implements ICommandRegistry { private final Supplier botUsernameSupplier; private BiConsumer defaultConsumer; + /** + * Creates a Command registry + * + * @param allowCommandsWithUsername True to allow commands with username, false otherwise + * @param botUsername Bot username + */ + public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { + Objects.requireNonNull(botUsername, "Bot username must not be null"); + this.allowCommandsWithUsername = allowCommandsWithUsername; + this.botUsernameSupplier = () -> botUsername; + } + /** * Creates a Command registry * @param allowCommandsWithUsername True to allow commands with username, false otherwise diff --git a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java index 232ea85b..2c22473c 100644 --- a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java +++ b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java @@ -8,6 +8,15 @@ import org.telegram.telegrambots.meta.bots.AbsSender; class CommandRegistryTest { + @Test + void should_create_registry() { + CommandRegistry registry = new CommandRegistry(true, "BotUsername"); + Assertions.assertNotNull(registry, "CommandRegistry is not created"); + NullPointerException exception = Assertions.assertThrows(NullPointerException.class, + () -> new CommandRegistry(true, (String) null)); + Assertions.assertEquals("Bot username must not be null", exception.getMessage(), "Invalid exception message"); + } + @Test void should_executes_commandWithBotUsername() { CommandRegistry registry = new CommandRegistry(true, () -> "BotUsername"); From cdef29f1ba915de2d609e8e069c5acbe62b8b5d4 Mon Sep 17 00:00:00 2001 From: Grig Alex Date: Sat, 24 Oct 2020 00:04:33 +0300 Subject: [PATCH 20/45] Deprecate old constructor --- .../extensions/bots/commandbot/commands/CommandRegistry.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java index b7e9d2a2..33fdfe17 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java @@ -29,7 +29,10 @@ public final class CommandRegistry implements ICommandRegistry { * * @param allowCommandsWithUsername True to allow commands with username, false otherwise * @param botUsername Bot username + * @throws java.lang.NullPointerException if {@code botUsername} is {@code null} + * @deprecated Use {@link #CommandRegistry(boolean, java.util.function.Supplier)} instead */ + @Deprecated public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { Objects.requireNonNull(botUsername, "Bot username must not be null"); this.allowCommandsWithUsername = allowCommandsWithUsername; @@ -134,6 +137,8 @@ public final class CommandRegistry implements ICommandRegistry { * the command * @param command Command to simplify * @return Simplified command + * @throws java.lang.NullPointerException if {@code allowCommandsWithUsername} is {@code true} + * and {@code botUsernameSupplier} returns {@code null} */ private String removeUsernameFromCommandIfNeeded(String command) { if (allowCommandsWithUsername) { From b4684b9ec7bd8b5d14f65a9a2203349f20adf679 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Mon, 26 Oct 2020 01:25:35 +0000 Subject: [PATCH 21/45] Fix bug --- .../main/java/org/telegram/abilitybots/api/objects/Ability.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 fbb319bc..d3880cb7 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 @@ -17,7 +17,7 @@ import static com.google.common.collect.Lists.newArrayList; import static java.lang.String.format; import static java.util.Objects.hash; import static java.util.Optional.ofNullable; -import static org.apache.commons.lang3.StringUtils.*; +import static org.telegram.abilitybots.api.util.AbilityUtils.isValidCommandName; /** * An ability is a fully-fledged bot action that contains all the necessary information to process: From ac83b5d5178a79d6b7567aa22da42af9044f90c8 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Wed, 28 Oct 2020 22:16:13 +0000 Subject: [PATCH 22/45] Update version --- README.md | 8 ++++---- TelegramBots.wiki/Changelog.md | 3 +++ TelegramBots.wiki/Getting-Started.md | 4 ++-- TelegramBots.wiki/abilities/Simple-Example.md | 4 ++-- pom.xml | 2 +- telegrambots-abilities/README.md | 8 ++++---- telegrambots-abilities/pom.xml | 4 ++-- telegrambots-chat-session-bot/README.md | 2 +- telegrambots-chat-session-bot/pom.xml | 4 ++-- telegrambots-extensions/README.md | 4 ++-- telegrambots-extensions/pom.xml | 4 ++-- telegrambots-meta/pom.xml | 2 +- telegrambots-spring-boot-starter/README.md | 4 ++-- telegrambots-spring-boot-starter/pom.xml | 4 ++-- telegrambots/pom.xml | 4 ++-- 15 files changed, 32 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 46836ab8..944beae8 100644 --- a/README.md +++ b/README.md @@ -27,16 +27,16 @@ Just import add the library to your project with one of these options: org.telegram telegrambots - 4.9.1 + 4.9.2 ``` ```gradle - compile "org.telegram:telegrambots:4.9.1" + compile "org.telegram:telegrambots:4.9.2" ``` - 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/4.9.1) - 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/4.9.1) + 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/4.9.2) + 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/4.9.2) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 15818304..62d825b8 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,3 +1,6 @@ +### 4.9.2 ### +1. Bug fixing: #792, #801, #804, #810, #812, #813, #820 and #814 + ### 4.9.1 ### 1. Bug fixing: #767, #766, #761, #763, #776, #772, #771, #780 diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md index a22d6719..d86c611d 100644 --- a/TelegramBots.wiki/Getting-Started.md +++ b/TelegramBots.wiki/Getting-Started.md @@ -11,13 +11,13 @@ First you need ot get the library and add it to your project. There are few poss org.telegram telegrambots - 4.9.1 + 4.9.2 ``` * With **Gradle**: ```groovy - compile group: 'org.telegram', name: 'telegrambots', version: '4.9.1' + compile group: 'org.telegram', name: 'telegrambots', version: '4.9.2' ``` 2. Don't like **Maven Central Repository**? It can also be taken from [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots). diff --git a/TelegramBots.wiki/abilities/Simple-Example.md b/TelegramBots.wiki/abilities/Simple-Example.md index a6e2492f..c687f25e 100644 --- a/TelegramBots.wiki/abilities/Simple-Example.md +++ b/TelegramBots.wiki/abilities/Simple-Example.md @@ -9,12 +9,12 @@ As with any Java project, you will need to set your dependencies. org.telegram telegrambots-abilities - 4.9.1 + 4.9.2 ``` * **Gradle** ```groovy - implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '4.9.1' + implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '4.9.2' ``` * [JitPack](https://jitpack.io/#rubenlagus/TelegramBots) diff --git a/pom.xml b/pom.xml index 523f4dfd..4704c1e6 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots pom - 4.9.1 + 4.9.2 telegrambots diff --git a/telegrambots-abilities/README.md b/telegrambots-abilities/README.md index 62f3579a..c7455741 100644 --- a/telegrambots-abilities/README.md +++ b/telegrambots-abilities/README.md @@ -18,19 +18,19 @@ Usage org.telegram telegrambots-abilities - 4.9.1 + 4.9.2 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-abilities:4.9.1" + compile "org.telegram:telegrambots-abilities:4.9.2" ``` -**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v4.9.1) +**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v4.9.2) -**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v4.9.1) +**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v4.9.2) Motivation ---------- diff --git a/telegrambots-abilities/pom.xml b/telegrambots-abilities/pom.xml index de940fed..a52cfb24 100644 --- a/telegrambots-abilities/pom.xml +++ b/telegrambots-abilities/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambots-abilities @@ -84,7 +84,7 @@ org.telegram telegrambots - 4.9.1 + 4.9.2 org.apache.commons diff --git a/telegrambots-chat-session-bot/README.md b/telegrambots-chat-session-bot/README.md index 1802bdd4..479c1d5c 100644 --- a/telegrambots-chat-session-bot/README.md +++ b/telegrambots-chat-session-bot/README.md @@ -15,7 +15,7 @@ Usage org.telegram telegrambots-chat-session-bot - 4.9.1 + 4.9.2 ``` diff --git a/telegrambots-chat-session-bot/pom.xml b/telegrambots-chat-session-bot/pom.xml index a1291c1f..e5e0138a 100644 --- a/telegrambots-chat-session-bot/pom.xml +++ b/telegrambots-chat-session-bot/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambots-chat-session-bot @@ -84,7 +84,7 @@ org.telegram telegrambots - 4.9.1 + 4.9.2 diff --git a/telegrambots-extensions/README.md b/telegrambots-extensions/README.md index 998f63c4..91fa288b 100644 --- a/telegrambots-extensions/README.md +++ b/telegrambots-extensions/README.md @@ -16,12 +16,12 @@ Just import add the library to your project with one of these options: org.telegram telegrambotsextensions - 4.9.1 + 4.9.2 ``` 2. Using Gradle: ```gradle - compile "org.telegram:telegrambotsextensions:4.9.1" + compile "org.telegram:telegrambotsextensions:4.9.2" ``` \ No newline at end of file diff --git a/telegrambots-extensions/pom.xml b/telegrambots-extensions/pom.xml index e0fdc053..0b16870d 100644 --- a/telegrambots-extensions/pom.xml +++ b/telegrambots-extensions/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambotsextensions @@ -75,7 +75,7 @@ org.telegram telegrambots - 4.9.1 + 4.9.2 diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index c31ab809..46ed343d 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambots-meta diff --git a/telegrambots-spring-boot-starter/README.md b/telegrambots-spring-boot-starter/README.md index dc6b0e03..422e3380 100644 --- a/telegrambots-spring-boot-starter/README.md +++ b/telegrambots-spring-boot-starter/README.md @@ -18,14 +18,14 @@ Usage org.telegram telegrambots-spring-boot-starter - 4.9.1 + 4.9.2 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-spring-boot-starter:4.9.1" + compile "org.telegram:telegrambots-spring-boot-starter:4.9.2" ``` Motivation diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index 90b989ab..aeb03f45 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambots-spring-boot-starter @@ -70,7 +70,7 @@ UTF-8 UTF-8 - 4.9.1 + 4.9.2 2.3.3.RELEASE 3.14.0 diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 66e70503..83779007 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.1 + 4.9.2 telegrambots @@ -95,7 +95,7 @@ org.telegram telegrambots-meta - 4.9.1 + 4.9.2 com.fasterxml.jackson.core From 341c330857542a9d032d104c33da70f272726085 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 28 Oct 2020 22:34:50 +0000 Subject: [PATCH 23/45] Add files via upload --- TelegramBots.svg | Bin 0 -> 1218 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 TelegramBots.svg diff --git a/TelegramBots.svg b/TelegramBots.svg new file mode 100644 index 0000000000000000000000000000000000000000..454f96db0c9bb2ebbb352fd912cdf742a809b14b GIT binary patch literal 1218 zcmex=F7_W3|#BpDf)n2`(tn##n$!p06ZgGm5rw)Wa>z4`Nf*FJE^s+@_1ff1^l8KivC zi4`Hson}no@CGW^5ny0qVq{@pWoBlDI1}VVK?YVKVKzl2!$1+EMA4E>DymLFMNmgG z+B58|JNw({)>dOrlb*=CeV*!`qB9ky9dcH7mJC#B^bFB`Bk`N(^=3bn{>GBjCwrzV zOUf(9iBJBW{O{?1hOXC}J>uNBx+42GFsr=Y9Hg^hs*tjxmIND1ioAjQgV&p5XFXq$ zHf_&J9U~*F387OSG?_juzwP$=Z}ox2FPFc_{CG+IwQcO2y*8Eg+ovtKm#}bKzPHM6 z&aJAwTV_1)Skn08(;G!;!;SLK0t%!WZDc0B_tJgyY|A!t)!u6D)$T`)8QmsNo~r)l z^?~c%+YNUd-rzO)^2Fe*E;E6S&`T~SQYR)cPX8bs$24oz+wHqk8r60FGx&V7DCM-3 zFHc`=Q`{F9HS6DH5%DOB4 zQ|L5U*(pBdrB)I9on)(9K~q!xaaN_V%r^heo!^A0~b#qdMpU#8x_a&D@mNho1bK z@tt!tY+SVQAS4+x0#ns`=c@17 z;+Mti;!ngsGm)C-tLDR@?Y?KDZnT&^XXRp%`>Q@aZkTQs6$`th+K*(-al?K_pM zdHO2P@=1~IfptqizBxbf#4r1OLOm%Vjb;_;r<{Uj0G*;I2yzJ%3qQ;ypbP{|;{rm8 zN{)#@$0!>bnFIzEHcni)Xd~D;%pm9N_j|Ez+TGa?8b!bSe6@UM0qgmz`R_U1qzxX2 zh?WI!$-2eLm#{RA*IKt&rhEOlb?c&k9XV(;?NH3)89t_C1M; MA#FR@?El{c05t)z2mk;8 literal 0 HcmV?d00001 From 48f9bf810562bba4ac7cbd01ecca1ccabc44140b Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 28 Oct 2020 22:39:23 +0000 Subject: [PATCH 24/45] Add files via upload --- TelegramBots.svg | Bin 1218 -> 998 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/TelegramBots.svg b/TelegramBots.svg index 454f96db0c9bb2ebbb352fd912cdf742a809b14b..da15af2f74b6007506670a796a16d41e6a905970 100644 GIT binary patch literal 998 zcma)5%Wm5+5WE-YKP(s&XaLKiCD}~^F+neF4sA|J@03JIL@3fA8OzDncPYz{I8agO zKyW!TJNr<6x9t>cgmuzrMiz5QK^#S5jyXvSOqluuT|2_$waB z`!a$9-g&bIQ`b(Q3_`*^DvdIhk&B{0?hr9+UP}MU$b3N{-sSp0$EQhf9=~@s+U>Y| z9!&BRPgazEs!Xt3Mp6Q`R0C5Gk0Ji8i z1=^7njEz*U4FqJZ=t-PiyjG>m#nq zHVmSZRiy+LZM2VS-bsa%xEE?8ye#>HcoEUBun4n53_=igK{!UwP_yq=ay9!SY{fO7 zIj&vggq7ISA(fMF0yhTdy5ESQ-@{u!u3lkOb<*A78*oI66|Nf|*x#`%x(MIy8Xfm3 vCAVeEeI5tqak0*IvVX%?-~KF7_W3|#BpDf)n2`(tn##n$!p06ZgGm5rw)Wa>z4`Nf*FJE^s+@_1ff1^l8KivC zi4`Hson}no@CGW^5ny0qVq{@pWoBlDI1}VVK?YVKVKzl2!$1+EMA4E>DymLFMNmgG z+B58|JNw({)>dOrlb*=CeV*!`qB9ky9dcH7mJC#B^bFB`Bk`N(^=3bn{>GBjCwrzV zOUf(9iBJBW{O{?1hOXC}J>uNBx+42GFsr=Y9Hg^hs*tjxmIND1ioAjQgV&p5XFXq$ zHf_&J9U~*F387OSG?_juzwP$=Z}ox2FPFc_{CG+IwQcO2y*8Eg+ovtKm#}bKzPHM6 z&aJAwTV_1)Skn08(;G!;!;SLK0t%!WZDc0B_tJgyY|A!t)!u6D)$T`)8QmsNo~r)l z^?~c%+YNUd-rzO)^2Fe*E;E6S&`T~SQYR)cPX8bs$24oz+wHqk8r60FGx&V7DCM-3 zFHc`=Q`{F9HS6DH5%DOB4 zQ|L5U*(pBdrB)I9on)(9K~q!xaaN_V%r^heo!^A0~b#qdMpU#8x_a&D@mNho1bK z@tt!tY+SVQAS4+x0#ns`=c@17 z;+Mti;!ngsGm)C-tLDR@?Y?KDZnT&^XXRp%`>Q@aZkTQs6$`th+K*(-al?K_pM zdHO2P@=1~IfptqizBxbf#4r1OLOm%Vjb;_;r<{Uj0G*;I2yzJ%3qQ;ypbP{|;{rm8 zN{)#@$0!>bnFIzEHcni)Xd~D;%pm9N_j|Ez+TGa?8b!bSe6@UM0qgmz`R_U1qzxX2 zh?WI!$-2eLm#{RA*IKt&rhEOlb?c&k9XV(;?NH3)89t_C1M; MA#FR@?El{c05t)z2mk;8 From f776950240ac960651bd1a3d149667a231bf3e46 Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Wed, 28 Oct 2020 22:42:49 +0000 Subject: [PATCH 25/45] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 944beae8..22ef1b08 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Telegram Bot Java Library -[![Telegram](http://trellobot.doomdns.org/telegrambadge.svg)](https://telegram.me/JavaBotsApi) +[![Telegram](/TelegramBots.svg)](https://telegram.me/JavaBotsApi) [![Build Status](https://travis-ci.org/rubenlagus/TelegramBots.svg?branch=master)](https://travis-ci.org/rubenlagus/TelegramBots) From 6b18fbb54564c1484a7f2cb7a6c3656800fcb2ab Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sat, 31 Oct 2020 13:04:38 +0000 Subject: [PATCH 26/45] Remove deprecated versions --- .../commandbot/commands/CommandRegistry.java | 17 +---- .../api/interfaces/InputBotApiObject.java | 17 ----- .../DeleteStickerSetName.java | 14 ---- .../GetChatMemberCount.java | 11 --- .../RestrictChatMember.java | 68 ----------------- .../EditMessageLiveLocation.java | 21 +---- .../telegrambots/meta/api/objects/Chat.java | 8 -- .../meta/api/objects/ChatMember.java | 8 -- .../meta/api/objects/InputFile.java | 4 +- .../meta/api/objects/LoginUrl.java | 4 +- .../InputMessageContent.java | 4 +- .../inlinequery/result/InlineQueryResult.java | 4 +- .../chached/InlineQueryResultCachedAudio.java | 15 ---- .../InlineQueryResultCachedDocument.java | 16 ---- .../chached/InlineQueryResultCachedGif.java | 13 ---- .../InlineQueryResultCachedMpeg4Gif.java | 13 ---- .../chached/InlineQueryResultCachedPhoto.java | 13 ---- .../InlineQueryResultCachedSticker.java | 16 ---- .../chached/InlineQueryResultCachedVideo.java | 13 ---- .../chached/InlineQueryResultCachedVoice.java | 15 ---- .../meta/api/objects/media/InputMedia.java | 6 +- .../dataerror/PassportElementError.java | 4 +- .../api/objects/payments/LabeledPrice.java | 6 +- .../api/objects/payments/ShippingOption.java | 4 +- .../objects/replykeyboard/ApiResponse.java | 76 ------------------- .../objects/replykeyboard/ReplyKeyboard.java | 3 +- .../buttons/InlineKeyboardButton.java | 12 +-- .../replykeyboard/buttons/KeyboardButton.java | 4 +- .../api/objects/stickers/MaskPosition.java | 4 +- 29 files changed, 31 insertions(+), 382 deletions(-) delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/interfaces/InputBotApiObject.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteStickerSetName.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMemberCount.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ApiResponse.java diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java index 33fdfe17..dcbf84aa 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java @@ -24,21 +24,6 @@ public final class CommandRegistry implements ICommandRegistry { private final Supplier botUsernameSupplier; private BiConsumer defaultConsumer; - /** - * Creates a Command registry - * - * @param allowCommandsWithUsername True to allow commands with username, false otherwise - * @param botUsername Bot username - * @throws java.lang.NullPointerException if {@code botUsername} is {@code null} - * @deprecated Use {@link #CommandRegistry(boolean, java.util.function.Supplier)} instead - */ - @Deprecated - public CommandRegistry(boolean allowCommandsWithUsername, String botUsername) { - Objects.requireNonNull(botUsername, "Bot username must not be null"); - this.allowCommandsWithUsername = allowCommandsWithUsername; - this.botUsernameSupplier = () -> botUsername; - } - /** * Creates a Command registry * @param allowCommandsWithUsername True to allow commands with username, false otherwise @@ -103,7 +88,7 @@ public final class CommandRegistry implements ICommandRegistry { /** * Executes a command action if the command is registered. * - * @note If the command is not registered and there is a default consumer, + * @apiNote If the command is not registered and there is a default consumer, * that action will be performed * * @param absSender absSender diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/interfaces/InputBotApiObject.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/interfaces/InputBotApiObject.java deleted file mode 100644 index 518f0fe0..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/interfaces/InputBotApiObject.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.telegram.telegrambots.meta.api.interfaces; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; - -/** - * @author Ruben Bermudez - * @version 1.0 - * An object used in the Bots API to answer updates - * - * @deprecated Please, use BotApiObject directly - */ -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonInclude(JsonInclude.Include.NON_NULL) -@Deprecated -public interface InputBotApiObject extends BotApiObject { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteStickerSetName.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteStickerSetName.java deleted file mode 100644 index 23154628..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteStickerSetName.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.telegram.telegrambots.meta.api.methods.groupadministration; - -/** - * @author Ruben Bermudez - * @version 3.4 - * Use this method to delete a group sticker set from a supergroup. - * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - * Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. - * Returns True on success. - * @deprecated Replaced by {@link DeleteChatStickerSet} - */ -@Deprecated -public class DeleteStickerSetName extends DeleteChatStickerSet { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMemberCount.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMemberCount.java deleted file mode 100644 index 6724a9ec..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMemberCount.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.telegram.telegrambots.meta.api.methods.groupadministration; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Use this method to get the number of members in a chat. Returns Int on success. - * @deprecated Replaced by {@link GetChatMembersCount} - */ -@Deprecated -public class GetChatMemberCount extends GetChatMembersCount { -} 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 b68e417b..137c66bb 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 @@ -123,74 +123,6 @@ public class RestrictChatMember extends BotApiMethod { return setUntilDate(Instant.now().plusMillis(duration.toMillis())); } - /** - * @deprecated Use {@link #getPermissions()} instead - */ - @Deprecated - public Boolean getCanSendMessages() { - return canSendMessages; - } - - /** - * @deprecated Use {@link #setPermissions(ChatPermissions)} instead - */ - @Deprecated - public RestrictChatMember setCanSendMessages(Boolean canSendMessages) { - this.canSendMessages = canSendMessages; - return this; - } - - /** - * @deprecated Use {@link #getPermissions()} instead - */ - @Deprecated - public Boolean getCanSendMediaMessages() { - return canSendMediaMessages; - } - - /** - * @deprecated Use {@link #setPermissions(ChatPermissions)} instead - */ - @Deprecated - public RestrictChatMember setCanSendMediaMessages(Boolean canSendMediaMessages) { - this.canSendMediaMessages = canSendMediaMessages; - return this; - } - - /** - * @deprecated Use {@link #getPermissions()} instead - */ - @Deprecated - public Boolean getCanSendOtherMessages() { - return canSendOtherMessages; - } - - /** - * @deprecated Use {@link #setPermissions(ChatPermissions)} instead - */ - @Deprecated - public RestrictChatMember setCanSendOtherMessages(Boolean canSendOtherMessages) { - this.canSendOtherMessages = canSendOtherMessages; - return this; - } - - /** - * @deprecated Use {@link #getPermissions()} instead - */ - @Deprecated - public Boolean getCanAddWebPagePreviews() { - return canAddWebPagePreviews; - } - - /** - * @deprecated Use {@link #setPermissions(ChatPermissions)} instead - */ - @Deprecated - public RestrictChatMember setCanAddWebPagePreviews(Boolean canAddWebPagePreviews) { - this.canAddWebPagePreviews = canAddWebPagePreviews; - return this; - } - public ChatPermissions getPermissions() { return permissions; } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java index 196e0752..2aa85ebc 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java @@ -1,11 +1,10 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -110,28 +109,10 @@ public class EditMessageLiveLocation extends BotApiMethod { return this; } - /** - * @deprecated Replaced by {@link #getLongitude()} - */ - @Deprecated - @JsonIgnore - public Float getLongitud() { - return longitude; - } - public Float getLongitude() { return longitude; } - /** - * @deprecated Replaced by {@link #setLongitude(Float)} - */ - @Deprecated - @JsonIgnore - public EditMessageLiveLocation setLongitud(Float longitude) { - return setLongitude(longitude); - } - public EditMessageLiveLocation setLongitude(Float longitude) { Objects.requireNonNull(longitude); this.longitude = longitude; 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 2fedbf9c..266c5692 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 @@ -127,14 +127,6 @@ public class Chat implements BotApiObject { return permissions; } - /** - * @deprecated Use {@link #getPermissions()} instead - */ - @Deprecated - public Boolean getAllMembersAreAdministrators() { - return allMembersAreAdministrators; - } - public ChatPhoto getPhoto() { return photo; } 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 3ab0c240..3da476d3 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 @@ -121,14 +121,6 @@ public class ChatMember implements BotApiObject { return canRestrictMembers; } - /** - * @deprecated Use {{@link #getCanRestrictMembers()}} - */ - @Deprecated - public Boolean getCanRestrictUsers() { - return canRestrictMembers; - } - public Boolean getCanPinMessages() { return canPinMessages; } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java index 7619ead4..9326d2e9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java @@ -2,7 +2,7 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -17,7 +17,7 @@ import java.io.InputStream; */ @SuppressWarnings({"WeakerAccess", "UnusedReturnValue"}) @JsonSerialize(using = InputFileSerializer.class, as = String.class) -public class InputFile implements InputBotApiObject, Validable { +public class InputFile implements Validable, BotApiObject { private String attachName; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java index c3d85987..4b4821c7 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -18,7 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; * All the user needs to do is tap/click a button and confirm that they want to log in. */ @SuppressWarnings("unused") -public class LoginUrl implements InputBotApiObject, Validable { +public class LoginUrl implements Validable, BotApiObject { private static final String URL_FIELD = "url"; private static final String FORWARD_TEXT_FIELD = "forward_text"; private static final String BOT_USERNAME_FIELD = "bot_username"; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java index 3c69ec1e..c8054213 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputMessageContent.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.serialization.InputMessageContentDeserializer; @@ -12,5 +12,5 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessageconten * query. */ @JsonDeserialize(using = InputMessageContentDeserializer.class) -public interface InputMessageContent extends InputBotApiObject, Validable { +public interface InputMessageContent extends Validable, BotApiObject { } 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 3950bd38..67d7c6b0 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 @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.serialization.InlineQueryResultDeserializer; @@ -11,5 +11,5 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.result.serializati * This object represents one result of an inline query. */ @JsonDeserialize(using = InlineQueryResultDeserializer.class) -public interface InlineQueryResult extends InputBotApiObject, Validable { +public interface InlineQueryResult extends Validable, BotApiObject { } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java deleted file mode 100644 index 68ac6663..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedAudio.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to an mp3 audio file stored on the Telegram servers. By default, this - * audio file will be sent by the user. Alternatively, you can use input_message_content to send a - * message with the specified content instead of the audio. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will - * ignore them. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedAudio} - */ -@Deprecated -public class InlineQueryResultCachedAudio extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedAudio { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java deleted file mode 100644 index e20809af..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedDocument.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a file stored on the Telegram servers. By default, this file will be - * sent by the user with an optional caption. Alternatively, you can use input_message_content to - * send a message with the specified content instead of the file. - * @note Currently, only pdf-files and zip archives can be sent using this method. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will - * ignore them. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedDocument} - */ -@Deprecated -public class InlineQueryResultCachedDocument extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedDocument { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java deleted file mode 100644 index d5c89e03..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedGif.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to an animated GIF file stored on the Telegram servers. By default, this - * animated GIF file will be sent by the user with an optional caption. Alternatively, you can use - * input_message_content to send a message with specified content instead of the animation. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedGif} - */ -@Deprecated -public class InlineQueryResultCachedGif extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedGif { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java deleted file mode 100644 index ff756d70..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedMpeg4Gif.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, - * this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can - * use input_message_content to send a message with the specified content instead of the animation. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedMpeg4Gif} - */ -@Deprecated -public class InlineQueryResultCachedMpeg4Gif extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedMpeg4Gif { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java deleted file mode 100644 index 50224520..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedPhoto.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a photo stored on the Telegram servers. By default, this photo will - * be sent by the user with an optional caption. Alternatively, you can use input_message_content to - * send a message with the specified content instead of the photo. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedPhoto} - */ -@Deprecated -public class InlineQueryResultCachedPhoto extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedPhoto { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java deleted file mode 100644 index 299b5280..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedSticker.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a sticker stored on the Telegram servers. By default, this sticker - * will be sent by the user. Alternatively, you can use input_message_content to send a message with - * the specified content instead of the sticker. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will - * ignore them. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedSticker} - */ -@Deprecated -public class InlineQueryResultCachedSticker extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedSticker { - -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java deleted file mode 100644 index 6bde7323..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVideo.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a video file stored on the Telegram servers. By default, this video - * file will be sent by the user with an optional caption. Alternatively, you can use - * input_message_content to send a message with the specified content instead of the video. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedVideo} - */ -@Deprecated -public class InlineQueryResultCachedVideo extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedVideo { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java deleted file mode 100644 index b53ade0d..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/chached/InlineQueryResultCachedVoice.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.inlinequery.result.chached; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Represents a link to a voice message stored on the Telegram servers. By default, this - * voice message will be sent by the user. Alternatively, you can use input_message_content to send - * a message with the specified content instead of the voice message. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will - * ignore them. - * @deprecated Replaced by {@link org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedVoice} - */ -@Deprecated -public class InlineQueryResultCachedVoice extends org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached.InlineQueryResultCachedVoice { -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java index d83f3190..45855293 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.media.serialization.InputMediaDeserializer; import org.telegram.telegrambots.meta.api.objects.media.serialization.InputMediaSerializer; @@ -20,7 +20,7 @@ import java.io.InputStream; @SuppressWarnings({"unchecked"}) @JsonSerialize(using = InputMediaSerializer.class) @JsonDeserialize(using = InputMediaDeserializer.class) -public abstract class InputMedia implements InputBotApiObject, Validable { +public abstract class InputMedia implements Validable, BotApiObject { public static final String TYPE_FIELD = "type"; public static final String MEDIA_FIELD = "media"; public static final String CAPTION_FIELD = "caption"; @@ -117,7 +117,7 @@ public abstract class InputMedia implements InputBotApiObject, Validable { return caption; } - public InputMedia setCaption(String caption) { + public InputMedia setCaption(String caption) { this.caption = caption; return this; } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementError.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementError.java index 4b1dd918..744203f7 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementError.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementError.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.passport.dataerror.serialization.PassportElementErrorDeserializer; @@ -22,5 +22,5 @@ import org.telegram.telegrambots.meta.api.objects.passport.dataerror.serializati * PassportElementErrorTranslationFiles */ @JsonDeserialize(using = PassportElementErrorDeserializer.class) -public interface PassportElementError extends InputBotApiObject, Validable { +public interface PassportElementError extends Validable, BotApiObject { } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java index 38f03403..9ddcd105 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.payments; import com.fasterxml.jackson.annotation.JsonProperty; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -12,17 +12,17 @@ import static com.google.common.base.Preconditions.checkNotNull; * @version 1.0 * This object represents a portion of goods price. */ -public class LabeledPrice implements InputBotApiObject, Validable { +public class LabeledPrice implements Validable, BotApiObject { private static final String LABEL_FIELD = "label"; private static final String AMOUNT_FIELD = "amount"; @JsonProperty(LABEL_FIELD) private String label; ///< Portion label - @JsonProperty(AMOUNT_FIELD) /** * Price of the product in the smallest units of the currency (integer, not float/double). * For example, for a price of US$ 1.45 pass amount = 145. */ + @JsonProperty(AMOUNT_FIELD) private Integer amount; /** diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java index 58a6446f..ea883ff2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.payments; import com.fasterxml.jackson.annotation.JsonProperty; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -15,7 +15,7 @@ import static com.google.common.base.Preconditions.checkNotNull; * * This object represents one shipping option. */ -public class ShippingOption implements InputBotApiObject, Validable { +public class ShippingOption implements Validable, BotApiObject { private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String PRICES_FIELD = "prices"; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ApiResponse.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ApiResponse.java deleted file mode 100644 index bcaa1082..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ApiResponse.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.telegram.telegrambots.meta.api.objects.replykeyboard; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.telegram.telegrambots.meta.api.objects.ResponseParameters; - -import java.io.Serializable; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Response from Telegram Server - * - * @deprecated Please, use {@link org.telegram.telegrambots.meta.api.objects.ApiResponse} instead. - * This class will be removed - */ -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonInclude(JsonInclude.Include.NON_NULL) -@Deprecated -public class ApiResponse implements Serializable { - private static final String OK_FIELD = "ok"; - private static final String ERROR_CODE_FIELD = "error_code"; - private static final String DESCRIPTION_CODE_FIELD = "description"; - private static final String PARAMETERS_FIELD = "parameters"; - private static final String RESULT_FIELD = "result"; - - @JsonProperty(OK_FIELD) - private Boolean ok; - @JsonProperty(ERROR_CODE_FIELD) - private Integer errorCode; - @JsonProperty(DESCRIPTION_CODE_FIELD) - private String errorDescription; - @JsonProperty(PARAMETERS_FIELD) - private ResponseParameters parameters; - @JsonProperty(RESULT_FIELD) - private T result; - - public Boolean getOk() { - return ok; - } - - public Integer getErrorCode() { - return errorCode; - } - - public String getErrorDescription() { - return errorDescription; - } - - public T getResult() { - return result; - } - - public ResponseParameters getParameters() { - return parameters; - } - - @Override - public String toString() { - if (ok) { - return "ApiResponse{" + - "ok=" + ok + - ", result=" + result + - '}'; - } else { - return "ApiResponse{" + - "ok=" + ok + - ", errorCode=" + errorCode + - ", errorDescription='" + errorDescription + '\'' + - ", parameters='" + parameters + '\'' + - '}'; - } - } -} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboard.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboard.java index d07ee5e7..e6487914 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboard.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboard.java @@ -2,7 +2,6 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.replykeyboard.serialization.KeyboardDeserializer; @@ -12,5 +11,5 @@ import org.telegram.telegrambots.meta.api.objects.replykeyboard.serialization.Ke * Reply keyboard abstract type */ @JsonDeserialize(using = KeyboardDeserializer.class) -public interface ReplyKeyboard extends InputBotApiObject, BotApiObject, Validable { +public interface ReplyKeyboard extends BotApiObject, Validable { } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java index 7bd349fb..20017a11 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; import com.fasterxml.jackson.annotation.JsonProperty; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.LoginUrl; import org.telegram.telegrambots.meta.api.objects.games.CallbackGame; @@ -16,10 +16,10 @@ import static com.google.common.base.Preconditions.checkNotNull; * @version 1.0 * This object represents one button of an inline keyboard. You must use exactly one of the * optional fields. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * display unsupported message. */ -public class InlineKeyboardButton implements InputBotApiObject, Validable { +public class InlineKeyboardButton implements Validable, BotApiObject { private static final String TEXT_FIELD = "text"; private static final String URL_FIELD = "url"; @@ -39,7 +39,7 @@ public class InlineKeyboardButton implements InputBotApiObject, Validable { /** * Optional. Description of the game that will be launched when the user presses the button. * - * @note This type of button must always be the first button in the first row. + * @apiNote This type of button must always be the first button in the first row. */ @JsonProperty(CALLBACK_GAME_FIELD) private CallbackGame callbackGame; @@ -49,7 +49,7 @@ public class InlineKeyboardButton implements InputBotApiObject, Validable { * open that chat and insert the bot‘s username and the specified inline query in the input field. * Can be empty, in which case just the bot’s username will be inserted. * - * @note This offers an easy way for users to start using your bot in inline mode when + * @apiNote This offers an easy way for users to start using your bot in inline mode when * they are currently in a private chat with it. * Especially useful when combined with switch_pm… actions – in this case the user will * be automatically returned to the chat they switched from, skipping the chat selection screen. @@ -67,7 +67,7 @@ public class InlineKeyboardButton implements InputBotApiObject, Validable { /** * Optional. Specify True, to send a Buy button. * - * @note This type of button must always be the first button in the first row. + * @apiNote This type of button must always be the first button in the first row. */ @JsonProperty(PAY_FIELD) private Boolean pay; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java index 091d8d12..dbf087e7 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java @@ -1,7 +1,7 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; import com.fasterxml.jackson.annotation.JsonProperty; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -19,7 +19,7 @@ import java.util.Objects; * @apiNote request_poll option will only work in Telegram versions released after 1X January, 2020. * Older clients will receive unsupported message. */ -public class KeyboardButton implements InputBotApiObject, Validable { +public class KeyboardButton implements Validable, BotApiObject { private static final String TEXT_FIELD = "text"; private static final String REQUEST_CONTACT_FIELD = "request_contact"; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java index 647cec40..b69d9cba 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java @@ -2,7 +2,7 @@ package org.telegram.telegrambots.meta.api.objects.stickers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.telegram.telegrambots.meta.api.interfaces.InputBotApiObject; +import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -12,7 +12,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * This object describes the position on faces where a mask should be placed by default. */ @JsonTypeInfo(use=JsonTypeInfo.Id.NONE) -public class MaskPosition implements InputBotApiObject, Validable { +public class MaskPosition implements Validable, BotApiObject { private static final String POINT_FIELD = "point"; private static final String XSHIFT_FIELD = "x_shift"; private static final String YSHIFT_FIELD = "y_shift"; From 0a58ef7120e54af0bf639f10131fa52146e9c5ce Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sat, 31 Oct 2020 13:19:19 +0000 Subject: [PATCH 27/45] Remove deprecated versions --- .../bots/commandbot/commands/CommandRegistryTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java index 2c22473c..9b847418 100644 --- a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java +++ b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java @@ -10,10 +10,10 @@ class CommandRegistryTest { @Test void should_create_registry() { - CommandRegistry registry = new CommandRegistry(true, "BotUsername"); + CommandRegistry registry = new CommandRegistry(true, () -> "BotUsername"); Assertions.assertNotNull(registry, "CommandRegistry is not created"); NullPointerException exception = Assertions.assertThrows(NullPointerException.class, - () -> new CommandRegistry(true, (String) null)); + () -> new CommandRegistry(true, () -> "BotUsername")); Assertions.assertEquals("Bot username must not be null", exception.getMessage(), "Invalid exception message"); } From 4fb51ec99c592facd0a72adfee8ad3885133d2ae Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sat, 31 Oct 2020 13:41:05 +0000 Subject: [PATCH 28/45] Added lombok --- pom.xml | 7 ++ telegrambots-meta/pom.xml | 5 ++ .../meta/api/methods/BotApiMethod.java | 2 + .../meta/api/objects/commands/BotCommand.java | 48 +++-------- .../meta/api/objects/games/Animation.java | 59 +------------ .../meta/api/objects/games/CallbackGame.java | 25 ++---- .../meta/api/objects/games/Game.java | 48 ++--------- .../meta/api/objects/games/GameHighScore.java | 29 ++----- .../inlinequery/ChosenInlineQuery.java | 44 ++-------- .../api/objects/inlinequery/InlineQuery.java | 52 ++--------- .../InputContactMessageContent.java | 64 +++----------- .../InputLocationMessageContent.java | 66 +++----------- .../InputTextMessageContent.java | 80 +++-------------- .../InputVenueMessageContent.java | 86 +++---------------- 14 files changed, 107 insertions(+), 508 deletions(-) diff --git a/pom.xml b/pom.xml index 4704c1e6..68db8f58 100644 --- a/pom.xml +++ b/pom.xml @@ -74,10 +74,17 @@ 2.10.1 1.7.29 1.3.5 + 1.18.16 + + org.projectlombok + lombok + ${lombok.version} + provided + org.junit.jupiter junit-jupiter-api diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index 46ed343d..24c60519 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -114,6 +114,11 @@ json ${json.version} + + org.projectlombok + lombok + provided + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java index 620f7bf2..6d4cc32f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java @@ -3,6 +3,7 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; import java.io.Serializable; @@ -14,6 +15,7 @@ import java.io.Serializable; */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) +@Data public abstract class BotApiMethod extends PartialBotApiMethod { protected static final String METHOD_FIELD = "method"; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java index 63fb2419..e3b4dfbb 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java @@ -1,17 +1,24 @@ package org.telegram.telegrambots.meta.api.objects.commands; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.7 * This object represents a bot command. */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder public class BotCommand implements BotApiObject, Validable { private static final String COMMAND_FIELD = "command"; private static final String DESCRIPTION_FIELD = "description"; @@ -20,37 +27,12 @@ public class BotCommand implements BotApiObject, Validable { * Text of the command. Can contain only lowercase English letters, digits and underscores. 1-32 characters. */ @JsonProperty(COMMAND_FIELD) + @NonNull private String command; ///< Value of the dice, 1-6 @JsonProperty(DESCRIPTION_FIELD) + @NonNull private String description; ///< Description of the command, 3-256 characters. - public BotCommand() { - super(); - } - - public BotCommand(String command, String description) { - this.command = checkNotNull(command); - this.description = checkNotNull(description); - } - - public String getCommand() { - return command; - } - - public BotCommand setCommand(String command) { - this.command = command; - return this; - } - - public String getDescription() { - return description; - } - - public BotCommand setDescription(String description) { - this.description = description; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (command == null || command.isEmpty()) { @@ -60,12 +42,4 @@ public class BotCommand implements BotApiObject, Validable { throw new TelegramApiValidationException("Description parameter can't be empty", this); } } - - @Override - public String toString() { - return "BotCommand{" + - "command='" + command + '\'' + - ", description='" + description + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java index 75d2d76e..d1279e21 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java @@ -17,6 +17,8 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -25,6 +27,8 @@ import org.telegram.telegrambots.meta.api.objects.PhotoSize; * @version 2.4 * This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). */ +@Data +@NoArgsConstructor public class Animation implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -58,59 +62,4 @@ public class Animation implements BotApiObject { private String mimetype; ///< Optional. MIME type of the file as defined by sender @JsonProperty(FILESIZE_FIELD) private Integer fileSize; ///< Optional. File size - - public Animation() { - super(); - } - - public String getFileId() { - return fileId; - } - - public PhotoSize getThumb() { - return thumb; - } - - public String getFileName() { - return fileName; - } - - public String getMimetype() { - return mimetype; - } - - public Integer getFileSize() { - return fileSize; - } - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - public Integer getDuration() { - return duration; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Animation{" + - "fileId='" + fileId + '\'' + - ", width=" + width + - ", height=" + height + - ", duration=" + duration + - ", thumb=" + thumb + - ", fileName='" + fileName + '\'' + - ", mimetype='" + mimetype + '\'' + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java index 6528163b..0aec927c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java @@ -17,31 +17,16 @@ package org.telegram.telegrambots.meta.api.objects.games; +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** * @author Ruben Bermudez * @version 2.4 - * @brief A placeholder, currently holds no information. Use BotFather to set up your game. - * @date 16 of September of 2016 + * A placeholder, currently holds no information. Use BotFather to set up your game. */ +@Data +@NoArgsConstructor public class CallbackGame implements BotApiObject { - public CallbackGame() { - super(); - } - - @Override - public String toString() { - return "CallbackGame{}"; - } - - @Override - public boolean equals(Object o) { - return o == this || o instanceof CallbackGame; - } - - @Override - public int hashCode() { - return getClass().hashCode(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java index 7e84b3ef..2be56adb 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java @@ -17,7 +17,8 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; - +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -27,10 +28,11 @@ import java.util.List; /** * @author Ruben Bermudez * @version 2.4 - * @brief This object represents a game. - * Use BotFather to create and edit games, their short names will act as unique identifiers. - * @date 27 of September of 2016 + * This object represents a game. + * @apiNote Use BotFather to create and edit games, their short names will act as unique identifiers. */ +@Data +@NoArgsConstructor public class Game implements BotApiObject { private static final String TITLE_FIELD = "title"; @@ -63,45 +65,7 @@ public class Game implements BotApiObject { @JsonProperty(ANIMATION_FIELD) private Animation animation; ///< Optional. Animation - public Game() { - super(); - } - - public String getTitle() { - return title; - } - - public String getDescription() { - return description; - } - - public List getPhoto() { - return photo; - } - - public Animation getAnimation() { - return animation; - } - - public String getText() { - return text; - } - public boolean hasEntities() { return entities != null && !entities.isEmpty(); } - - public List getEntities() { - return entities; - } - - @Override - public String toString() { - return "Game{" + - "title='" + title + '\'' + - ", description='" + description + '\'' + - ", photo=" + photo + - ", animation=" + animation + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java index c9a7f43a..379fd281 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java @@ -18,16 +18,18 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; - +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.User; /** * @author Ruben Bermudez * @version 1.0 - * @brief This object represents one row of a game high scores table - * @date 25 of September of 2016 + * This object represents one row of a game high scores table */ +@Data +@NoArgsConstructor public class GameHighScore implements BotApiObject { private static final String POSITION_FIELD = "position"; private static final String USER_FIELD = "user"; @@ -39,25 +41,4 @@ public class GameHighScore implements BotApiObject { private User user; ///< User @JsonProperty(SCORE_FIELD) private Integer score; ///< Score - - public Integer getPosition() { - return position; - } - - public User getUser() { - return user; - } - - public Integer getScore() { - return score; - } - - @Override - public String toString() { - return "GameHighScore{" + - "position=" + position + - ", user=" + user + - ", score=" + score + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java index f0e4de82..bd1114eb 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java @@ -2,6 +2,9 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -9,10 +12,12 @@ import org.telegram.telegrambots.meta.api.objects.User; /** * @author Ruben Bermudez * @version 1.0 - * @brief Represents a result of an inline query that was chosen by the user and sent to their chat + * Represents a result of an inline query that was chosen by the user and sent to their chat * partner. - * @date 01 of January of 2016 */ +@Data +@NoArgsConstructor +@Builder public class ChosenInlineQuery implements BotApiObject { private static final String RESULTID_FIELD = "result_id"; private static final String FROM_FIELD = "from"; @@ -36,39 +41,4 @@ public class ChosenInlineQuery implements BotApiObject { private String inlineMessageId; @JsonProperty(QUERY_FIELD) private String query; ///< The query that was used to obtain the result. - - public ChosenInlineQuery() { - super(); - } - - public String getResultId() { - return resultId; - } - - public User getFrom() { - return from; - } - - public Location getLocation() { - return location; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public String getQuery() { - return query; - } - - @Override - public String toString() { - return "ChosenInlineQuery{" + - "resultId='" + resultId + '\'' + - ", from=" + from + - ", location=" + location + - ", inlineMessageId=" + inlineMessageId + - ", query='" + query + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java index 99d31257..b41039a4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java @@ -2,6 +2,9 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -9,10 +12,12 @@ import org.telegram.telegrambots.meta.api.objects.User; /** * @author Ruben Bermudez * @version 1.0 - * @brief This object represents an incoming inline query. When the user sends an empty query, your + * This object represents an incoming inline query. When the user sends an empty query, your * bot could return some default or trending results. - * @date 01 of January of 2016 */ +@Data +@NoArgsConstructor +@Builder public class InlineQuery implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FROM_FIELD = "from"; @@ -30,48 +35,5 @@ public class InlineQuery implements BotApiObject { private String query; ///< Text of the query @JsonProperty(OFFSET_FIELD) private String offset; ///< Offset of the results to be returned, can be controlled by the bot - - public InlineQuery() { - super(); - } - - public String getId() { - return id; - } - - public User getFrom() { - return from; - } - - public Location getLocation() { - return location; - } - - public String getQuery() { - return query; - } - - public String getOffset() { - return offset; - } - - public boolean hasQuery() { - return query != null && !query.isEmpty(); - } - - public boolean hasLocation() { - return location != null; - } - - @Override - public String toString() { - return "InlineQuery{" + - "id='" + id + '\'' + - ", from=" + from + - ", location=" + location + - ", query='" + query + '\'' + - ", offset='" + offset + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java index e40965f9..28309713 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java @@ -1,18 +1,26 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** * @author Ruben Bermudez * @version 1.0 * Represents the content of a contact message to be sent as the result of an inline query - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InputContactMessageContent implements InputMessageContent { private static final String PHONE_NUMBER_FIELD = "phone_number"; @@ -21,54 +29,16 @@ public class InputContactMessageContent implements InputMessageContent { private static final String VCARD_FIELD = "vcard"; @JsonProperty(PHONE_NUMBER_FIELD) + @NonNull private String phoneNumber; ///< Contact's phone number @JsonProperty(FIRST_NAME_FIELD) + @NonNull private String firstName; ///< Contact's first name @JsonProperty(LAST_NAME_FIELD) private String lastName; ///< Optional. Contact's last name @JsonProperty(VCARD_FIELD) private String vCard; ///< Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes - public InputContactMessageContent() { - super(); - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public InputContactMessageContent setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public String getFirstName() { - return firstName; - } - - public InputContactMessageContent setFirstName(String firstName) { - this.firstName = firstName; - return this; - } - - public String getLastName() { - return lastName; - } - - public InputContactMessageContent setLastName(String lastName) { - this.lastName = lastName; - return this; - } - - public String getVCard() { - return vCard; - } - - public InputContactMessageContent setVCard(String vCard) { - this.vCard = vCard; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (phoneNumber == null || phoneNumber.isEmpty()) { @@ -78,14 +48,4 @@ public class InputContactMessageContent implements InputMessageContent { throw new TelegramApiValidationException("FirstName parameter can't be empty", this); } } - - @Override - public String toString() { - return "InputContactMessageContent{" + - "phoneNumber='" + phoneNumber + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", vCard='" + vCard + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java index 55b59866..a60d3949 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java @@ -1,22 +1,26 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * Represents the content of a location message to be sent as the result of an inline query. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InputLocationMessageContent implements InputMessageContent { private static final String LATITUDE_FIELD = "latitude"; @@ -24,51 +28,14 @@ public class InputLocationMessageContent implements InputMessageContent { private static final String LIVEPERIOD_FIELD = "live_period"; @JsonProperty(LATITUDE_FIELD) + @NonNull private Float latitude; ///< Latitude of the location in degrees @JsonProperty(LONGITUDE_FIELD) + @NonNull private Float longitude; ///< Longitude of the location in degrees @JsonProperty(LIVEPERIOD_FIELD) private Integer livePeriod; ///< Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. - public InputLocationMessageContent() { - super(); - } - - public InputLocationMessageContent(Float latitude, Float longitude) { - super(); - this.latitude = checkNotNull(latitude); - this.longitude = checkNotNull(longitude); - } - - public Float getLongitude() { - return longitude; - } - - public InputLocationMessageContent setLongitude(Float longitude) { - Objects.requireNonNull(longitude); - this.longitude = longitude; - return this; - } - - public Float getLatitude() { - return latitude; - } - - public InputLocationMessageContent setLatitude(Float latitude) { - Objects.requireNonNull(latitude); - this.latitude = latitude; - return this; - } - - public Integer getLivePeriod() { - return livePeriod; - } - - public InputLocationMessageContent setLivePeriod(Integer livePeriod) { - this.livePeriod = livePeriod; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (latitude == null) { @@ -81,13 +48,4 @@ public class InputLocationMessageContent implements InputMessageContent { throw new TelegramApiValidationException("Live period parameter must be between 60 and 86400", this); } } - - @Override - public String toString() { - return "InputLocationMessageContent{" + - "latitude=" + latitude + - ", longitude=" + longitude + - ", livePeriod=" + livePeriod + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java index 70268150..0f529854 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java @@ -1,9 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.telegram.telegrambots.meta.api.methods.ParseMode; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** @@ -12,6 +15,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * Represents the content of a text message to be sent as the result of an inline query. */ @JsonDeserialize +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InputTextMessageContent implements InputMessageContent { private static final String MESSAGETEXT_FIELD = "message_text"; @@ -19,84 +26,17 @@ public class InputTextMessageContent implements InputMessageContent { private static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; @JsonProperty(MESSAGETEXT_FIELD) + @NonNull private String messageText; ///< Text of a message to be sent, 1-4096 characters @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message - public InputTextMessageContent() { - super(); - } - - public String getMessageText() { - return messageText; - } - - public InputTextMessageContent setMessageText(String messageText) { - this.messageText = messageText; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InputTextMessageContent setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public Boolean getDisableWebPagePreview() { - return disableWebPagePreview; - } - - public InputTextMessageContent setDisableWebPagePreview(Boolean disableWebPagePreview) { - this.disableWebPagePreview = disableWebPagePreview; - return this; - } - - public InputTextMessageContent enableMarkdown(boolean enable) { - if (enable) { - this.parseMode = ParseMode.MARKDOWN; - } else { - this.parseMode = null; - } - return this; - } - - public InputTextMessageContent enableHtml(boolean enable) { - if (enable) { - this.parseMode = ParseMode.HTML; - } else { - this.parseMode = null; - } - return this; - } - - public InputTextMessageContent disableWebPagePreview() { - disableWebPagePreview = true; - return this; - } - - public InputTextMessageContent enableWebPagePreview() { - disableWebPagePreview = null; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (messageText == null || messageText.isEmpty()) { throw new TelegramApiValidationException("MessageText parameter can't be empty", this); } } - - @Override - public String toString() { - return "InputTextMessageContent{" + - ", messageText='" + messageText + '\'' + - ", parseMode='" + parseMode + '\'' + - ", disableWebPagePreview=" + disableWebPagePreview + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java index fe8ef9e0..68b0f945 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java @@ -3,16 +3,25 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessageconte import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** * @author Ruben Bermudez * @version 1.0 * Represents the content of a venue message to be sent as the result of an inline query. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InputVenueMessageContent implements InputMessageContent { private static final String LATITUDE_FIELD = "latitude"; @@ -23,77 +32,22 @@ public class InputVenueMessageContent implements InputMessageContent { private static final String FOURSQUARETYPE_FIELD = "foursquare_type"; @JsonProperty(LATITUDE_FIELD) + @NonNull private Float latitude; ///< Latitude of the venue in degrees @JsonProperty(LONGITUDE_FIELD) + @NonNull private Float longitude; ///< Longitude of the venue in degrees @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Name of the venue @JsonProperty(ADDRESS_FIELD) + @NonNull private String address; ///< Address of the venue @JsonProperty(FOURSQUAREID_FIELD) private String foursquareId; ///< Optional. Foursquare identifier of the venue, if known @JsonProperty(FOURSQUARETYPE_FIELD) private String foursquareType; ///< Optional. Foursquare type of the venue, if known. - - public InputVenueMessageContent() { - super(); - } - - public Float getLatitude() { - return latitude; - } - - public InputVenueMessageContent setLatitude(Float latitude) { - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public InputVenueMessageContent setLongitude(Float longitude) { - this.longitude = longitude; - return this; - } - - public String getTitle() { - return title; - } - - public InputVenueMessageContent setTitle(String title) { - this.title = title; - return this; - } - - public String getAddress() { - return address; - } - - public InputVenueMessageContent setAddress(String address) { - this.address = address; - return this; - } - - public String getFoursquareId() { - return foursquareId; - } - - public InputVenueMessageContent setFoursquareId(String foursquareId) { - this.foursquareId = foursquareId; - return this; - } - - public String getFoursquareType() { - return foursquareType; - } - - public InputVenueMessageContent setFoursquareType(String foursquareType) { - this.foursquareType = foursquareType; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (latitude == null) { @@ -109,16 +63,4 @@ public class InputVenueMessageContent implements InputMessageContent { throw new TelegramApiValidationException("Address parameter can't be empty", this); } } - - @Override - public String toString() { - return "InputVenueMessageContent{" + - "latitude=" + latitude + - ", longitude=" + longitude + - ", title='" + title + '\'' + - ", address='" + address + '\'' + - ", foursquareId='" + foursquareId + '\'' + - ", foursquareType='" + foursquareType + '\'' + - '}'; - } } From bea0b95fc7e3c7d1312998bc3af8d3660e3f81d4 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sat, 31 Oct 2020 16:50:18 +0000 Subject: [PATCH 29/45] Update Location fields to Double to avoid roundings --- .../meta/api/objects/Location.java | 33 +++++-------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java index c9f30fb9..d21a07c3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java @@ -2,41 +2,26 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** * @author Ruben Bermudez * @version 1.0 - * @brief This object represents a point on the map. - * @date 20 of June of 2015 + * This object represents a point on the map. */ +@Data +@NoArgsConstructor +@AllArgsConstructor public class Location implements BotApiObject { private static final String LONGITUDE_FIELD = "longitude"; private static final String LATITUDE_FIELD = "latitude"; @JsonProperty(LONGITUDE_FIELD) - private Float longitude; ///< Longitude as defined by sender + private Double longitude; ///< Longitude as defined by sender @JsonProperty(LATITUDE_FIELD) - private Float latitude; ///< Latitude as defined by sender - - public Location() { - super(); - } - - public Float getLongitude() { - return longitude; - } - - public Float getLatitude() { - return latitude; - } - - @Override - public String toString() { - return "Location{" + - "longitude=" + longitude + - ", latitude=" + latitude + - '}'; - } + private Double latitude; ///< Latitude as defined by sender } From 3275c10913a2e14d6ee67414c5d7c74eeddd0f04 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sat, 31 Oct 2020 17:43:32 +0000 Subject: [PATCH 30/45] More cleanup --- pom.xml | 2 +- .../abilitybots/api/util/AbilityUtils.java | 6 +- .../api/bot/AbilityBotI18nTest.java | 4 +- .../abilitybots/api/bot/AbilityBotTest.java | 3 +- .../api/bot/ContinuousTextTest.java | 2 +- .../abilitybots/api/bot/TestUtils.java | 4 +- .../commands/CommandRegistryTest.java | 9 - telegrambots-meta/pom.xml | 5 +- .../meta/api/methods/BotApiMethod.java | 2 - .../telegrambots/meta/api/objects/Chat.java | 93 +----- .../meta/api/objects/Location.java | 6 +- .../meta/api/objects/Message.java | 293 +++--------------- .../telegrambots/meta/api/objects/User.java | 100 +----- .../meta/api/objects/games/Animation.java | 10 + .../meta/api/objects/games/Game.java | 8 + .../meta/api/objects/games/GameHighScore.java | 6 + .../inlinequery/ChosenInlineQuery.java | 8 + .../api/objects/inlinequery/InlineQuery.java | 9 + .../InputContactMessageContent.java | 2 + .../InputLocationMessageContent.java | 2 + .../InputTextMessageContent.java | 2 + .../InputVenueMessageContent.java | 2 + .../result/InlineQueryResultPhoto.java | 148 +-------- .../meta/test/TestDeserialization.java | 5 +- .../test/BotApiMethodHelperFactory.java | 103 +++--- .../telegrambots/test/TestRestApi.java | 88 ++++-- 26 files changed, 273 insertions(+), 649 deletions(-) diff --git a/pom.xml b/pom.xml index 68db8f58..7899d19a 100644 --- a/pom.xml +++ b/pom.xml @@ -67,7 +67,7 @@ ${java.version} ${java.version} - 5.5.2 + 5.6.2 3.1.0 3.1.0 2.10.1 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 b38f5ab0..02db0f9a 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(0, "", false); private AbilityUtils() { @@ -37,7 +37,7 @@ public final class AbilityUtils { */ public static String stripTag(String username) { String lowerCase = username.toLowerCase(); - return lowerCase.startsWith("@") ? lowerCase.substring(1, lowerCase.length()) : lowerCase; + return lowerCase.startsWith("@") ? lowerCase.substring(1) : lowerCase; } /** @@ -252,7 +252,7 @@ public final class AbilityUtils { * The full name is identified as the concatenation of the first and last name, separated by a space. * This method can return an empty name if both first and last name are empty. * - * @param user + * @param user User to use * @return the full name of the user */ public static String fullName(User user) { 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 5b320898..ada4147f 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); - private static final User ITALIAN_USER = new User(2, "first", false, "last", "username", "it-IT"); + 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 DBContext db; private NoPublicCommandsBot bot; 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 2e407cc3..c69daef3 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 @@ -351,7 +351,7 @@ public class AbilityBotTest { String newFirstName = USER.getFirstName() + "-test"; String newLastName = USER.getLastName() + "-test"; int sameId = USER.getId(); - User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, null); + User changedUser = new User(sameId, newFirstName, false, newLastName, newUsername, "en", false, false, false); mockAlternateUser(update, message, changedUser); @@ -515,6 +515,7 @@ public class AbilityBotTest { assertTrue(bot.checkGlobalFlags(update), "Unexpected result when checking for the default global flags"); } + @SuppressWarnings({"NumericOverflow", "divzero"}) @Test void canConsumeUpdate() { Ability ability = getDefaultBuilder() 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 a2e5b18f..2604a2ba 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, "last", "username", null); + private static final User USER = new User(1, "first", false); private DBContext db; 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 bf1c3479..5e85b66b 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); - public static final User CREATOR = new User(1337, "creatorFirst", false, "creatorLast", "creatorUsername", null); + 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); private TestUtils() { diff --git a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java index 9b847418..232ea85b 100644 --- a/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java +++ b/telegrambots-extensions/src/test/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistryTest.java @@ -8,15 +8,6 @@ import org.telegram.telegrambots.meta.bots.AbsSender; class CommandRegistryTest { - @Test - void should_create_registry() { - CommandRegistry registry = new CommandRegistry(true, () -> "BotUsername"); - Assertions.assertNotNull(registry, "CommandRegistry is not created"); - NullPointerException exception = Assertions.assertThrows(NullPointerException.class, - () -> new CommandRegistry(true, () -> "BotUsername")); - Assertions.assertEquals("Bot username must not be null", exception.getMessage(), "Invalid exception message"); - } - @Test void should_executes_commandWithBotUsername() { CommandRegistry registry = new CommandRegistry(true, () -> "BotUsername"); diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index 24c60519..7d3ffc4e 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -69,11 +69,11 @@ UTF-8 UTF-8 - 4.2.2 + 4.2.3 2.10.1 2.10.1 20180813 - 28.1-jre + 30.0-jre @@ -119,6 +119,7 @@ lombok provided + diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java index 6d4cc32f..620f7bf2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/BotApiMethod.java @@ -3,7 +3,6 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; import java.io.Serializable; @@ -15,7 +14,6 @@ import java.io.Serializable; */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) -@Data public abstract class BotApiMethod extends PartialBotApiMethod { protected static final String METHOD_FIELD = "method"; 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 266c5692..a02a06bc 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 @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** @@ -9,6 +15,10 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * This object represents a Telegram chat with an user or a group */ @SuppressWarnings("WeakerAccess") +@Data +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor public class Chat implements BotApiObject { private static final String ID_FIELD = "id"; @@ -39,8 +49,10 @@ public class Chat implements BotApiObject { * so a signed 64 bit integer or double-precision float type are safe for storing this identifier. */ @JsonProperty(ID_FIELD) + @NonNull private Long id; ///< Unique identifier for this chat, not exceeding 1e13 by absolute value @JsonProperty(TYPE_FIELD) + @NonNull private String type; ///< Type of the chat, one of “private”, “group” or “channel” @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title of the chat, only for channels and group chat @@ -83,96 +95,23 @@ public class Chat implements BotApiObject { @JsonProperty(SLOWMODEDELAY_FIELD) private Integer slowModeDelay; - public Chat() { - super(); - } - - public Long getId() { - return id; - } - + @JsonIgnore public Boolean isGroupChat() { return GROUPCHATTYPE.equals(type); } + @JsonIgnore public Boolean isChannelChat() { return CHANNELCHATTYPE.equals(type); } + @JsonIgnore public Boolean isUserChat() { return USERCHATTYPE.equals(type); } + @JsonIgnore public Boolean isSuperGroupChat() { return SUPERGROUPCHATTYPE.equals(type); } - - public String getTitle() { - return title; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public String getUserName() { - return userName; - } - - public ChatPermissions getPermissions() { - return permissions; - } - - public ChatPhoto getPhoto() { - return photo; - } - - public String getDescription() { - return description; - } - - public String getInviteLink() { - return inviteLink; - } - - public Message getPinnedMessage() { - return pinnedMessage; - } - - public String getStickerSetName() { - return stickerSetName; - } - - public Boolean getCanSetStickerSet() { - return canSetStickerSet; - } - - public Integer getSlowModeDelay() { - return slowModeDelay; - } - - @Override - public String toString() { - return "Chat{" + - "id=" + id + - ", type='" + type + '\'' + - ", title='" + title + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", userName='" + userName + '\'' + - ", allMembersAreAdministrators=" + allMembersAreAdministrators + - ", photo=" + photo + - ", description='" + description + '\'' + - ", inviteLink='" + inviteLink + '\'' + - ", pinnedMessage=" + pinnedMessage + - ", stickerSetName='" + stickerSetName + '\'' + - ", canSetStickerSet=" + canSetStickerSet + - ", permissions=" + permissions + - ", slowModeDelay=" + slowModeDelay + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java index d21a07c3..6dac47db 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java @@ -1,10 +1,10 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** @@ -13,15 +13,17 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * This object represents a point on the map. */ @Data -@NoArgsConstructor @AllArgsConstructor +@NoArgsConstructor public class Location implements BotApiObject { private static final String LONGITUDE_FIELD = "longitude"; private static final String LATITUDE_FIELD = "latitude"; @JsonProperty(LONGITUDE_FIELD) + @NonNull private Double longitude; ///< Longitude as defined by sender @JsonProperty(LATITUDE_FIELD) + @NonNull private Double latitude; ///< Latitude as defined by sender } 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 b0723615..8db7b7cb 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 @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.games.Animation; import org.telegram.telegrambots.meta.api.objects.games.Game; @@ -19,6 +25,10 @@ import java.util.List; * @version 1.0 * This object represents a message. */ +@Data +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor public class Message implements BotApiObject { private static final String MESSAGEID_FIELD = "message_id"; private static final String FROM_FIELD = "from"; @@ -71,12 +81,15 @@ public class Message implements BotApiObject { private static final String VIABOT_FIELD = "via_bot"; @JsonProperty(MESSAGEID_FIELD) + @NonNull private Integer messageId; ///< Integer Unique message identifier @JsonProperty(FROM_FIELD) private User from; ///< Optional. Sender, can be empty for messages sent to channels @JsonProperty(DATE_FIELD) - private Integer date; ///< Optional. Date the message was sent in Unix time + @NonNull + private Integer date; ///< ODate the message was sent in Unix time @JsonProperty(CHAT_FIELD) + @NonNull private Chat chat; ///< Conversation the message belongs to @JsonProperty(FORWARDFROM_FIELD) private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message @@ -213,37 +226,6 @@ public class Message implements BotApiObject { private Dice dice; // Optional. Message is a dice with random value from 1 to 6 @JsonProperty(VIABOT_FIELD) private User viaBot; // Optional. Bot through which the message was sent - public Message() { - super(); - } - - public Integer getMessageId() { - return messageId; - } - - public User getFrom() { - return from; - } - - public Integer getDate() { - return date; - } - - public Chat getChat() { - return chat; - } - - public User getForwardFrom() { - return forwardFrom; - } - - public Integer getForwardDate() { - return forwardDate; - } - - public String getText() { - return text; - } public List getEntities() { if (entities != null) { @@ -259,130 +241,47 @@ public class Message implements BotApiObject { return captionEntities; } - public Audio getAudio() { - return audio; - } - - public Document getDocument() { - return document; - } - - public List getPhoto() { - return photo; - } - - public Sticker getSticker() { - return sticker; - } - - public boolean hasSticker() { - return sticker != null; - } - - public Video getVideo() { - return video; - } - - public Animation getAnimation() { - return animation; - } - - public Contact getContact() { - return contact; - } - - public Location getLocation() { - return location; - } - - public Venue getVenue() { - return venue; - } - - public Message getPinnedMessage() { - return pinnedMessage; - } - + @JsonIgnore public List getNewChatMembers() { return newChatMembers == null ? new ArrayList<>() : newChatMembers; } - public User getLeftChatMember() { - return leftChatMember; - } - - public String getNewChatTitle() { - return newChatTitle; - } - - public List getNewChatPhoto() { - return newChatPhoto; - } - - public Boolean getDeleteChatPhoto() { - return deleteChatPhoto; - } - - public Boolean getGroupchatCreated() { - return groupchatCreated; - } - - public Message getReplyToMessage() { - return replyToMessage; - } - - public Voice getVoice() { - return voice; - } - - public String getCaption() { - return caption; - } - - public Boolean getSuperGroupCreated() { - return superGroupCreated; - } - - public Boolean getChannelChatCreated() { - return channelChatCreated; - } - - public Long getMigrateToChatId() { - return migrateToChatId; - } - - public Long getMigrateFromChatId() { - return migrateFromChatId; - } - - public Integer getForwardFromMessageId() { - return forwardFromMessageId; + @JsonIgnore + public boolean hasSticker() { + return sticker != null; } + @JsonIgnore public boolean isGroupMessage() { return chat.isGroupChat(); } + @JsonIgnore public boolean isUserMessage() { return chat.isUserChat(); } + @JsonIgnore public boolean isChannelMessage() { return chat.isChannelChat(); } + @JsonIgnore public boolean isSuperGroupMessage() { return chat.isSuperGroupChat(); } + @JsonIgnore public Long getChatId() { return chat.getId(); } + @JsonIgnore public boolean hasText() { return text != null && !text.isEmpty(); } + @JsonIgnore public boolean isCommand() { if (hasText() && entities != null) { for (MessageEntity entity : entities) { @@ -395,202 +294,98 @@ public class Message implements BotApiObject { return false; } + @JsonIgnore public boolean hasDocument() { return this.document != null; } + @JsonIgnore public boolean hasVideo() { return this.video != null; } + @JsonIgnore public boolean hasAudio(){ return this.audio != null; } + @JsonIgnore public boolean hasVoice(){ return this.voice != null; } + @JsonIgnore public boolean isReply() { return this.replyToMessage != null; } + @JsonIgnore public boolean hasLocation() { return location != null; } - public Chat getForwardFromChat() { - return forwardFromChat; - } - - public Integer getEditDate() { - return editDate; - } - - public Game getGame() { - return game; - } - + @JsonIgnore private boolean hasGame() { return game != null; } + @JsonIgnore public boolean hasEntities() { return entities != null && !entities.isEmpty(); } + @JsonIgnore public boolean hasPhoto() { return photo != null && !photo.isEmpty(); } + @JsonIgnore public boolean hasInvoice() { return invoice != null; } + @JsonIgnore public boolean hasSuccessfulPayment() { return successfulPayment != null; } + @JsonIgnore public boolean hasContact() { return contact != null; } - public Invoice getInvoice() { - return invoice; - } - - public SuccessfulPayment getSuccessfulPayment() { - return successfulPayment; - } - - public VideoNote getVideoNote() { - return videoNote; - } - + @JsonIgnore public boolean hasVideoNote() { return videoNote != null; } - public String getAuthorSignature() { - return authorSignature; - } - - public String getForwardSignature() { - return forwardSignature; - } - - public String getMediaGroupId() { - return mediaGroupId; - } - - public String getConnectedWebsite() { - return connectedWebsite; - } - - public PassportData getPassportData() { - return passportData; - } - + @JsonIgnore public boolean hasPassportData() { return passportData != null; } + @JsonIgnore public boolean hasAnimation() { return animation != null; } - public String getForwardSenderName() { - return forwardSenderName; - } - - public void setForwardSenderName(String forwardSenderName) { - this.forwardSenderName = forwardSenderName; - } - + @JsonIgnore public boolean hasPoll() { return poll != null; } - public Poll getPoll() { - return poll; - } - - public Dice getDice() { - return dice; - } - + @JsonIgnore public boolean hasDice() { return dice != null; } - public User getViaBot() { - return viaBot; - } - + @JsonIgnore public boolean hasViaBot() { return viaBot != null; } + @JsonIgnore public boolean hasReplyMarkup() { return replyMarkup != null; } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - @Override - public String toString() { - return "Message{" + - "messageId=" + messageId + - ", from=" + from + - ", date=" + date + - ", chat=" + chat + - ", forwardFrom=" + forwardFrom + - ", forwardFromChat=" + forwardFromChat + - ", forwardDate=" + forwardDate + - ", text='" + text + '\'' + - ", entities=" + entities + - ", captionEntities=" + captionEntities + - ", audio=" + audio + - ", document=" + document + - ", photo=" + photo + - ", sticker=" + sticker + - ", video=" + video + - ", contact=" + contact + - ", location=" + location + - ", venue=" + venue + - ", animation=" + animation + - ", pinnedMessage=" + pinnedMessage + - ", newChatMembers=" + newChatMembers + - ", leftChatMember=" + leftChatMember + - ", newChatTitle='" + newChatTitle + '\'' + - ", newChatPhoto=" + newChatPhoto + - ", deleteChatPhoto=" + deleteChatPhoto + - ", groupchatCreated=" + groupchatCreated + - ", replyToMessage=" + replyToMessage + - ", voice=" + voice + - ", caption='" + caption + '\'' + - ", superGroupCreated=" + superGroupCreated + - ", channelChatCreated=" + channelChatCreated + - ", migrateToChatId=" + migrateToChatId + - ", migrateFromChatId=" + migrateFromChatId + - ", editDate=" + editDate + - ", game=" + game + - ", forwardFromMessageId=" + forwardFromMessageId + - ", invoice=" + invoice + - ", successfulPayment=" + successfulPayment + - ", videoNote=" + videoNote + - ", authorSignature='" + authorSignature + '\'' + - ", forwardSignature='" + forwardSignature + '\'' + - ", mediaGroupId='" + mediaGroupId + '\'' + - ", connectedWebsite='" + connectedWebsite + '\'' + - ", passportData=" + passportData + - ", forwardSenderName='" + forwardSenderName + '\'' + - ", poll=" + poll + - ", replyMarkup=" + replyMarkup + - ", dice=" + dice + - ", viaBot=" + viaBot + - '}'; - } } 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 8bc2582c..32501eae 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 @@ -1,15 +1,22 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; -import java.util.Objects; - /** * @author Ruben Bermudez * @version 3.0 * This object represents a Telegram user or bot. */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@RequiredArgsConstructor public class User implements BotApiObject { private static final String ID_FIELD = "id"; @@ -23,10 +30,13 @@ public class User implements BotApiObject { private static final String SUPPORTINLINEQUERIES_FIELD = "supports_inline_queries"; @JsonProperty(ID_FIELD) + @NonNull private Integer id; ///< Unique identifier for this user or bot @JsonProperty(FIRSTNAME_FIELD) + @NonNull private String firstName; ///< User‘s or bot’s first name @JsonProperty(ISBOT_FIELD) + @NonNull private Boolean isBot; ///< True, if this user is a bot @JsonProperty(LASTNAME_FIELD) private String lastName; ///< Optional. User‘s or bot’s last name @@ -40,90 +50,4 @@ public class User implements BotApiObject { private Boolean canReadAllGroupMessages; ///< Optional. True, if privacy mode is disabled for the bot. Returned only in getMe. @JsonProperty(SUPPORTINLINEQUERIES_FIELD) private Boolean supportInlineQueries; ///< Optional. True, if the bot supports inline queries. Returned only in getMe. - - public User() { - super(); - } - - public User(Integer id, String firstName, Boolean isBot, String lastName, String userName, String languageCode) { - this.id = id; - this.firstName = firstName; - this.isBot = isBot; - this.lastName = lastName; - this.userName = userName; - this.languageCode = languageCode; - } - - public Integer getId() { - return id; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public String getUserName() { - return userName; - } - - public String getLanguageCode() { - return languageCode; - } - - public Boolean getBot() { - return isBot; - } - - public Boolean getCanJoinGroups() { - return canJoinGroups; - } - - public Boolean getCanReadAllGroupMessages() { - return canReadAllGroupMessages; - } - - public Boolean getSupportInlineQueries() { - return supportInlineQueries; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(firstName, user.firstName) && - Objects.equals(isBot, user.isBot) && - Objects.equals(lastName, user.lastName) && - Objects.equals(userName, user.userName) && - Objects.equals(languageCode, user.languageCode) && - Objects.equals(canJoinGroups, user.canJoinGroups) && - Objects.equals(canReadAllGroupMessages, user.canReadAllGroupMessages) && - Objects.equals(supportInlineQueries, user.supportInlineQueries); - } - - @Override - public int hashCode() { - return Objects.hash(id, firstName, isBot, lastName, userName, languageCode, - canJoinGroups, canReadAllGroupMessages, supportInlineQueries); - } - - @Override - public String toString() { - return "User{" + - "id=" + id + - ", firstName='" + firstName + '\'' + - ", isBot=" + isBot + - ", lastName='" + lastName + '\'' + - ", userName='" + userName + '\'' + - ", languageCode='" + languageCode + '\'' + - ", canJoinGroups=" + canJoinGroups + - ", canReadAllGroupMessages=" + canReadAllGroupMessages + - ", supportInlineQueries=" + supportInlineQueries + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java index d1279e21..6fd19f03 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java @@ -17,8 +17,11 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -28,7 +31,9 @@ import org.telegram.telegrambots.meta.api.objects.PhotoSize; * This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). */ @Data +@RequiredArgsConstructor @NoArgsConstructor +@AllArgsConstructor public class Animation implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -41,18 +46,23 @@ public class Animation implements BotApiObject { private static final String FILESIZE_FIELD = "file_size"; @JsonProperty(FILEID_FIELD) + @NonNull private String fileId; ///< Identifier for this file, which can be used to download or reuse the file /** * Unique identifier for this file, which is supposed to be the same over time and for different bots. * Can't be used to download or reuse the file. */ @JsonProperty(FILEUNIQUEID_FIELD) + @NonNull private String fileUniqueId; @JsonProperty(WIDTH_FIELD) + @NonNull private Integer width; ///< Video width as defined by sender @JsonProperty(HEIGHT_FIELD) + @NonNull private Integer height; ///< Video height as defined by sender @JsonProperty(DURATION_FIELD) + @NonNull private Integer duration; ///< Duration of the video in seconds as defined by sender @JsonProperty(THUMB_FIELD) private PhotoSize thumb; ///< Optional. Animation thumbnail as defined by sender diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java index 2be56adb..8ddbfd3e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java @@ -17,8 +17,11 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -32,7 +35,9 @@ import java.util.List; * @apiNote Use BotFather to create and edit games, their short names will act as unique identifiers. */ @Data +@RequiredArgsConstructor @NoArgsConstructor +@AllArgsConstructor public class Game implements BotApiObject { private static final String TITLE_FIELD = "title"; @@ -43,10 +48,13 @@ public class Game implements BotApiObject { private static final String TEXTENTITIES_FIELD = "text_entities"; @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Title of the game @JsonProperty(DESCRIPTION_FIELD) + @NonNull private String description; ///< Description of the game @JsonProperty(PHOTO_FIELD) + @NonNull private List photo; ///< Photo /** * Optional. Brief description of the game or high scores included in the game message. diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java index 379fd281..86bf27a8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java @@ -18,8 +18,10 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.User; @@ -30,15 +32,19 @@ import org.telegram.telegrambots.meta.api.objects.User; */ @Data @NoArgsConstructor +@AllArgsConstructor public class GameHighScore implements BotApiObject { private static final String POSITION_FIELD = "position"; private static final String USER_FIELD = "user"; private static final String SCORE_FIELD = "score"; @JsonProperty(POSITION_FIELD) + @NonNull private Integer position; ///< Position in the game high score table @JsonProperty(USER_FIELD) + @NonNull private User user; ///< User @JsonProperty(SCORE_FIELD) + @NonNull private Integer score; ///< Score } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java index bd1114eb..09d11e69 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java @@ -2,9 +2,12 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -16,7 +19,9 @@ import org.telegram.telegrambots.meta.api.objects.User; * partner. */ @Data +@RequiredArgsConstructor @NoArgsConstructor +@AllArgsConstructor @Builder public class ChosenInlineQuery implements BotApiObject { private static final String RESULTID_FIELD = "result_id"; @@ -26,8 +31,10 @@ public class ChosenInlineQuery implements BotApiObject { private static final String QUERY_FIELD = "query"; @JsonProperty(RESULTID_FIELD) + @NonNull private String resultId; ///< The unique identifier for the result that was chosen. @JsonProperty(FROM_FIELD) + @NonNull private User from; ///< The user that chose the result. @JsonProperty(LOCATION_FIELD) private Location location; ///< Optional. Sender location, only for bots that require user location @@ -40,5 +47,6 @@ public class ChosenInlineQuery implements BotApiObject { @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; @JsonProperty(QUERY_FIELD) + @NonNull private String query; ///< The query that was used to obtain the result. } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java index b41039a4..4049e4f9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java @@ -2,9 +2,12 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -16,7 +19,9 @@ import org.telegram.telegrambots.meta.api.objects.User; * bot could return some default or trending results. */ @Data +@RequiredArgsConstructor @NoArgsConstructor +@AllArgsConstructor @Builder public class InlineQuery implements BotApiObject { private static final String ID_FIELD = "id"; @@ -26,14 +31,18 @@ public class InlineQuery implements BotApiObject { private static final String OFFSET_FIELD = "offset"; @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier for this query @JsonProperty(FROM_FIELD) + @NonNull private User from; ///< Sender @JsonProperty(LOCATION_FIELD) private Location location; ///< Optional. Sender location, only for bots that request user location @JsonProperty(QUERY_FIELD) + @NonNull private String query; ///< Text of the query @JsonProperty(OFFSET_FIELD) + @NonNull private String offset; ///< Offset of the results to be returned, can be controlled by the bot } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java index 28309713..2cdc30a4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java @@ -7,6 +7,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** @@ -18,6 +19,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @JsonDeserialize @Data +@RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @Builder diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java index a60d3949..66656f0c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java @@ -7,6 +7,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** @@ -18,6 +19,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @JsonDeserialize @Data +@RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @Builder diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java index 0f529854..3c86b2c7 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java @@ -7,6 +7,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** @@ -16,6 +17,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @JsonDeserialize @Data +@RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @Builder diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java index 68b0f945..58d6a312 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java @@ -8,6 +8,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; /** @@ -19,6 +20,7 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @JsonDeserialize @Data +@RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @Builder diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java index 5b3c78c4..81827796 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java @@ -3,6 +3,12 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -15,6 +21,11 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * specified content instead of the photo. */ @JsonDeserialize +@Data +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultPhoto implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -33,8 +44,10 @@ public class InlineQueryResultPhoto implements InlineQueryResult { @JsonProperty(TYPE_FIELD) private final String type = "photo"; ///< Type of the result, must be “photo” @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHOTOURL_FIELD) + @NonNull private String photoUrl; ///< A valid URL of the photo. Photo size must not exceed 5MB @JsonProperty(MIMETYPE_FIELD) private String mimeType; ///< Optional. MIME type of the photo, defaults to image/jpeg @@ -57,122 +70,6 @@ public class InlineQueryResultPhoto implements InlineQueryResult { @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - public InlineQueryResultPhoto() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultPhoto setId(String id) { - this.id = id; - return this; - } - - public String getPhotoUrl() { - return photoUrl; - } - - public InlineQueryResultPhoto setPhotoUrl(String photoUrl) { - this.photoUrl = photoUrl; - return this; - } - - public String getMimeType() { - return mimeType; - } - - public InlineQueryResultPhoto setMimeType(String mimeType) { - this.mimeType = mimeType; - return this; - } - - public Integer getPhotoWidth() { - return photoWidth; - } - - public InlineQueryResultPhoto setPhotoWidth(Integer photoWidth) { - this.photoWidth = photoWidth; - return this; - } - - public Integer getPhotoHeight() { - return photoHeight; - } - - public InlineQueryResultPhoto setPhotoHeight(Integer photoHeight) { - this.photoHeight = photoHeight; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultPhoto setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultPhoto setTitle(String title) { - this.title = title; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultPhoto setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultPhoto setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultPhoto setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultPhoto setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultPhoto setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -188,23 +85,4 @@ public class InlineQueryResultPhoto implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultPhoto{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", photoUrl='" + photoUrl + '\'' + - ", mimeType='" + mimeType + '\'' + - ", photoWidth=" + photoWidth + - ", photoHeight=" + photoHeight + - ", thumbUrl='" + thumbUrl + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } 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 02893c15..9f9a3c6f 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 @@ -2,7 +2,6 @@ package org.telegram.telegrambots.meta.test; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.telegram.telegrambots.meta.api.objects.ApiResponse; @@ -183,8 +182,8 @@ class TestDeserialization { assertEquals("offset", inlineQuery.getOffset()); assertFromUser(inlineQuery.getFrom()); assertNotNull(inlineQuery.getLocation()); - assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLatitude()); - assertEquals(Float.valueOf("0.234242534"), inlineQuery.getLocation().getLongitude()); + assertEquals(0.234242534, inlineQuery.getLocation().getLatitude()); + assertEquals(0.234242534, inlineQuery.getLocation().getLongitude()); } private void assertCallbackQuery(CallbackQuery callbackQuery) { 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 2b43acaa..9ac70c3f 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java @@ -18,11 +18,25 @@ import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMem import org.telegram.telegrambots.meta.api.methods.groupadministration.KickChatMember; import org.telegram.telegrambots.meta.api.methods.groupadministration.LeaveChat; import org.telegram.telegrambots.meta.api.methods.groupadministration.UnbanChatMember; -import org.telegram.telegrambots.meta.api.methods.send.*; +import org.telegram.telegrambots.meta.api.methods.send.SendChatAction; +import org.telegram.telegrambots.meta.api.methods.send.SendContact; +import org.telegram.telegrambots.meta.api.methods.send.SendGame; +import org.telegram.telegrambots.meta.api.methods.send.SendInvoice; +import org.telegram.telegrambots.meta.api.methods.send.SendLocation; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.send.SendVenue; import org.telegram.telegrambots.meta.api.methods.updates.GetWebhookInfo; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageCaption; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageReplyMarkup; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.Chat; +import org.telegram.telegrambots.meta.api.objects.ChatMember; +import org.telegram.telegrambots.meta.api.objects.File; +import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.api.objects.User; +import org.telegram.telegrambots.meta.api.objects.UserProfilePhotos; +import org.telegram.telegrambots.meta.api.objects.WebhookInfo; +import org.telegram.telegrambots.meta.api.objects.games.GameHighScore; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputTextMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; @@ -37,6 +51,7 @@ import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKe import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; +import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -48,7 +63,7 @@ public final class BotApiMethodHelperFactory { private BotApiMethodHelperFactory() { } - public static BotApiMethod getSendMessage() { + public static BotApiMethod getSendMessage() { return new SendMessage() .setChatId("@test") .setText("Hithere") @@ -57,14 +72,14 @@ public final class BotApiMethodHelperFactory { .setReplyMarkup(new ForceReplyKeyboard()); } - public static BotApiMethod getAnswerCallbackQuery() { + public static BotApiMethod getAnswerCallbackQuery() { return new AnswerCallbackQuery() .setCallbackQueryId("id") .setText("text") .setShowAlert(true); } - public static BotApiMethod getAnswerInlineQuery() { + public static BotApiMethod getAnswerInlineQuery() { return new AnswerInlineQuery() .setInlineQueryId("id") .setPersonal(true) @@ -75,7 +90,7 @@ public final class BotApiMethodHelperFactory { .setSwitchPmText("pmText"); } - public static BotApiMethod getEditMessageCaption() { + public static BotApiMethod getEditMessageCaption() { return new EditMessageCaption() .setChatId("ChatId") .setMessageId(1) @@ -84,7 +99,7 @@ public final class BotApiMethodHelperFactory { } - public static BotApiMethod getEditMessageText() { + public static BotApiMethod getEditMessageText() { return new EditMessageText() .setChatId("ChatId") .setMessageId(1) @@ -93,13 +108,13 @@ public final class BotApiMethodHelperFactory { .setReplyMarkup(getInlineKeyboardMarkup()); } - public static BotApiMethod getEditMessageReplyMarkup() { + public static BotApiMethod getEditMessageReplyMarkup() { return new EditMessageReplyMarkup() .setInlineMessageId("12345") .setReplyMarkup(getInlineKeyboardMarkup()); } - public static BotApiMethod getForwardMessage() { + public static BotApiMethod getForwardMessage() { return new ForwardMessage(54L, 123L, 55) .setFromChatId("From") .setChatId("To") @@ -107,72 +122,72 @@ public final class BotApiMethodHelperFactory { .disableNotification(); } - public static BotApiMethod getGetChat() { + public static BotApiMethod getGetChat() { return new GetChat() .setChatId("12345"); } - public static BotApiMethod getChatAdministrators() { + public static BotApiMethod> getChatAdministrators() { return new GetChatAdministrators() .setChatId("12345"); } - public static BotApiMethod getChatMember() { + public static BotApiMethod getChatMember() { return new GetChatMember() .setChatId("12345") .setUserId(98765); } - public static BotApiMethod getChatMembersCount() { + public static BotApiMethod getChatMembersCount() { return new GetChatMembersCount() .setChatId("12345"); } - public static BotApiMethod getGetFile() { + public static BotApiMethod getGetFile() { return new GetFile() .setFileId("FileId"); } - public static BotApiMethod getGetGameHighScores() { + public static BotApiMethod> getGetGameHighScores() { return new GetGameHighScores() .setChatId("12345") .setMessageId(67890) .setUserId(98765); } - public static BotApiMethod getGetMe() { + public static BotApiMethod getGetMe() { return new GetMe(); } - public static BotApiMethod getGetUserProfilePhotos() { + public static BotApiMethod getGetUserProfilePhotos() { return new GetUserProfilePhotos() .setUserId(98765) .setLimit(10) .setOffset(3); } - public static BotApiMethod getGetWebhookInfo() { + public static BotApiMethod getGetWebhookInfo() { return new GetWebhookInfo(); } - public static BotApiMethod getKickChatMember() { + public static BotApiMethod getKickChatMember() { return new KickChatMember() .setChatId("12345") .setUserId(98765); } - public static BotApiMethod getLeaveChat() { + public static BotApiMethod getLeaveChat() { return new LeaveChat() .setChatId("12345"); } - public static BotApiMethod getSendChatAction() { + public static BotApiMethod getSendChatAction() { return new SendChatAction() .setChatId("12345") .setAction(ActionType.RECORDVIDEO); } - public static BotApiMethod getSendContact() { + public static BotApiMethod getSendContact() { return new SendContact() .setChatId("12345") .setFirstName("First Name") @@ -213,24 +228,28 @@ public final class BotApiMethodHelperFactory { } private static InlineQueryResult getInlineQueryResultPhoto() { - return new InlineQueryResultPhoto() - .setId("1") - .setPhotoUrl("PhotoUrl") - .setPhotoWidth(10) - .setPhotoHeight(20) - .setMimeType("image/jpg") - .setThumbUrl("ThumbUrl") - .setTitle("Title") - .setDescription("Description") - .setCaption("Caption") - .setInputMessageContent(getInputMessageContent()) - .setReplyMarkup(getInlineKeyboardMarkup()); + return InlineQueryResultPhoto + .builder() + .id("1") + .photoUrl("PhotoUrl") + .photoWidth(10) + .photoHeight(20) + .mimeType("image/jpg") + .thumbUrl("ThumbUrl") + .title("Title") + .description("Description") + .caption("Caption") + .inputMessageContent(getInputMessageContent()) + .replyMarkup(getInlineKeyboardMarkup()) + .build(); } private static InputMessageContent getInputMessageContent() { - return new InputTextMessageContent() - .setMessageText("Text") - .setParseMode(ParseMode.MARKDOWN); + return InputTextMessageContent + .builder() + .messageText("Text") + .parseMode(ParseMode.MARKDOWN) + .build(); } private static InlineKeyboardMarkup getInlineKeyboardMarkup() { @@ -245,13 +264,13 @@ public final class BotApiMethodHelperFactory { .setKeyboard(keyboard); } - public static BotApiMethod getSendGame() { + public static BotApiMethod getSendGame() { return new SendGame() .setChatId("12345") .setGameShortName("MyGame"); } - public static BotApiMethod getSendLocation() { + public static BotApiMethod getSendLocation() { return new SendLocation() .setChatId("12345") .setLatitude(12.5F) @@ -259,7 +278,7 @@ public final class BotApiMethodHelperFactory { .setReplyToMessageId(53); } - public static BotApiMethod getSendVenue() { + public static BotApiMethod getSendVenue() { return new SendVenue() .setChatId("12345") .setLatitude(12.5F) @@ -270,7 +289,7 @@ public final class BotApiMethodHelperFactory { .setFoursquareId("FourId"); } - public static BotApiMethod getSetGameScore() { + public static BotApiMethod getSetGameScore() { return new SetGameScore() .setInlineMessageId("12345") .setDisableEditMessage(true) @@ -278,13 +297,13 @@ public final class BotApiMethodHelperFactory { .setUserId(98765); } - public static BotApiMethod getUnbanChatMember() { + public static BotApiMethod getUnbanChatMember() { return new UnbanChatMember() .setChatId("12345") .setUserId(98765); } - public static BotApiMethod getSendInvoice() { + public static BotApiMethod getSendInvoice() { List prices = new ArrayList<>(); prices.add(new LabeledPrice("LABEL", 1000)); diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/test/TestRestApi.java b/telegrambots/src/test/java/org/telegram/telegrambots/test/TestRestApi.java index 26e18097..c1d43a92 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/TestRestApi.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/TestRestApi.java @@ -7,16 +7,42 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; -import org.telegram.telegrambots.meta.api.methods.*; +import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; +import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.methods.ForwardMessage; +import org.telegram.telegrambots.meta.api.methods.GetFile; +import org.telegram.telegrambots.meta.api.methods.GetMe; +import org.telegram.telegrambots.meta.api.methods.GetUserProfilePhotos; import org.telegram.telegrambots.meta.api.methods.games.GetGameHighScores; import org.telegram.telegrambots.meta.api.methods.games.SetGameScore; -import org.telegram.telegrambots.meta.api.methods.groupadministration.*; -import org.telegram.telegrambots.meta.api.methods.send.*; +import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChat; +import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators; +import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember; +import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMembersCount; +import org.telegram.telegrambots.meta.api.methods.groupadministration.KickChatMember; +import org.telegram.telegrambots.meta.api.methods.groupadministration.LeaveChat; +import org.telegram.telegrambots.meta.api.methods.groupadministration.UnbanChatMember; +import org.telegram.telegrambots.meta.api.methods.send.SendChatAction; +import org.telegram.telegrambots.meta.api.methods.send.SendContact; +import org.telegram.telegrambots.meta.api.methods.send.SendGame; +import org.telegram.telegrambots.meta.api.methods.send.SendInvoice; +import org.telegram.telegrambots.meta.api.methods.send.SendLocation; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.send.SendVenue; import org.telegram.telegrambots.meta.api.methods.updates.GetWebhookInfo; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageCaption; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageReplyMarkup; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.Chat; +import org.telegram.telegrambots.meta.api.objects.ChatMember; +import org.telegram.telegrambots.meta.api.objects.File; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.api.objects.User; +import org.telegram.telegrambots.meta.api.objects.UserProfilePhotos; +import org.telegram.telegrambots.meta.api.objects.WebhookInfo; +import org.telegram.telegrambots.meta.api.objects.games.GameHighScore; import org.telegram.telegrambots.test.Fakes.FakeWebhook; import org.telegram.telegrambots.updatesreceivers.RestApi; @@ -24,6 +50,8 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -55,7 +83,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendMessage()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendMessage.class); @@ -67,7 +95,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerCallbackQuery()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, AnswerCallbackQuery.class); @@ -80,7 +108,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getAnswerInlineQuery()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, AnswerInlineQuery.class); @@ -93,7 +121,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageCaption()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, EditMessageCaption.class); @@ -109,7 +137,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageReplyMarkup()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, EditMessageReplyMarkup.class); @@ -125,7 +153,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getEditMessageText()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, EditMessageText.class); @@ -141,7 +169,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getForwardMessage()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, ForwardMessage.class); @@ -155,7 +183,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetChat()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetChat.class); @@ -168,7 +196,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatAdministrators()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod> result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetChatAdministrators.class); @@ -181,7 +209,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMember()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetChatMember.class); @@ -194,7 +222,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getChatMembersCount()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetChatMembersCount.class); @@ -207,7 +235,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetFile()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetFile.class); @@ -220,7 +248,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetGameHighScores()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod> result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetGameHighScores.class); @@ -233,7 +261,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetMe()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetMe.class); @@ -246,7 +274,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetUserProfilePhotos()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetUserProfilePhotos.class); @@ -259,7 +287,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getGetWebhookInfo()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, GetWebhookInfo.class); @@ -272,7 +300,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getKickChatMember()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, KickChatMember.class); @@ -285,7 +313,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getLeaveChat()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, LeaveChat.class); @@ -298,7 +326,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendChatAction()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendChatAction.class); @@ -311,7 +339,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendContact()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendContact.class); @@ -324,7 +352,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendGame()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendGame.class); @@ -337,7 +365,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendLocation()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendLocation.class); @@ -350,7 +378,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendVenue()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendVenue.class); @@ -363,7 +391,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSetGameScore()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SetGameScore.class); @@ -376,7 +404,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getUnbanChatMember()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, UnbanChatMember.class); @@ -389,7 +417,7 @@ public class TestRestApi extends JerseyTest { webhookBot.setReturnValue(BotApiMethodHelperFactory.getSendInvoice()); Entity entity = Entity.json(getUpdate()); - BotApiMethod result = + BotApiMethod result = target("callback/testbot") .request(MediaType.APPLICATION_JSON) .post(entity, SendInvoice.class); @@ -409,7 +437,7 @@ public class TestRestApi extends JerseyTest { } } - private String map(BotApiMethod method) { + private String map(BotApiMethod method) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(method); From 447c9d3f926f95af03bea2dffc5de0ae5a847868 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 1 Nov 2020 22:46:36 +0000 Subject: [PATCH 31/45] Update 5.0 and lombok --- README.md | 8 +- TelegramBots.wiki/Changelog.md | 9 + TelegramBots.wiki/Getting-Started.md | 4 +- TelegramBots.wiki/abilities/Simple-Example.md | 4 +- pom.xml | 14 +- telegrambots-abilities/README.md | 8 +- telegrambots-abilities/pom.xml | 8 +- .../api/bot/AbilityWebhookBot.java | 11 +- .../abilitybots/api/bot/BaseAbilityBot.java | 2 +- .../abilitybots/api/bot/DefaultAbilities.java | 10 +- .../abilitybots/api/sender/SilentSender.java | 4 +- .../abilitybots/api/bot/AbilityBotTest.java | 1 + telegrambots-chat-session-bot/README.md | 2 +- telegrambots-chat-session-bot/pom.xml | 6 +- telegrambots-extensions/README.md | 4 +- telegrambots-extensions/pom.xml | 4 +- .../commands/helpCommand/HelpCommand.java | 4 +- telegrambots-meta/pom.xml | 6 +- .../telegrambots/meta/TelegramBotsApi.java | 10 +- .../meta/api/methods/AnswerCallbackQuery.java | 83 ++--- .../meta/api/methods/AnswerInlineQuery.java | 112 ++----- .../api/methods/AnswerPreCheckoutQuery.java | 74 ++--- .../meta/api/methods/AnswerShippingQuery.java | 86 ++--- .../meta/api/methods/CopyMessage.java | 158 ++++++++++ .../meta/api/methods/ForwardMessage.java | 127 ++------ .../meta/api/methods/GetFile.java | 39 +-- .../telegrambots/meta/api/methods/GetMe.java | 19 +- .../api/methods/GetUserProfilePhotos.java | 60 ++-- .../api/methods/SetPassportDataErrors.java | 61 ++-- .../api/methods/StopMessageLiveLocation.java | 71 +---- .../api/methods/commands/GetMyCommands.java | 21 +- .../api/methods/commands/SetMyCommands.java | 44 ++- .../api/methods/games/GetGameHighScores.java | 75 ++--- .../meta/api/methods/games/SetGameScore.java | 104 ++---- .../groupadministration/DeleteChatPhoto.java | 55 +--- .../DeleteChatStickerSet.java | 55 +--- .../ExportChatInviteLink.java | 55 +--- .../methods/groupadministration/GetChat.java | 58 +--- .../GetChatAdministrators.java | 46 +-- .../groupadministration/GetChatMember.java | 57 ++-- .../GetChatMembersCount.java | 43 +-- .../groupadministration/KickChatMember.java | 95 ++---- .../groupadministration/LeaveChat.java | 44 +-- .../PromoteChatMember.java | 167 ++-------- .../RestrictChatMember.java | 118 ++----- .../SetChatAdministratorCustomTitle.java | 83 ++--- .../SetChatDescription.java | 72 ++--- .../SetChatPermissions.java | 69 +--- .../groupadministration/SetChatPhoto.java | 116 ++----- .../SetChatStickerSet.java | 68 +--- .../groupadministration/SetChatTitle.java | 69 +--- .../groupadministration/UnbanChatMember.java | 88 ++---- .../pinnedmessages/PinChatMessage.java | 90 ++---- .../pinnedmessages/UnpinAllChatMessages.java | 72 +++++ .../pinnedmessages/UnpinChatMessage.java | 76 ++--- .../meta/api/methods/polls/SendPoll.java | 249 +++------------ .../meta/api/methods/polls/StopPoll.java | 87 ++--- .../meta/api/methods/send/SendAnimation.java | 182 ++--------- .../meta/api/methods/send/SendAudio.java | 199 +++--------- .../meta/api/methods/send/SendChatAction.java | 63 ++-- .../meta/api/methods/send/SendContact.java | 123 ++------ .../meta/api/methods/send/SendDice.java | 98 ++---- .../meta/api/methods/send/SendDocument.java | 166 +++------- .../meta/api/methods/send/SendGame.java | 93 ++---- .../meta/api/methods/send/SendInvoice.java | 298 ++---------------- .../meta/api/methods/send/SendLocation.java | 159 ++++------ .../meta/api/methods/send/SendMediaGroup.java | 129 +++----- .../meta/api/methods/send/SendMessage.java | 166 +++------- .../meta/api/methods/send/SendPhoto.java | 139 ++------ .../meta/api/methods/send/SendSticker.java | 109 ++----- .../meta/api/methods/send/SendVenue.java | 160 +++------- .../meta/api/methods/send/SendVideo.java | 195 +++--------- .../meta/api/methods/send/SendVideoNote.java | 207 ++---------- .../meta/api/methods/send/SendVoice.java | 155 ++------- .../api/methods/stickers/AddStickerToSet.java | 123 ++------ .../methods/stickers/CreateNewStickerSet.java | 152 ++------- .../stickers/DeleteStickerFromSet.java | 43 +-- .../api/methods/stickers/GetStickerSet.java | 43 +-- .../stickers/SetStickerPositionInSet.java | 54 +--- .../methods/stickers/SetStickerSetThumb.java | 81 ++--- .../methods/stickers/UploadStickerFile.java | 62 ++-- .../meta/api/methods/updates/Close.java | 60 ++++ .../api/methods/updates/DeleteWebhook.java | 28 +- .../meta/api/methods/updates/GetUpdates.java | 69 +--- .../api/methods/updates/GetWebhookInfo.java | 24 +- .../meta/api/methods/updates/LogOut.java | 60 ++++ .../meta/api/methods/updates/SetWebhook.java | 121 ++++--- .../updatingmessages/DeleteMessage.java | 66 +--- .../updatingmessages/EditMessageCaption.java | 99 ++---- .../EditMessageLiveLocation.java | 133 +++----- .../updatingmessages/EditMessageMedia.java | 91 ++---- .../EditMessageReplyMarkup.java | 72 +---- .../updatingmessages/EditMessageText.java | 113 ++----- .../telegrambots/meta/api/objects/Audio.java | 65 +--- .../meta/api/objects/CallbackQuery.java | 69 +--- .../telegrambots/meta/api/objects/Chat.java | 33 +- .../meta/api/objects/ChatLocation.java | 33 ++ .../meta/api/objects/ChatMember.java | 120 +------ .../meta/api/objects/ChatPermissions.java | 96 +----- .../meta/api/objects/ChatPhoto.java | 42 +-- .../meta/api/objects/Contact.java | 48 +-- .../telegrambots/meta/api/objects/Dice.java | 40 ++- .../meta/api/objects/Document.java | 55 +--- .../telegrambots/meta/api/objects/File.java | 45 +-- .../meta/api/objects/InputFile.java | 35 +- .../meta/api/objects/Location.java | 44 ++- .../meta/api/objects/LoginUrl.java | 95 ++---- .../meta/api/objects/MemberStatus.java | 3 +- .../meta/api/objects/Message.java | 47 ++- .../meta/api/objects/MessageEntity.java | 65 ++-- .../meta/api/objects/MessageId.java | 31 ++ .../meta/api/objects/PhotoSize.java | 58 +--- .../api/objects/ProximityAlertTriggered.java | 37 +++ .../meta/api/objects/ResponseParameters.java | 35 +- .../telegrambots/meta/api/objects/Update.java | 83 +---- .../telegrambots/meta/api/objects/User.java | 10 +- .../meta/api/objects/UserProfilePhotos.java | 35 +- .../telegrambots/meta/api/objects/Venue.java | 53 ++-- .../telegrambots/meta/api/objects/Video.java | 68 +--- .../meta/api/objects/VideoNote.java | 52 +-- .../telegrambots/meta/api/objects/Voice.java | 50 +-- .../meta/api/objects/WebhookInfo.java | 51 +-- .../meta/api/objects/commands/BotCommand.java | 10 +- .../meta/api/objects/games/Animation.java | 10 +- .../meta/api/objects/games/CallbackGame.java | 10 +- .../meta/api/objects/games/Game.java | 10 +- .../meta/api/objects/games/GameHighScore.java | 10 +- .../inlinequery/ChosenInlineQuery.java | 11 +- .../api/objects/inlinequery/InlineQuery.java | 11 +- .../InputContactMessageContent.java | 10 +- .../InputLocationMessageContent.java | 46 ++- .../InputTextMessageContent.java | 19 +- .../InputVenueMessageContent.java | 17 +- .../result/InlineQueryResultArticle.java | 136 ++------ .../result/InlineQueryResultAudio.java | 139 ++------ .../result/InlineQueryResultContact.java | 139 ++------ .../result/InlineQueryResultDocument.java | 175 +++------- .../result/InlineQueryResultGame.java | 63 ++-- .../result/InlineQueryResultGif.java | 165 ++-------- .../result/InlineQueryResultLocation.java | 172 ++++------ .../result/InlineQueryResultMpeg4Gif.java | 157 ++------- .../result/InlineQueryResultPhoto.java | 22 +- .../result/InlineQueryResultVenue.java | 168 ++-------- .../result/InlineQueryResultVideo.java | 178 ++--------- .../result/InlineQueryResultVoice.java | 121 ++----- .../cached/InlineQueryResultCachedAudio.java | 109 ++----- .../InlineQueryResultCachedDocument.java | 131 ++------ .../cached/InlineQueryResultCachedGif.java | 135 ++------ .../InlineQueryResultCachedMpeg4Gif.java | 117 ++----- .../cached/InlineQueryResultCachedPhoto.java | 127 ++------ .../InlineQueryResultCachedSticker.java | 76 ++--- .../cached/InlineQueryResultCachedVideo.java | 127 ++------ .../cached/InlineQueryResultCachedVoice.java | 120 ++----- .../meta/api/objects/media/InputMedia.java | 98 ++---- .../objects/media/InputMediaAnimation.java | 64 ++-- .../api/objects/media/InputMediaAudio.java | 65 ++-- .../api/objects/media/InputMediaDocument.java | 48 ++- .../api/objects/media/InputMediaPhoto.java | 31 +- .../api/objects/media/InputMediaVideo.java | 73 ++--- .../serialization/InputMediaSerializer.java | 14 +- .../passport/EncryptedCredentials.java | 42 +-- .../passport/EncryptedPassportElement.java | 87 +---- .../api/objects/passport/PassportData.java | 36 +-- .../api/objects/passport/PassportFile.java | 47 +-- .../PassportElementErrorDataField.java | 85 ++--- .../dataerror/PassportElementErrorFile.java | 72 ++--- .../dataerror/PassportElementErrorFiles.java | 84 ++--- .../PassportElementErrorFrontSide.java | 72 ++--- .../PassportElementErrorReverseSide.java | 72 ++--- .../dataerror/PassportElementErrorSelfie.java | 72 ++--- .../PassportElementErrorTranslationFile.java | 72 ++--- .../PassportElementErrorTranslationFiles.java | 74 ++--- .../PassportElementErrorUnspecified.java | 72 ++--- .../meta/api/objects/payments/Invoice.java | 54 +--- .../api/objects/payments/LabeledPrice.java | 56 +--- .../meta/api/objects/payments/OrderInfo.java | 42 +-- .../objects/payments/PreCheckoutQuery.java | 59 +--- .../api/objects/payments/ShippingAddress.java | 52 +-- .../api/objects/payments/ShippingOption.java | 77 ++--- .../api/objects/payments/ShippingQuery.java | 42 +-- .../objects/payments/SuccessfulPayment.java | 59 +--- .../meta/api/objects/polls/Poll.java | 148 +-------- .../meta/api/objects/polls/PollAnswer.java | 64 +--- .../meta/api/objects/polls/PollOption.java | 39 +-- .../replykeyboard/ForceReplyKeyboard.java | 68 ++-- .../replykeyboard/InlineKeyboardMarkup.java | 62 ++-- .../replykeyboard/ReplyKeyboardMarkup.java | 103 ++---- .../replykeyboard/ReplyKeyboardRemove.java | 66 ++-- .../buttons/InlineKeyboardButton.java | 147 ++------- .../replykeyboard/buttons/KeyboardButton.java | 98 ++---- .../buttons/KeyboardButtonPollType.java | 54 +--- .../replykeyboard/buttons/KeyboardRow.java | 3 +- .../api/objects/stickers/MaskPosition.java | 65 ++-- .../meta/api/objects/stickers/Sticker.java | 72 +---- .../meta/api/objects/stickers/StickerSet.java | 62 +--- .../telegrambots/meta/bots/AbsSender.java | 2 +- .../meta/generics/WebhookBot.java | 9 +- .../api/methods/send/SendMessageTest.java | 23 +- .../meta/test/TestDeserialization.java | 112 +++++++ .../meta/test/TestSerialization.java | 79 +++++ telegrambots-spring-boot-starter/README.md | 4 +- telegrambots-spring-boot-starter/pom.xml | 8 +- .../starter/SpringWebhookBot.java | 27 ++ .../starter/TelegramBotInitializer.java | 9 +- .../TelegramBotStarterConfiguration.java | 10 +- .../TestTelegramBotStarterConfiguration.java | 31 +- telegrambots/pom.xml | 22 +- .../telegrambots/bots/DefaultAbsSender.java | 67 +++- .../telegrambots/bots/TelegramWebhookBot.java | 7 +- .../updatesreceivers/DefaultBotSession.java | 15 +- .../telegrambots/util/WebhookUtils.java | 75 +++++ .../test/BotApiMethodHelperFactory.java | 295 ++++++++++------- .../telegrambots/test/Fakes/FakeWebhook.java | 5 +- 213 files changed, 4731 insertions(+), 10400 deletions(-) create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/CopyMessage.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinAllChatMessages.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatLocation.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageId.java create mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ProximityAlertTriggered.java create mode 100644 telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestSerialization.java create mode 100644 telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java diff --git a/README.md b/README.md index 22ef1b08..6dd58284 100644 --- a/README.md +++ b/README.md @@ -27,16 +27,16 @@ Just import add the library to your project with one of these options: org.telegram telegrambots - 4.9.2 + 5.0.0 ``` ```gradle - compile "org.telegram:telegrambots:4.9.2" + compile "org.telegram:telegrambots:5.0.0" ``` - 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/4.9.2) - 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/4.9.2) + 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/5.0.0) + 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/5.0.0) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 62d825b8..1358a72a 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,3 +1,12 @@ +### 5.0.0 ### +1. Update Api version [5.0](https://core.telegram.org/bots/api-changelog#june-4-2020) +2. Added Builders for many of the API methods and objects +3. Some setters/getters may have change name. They no longer return a refence to itself, use Builder for that. +4. Simplified methods to set files in methods. Only InputFile is available now (this class contains constructors for all the cases) +5. Locations now use Double instead of Float to avoid rounding. +6. When registering a Webhook Bot, a SetWebhook object must be provided. +7. When using Webhook with Spring, extends class SpringWebhookBot instead of WebhookBot + ### 4.9.2 ### 1. Bug fixing: #792, #801, #804, #810, #812, #813, #820 and #814 diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md index d86c611d..ec56403d 100644 --- a/TelegramBots.wiki/Getting-Started.md +++ b/TelegramBots.wiki/Getting-Started.md @@ -11,13 +11,13 @@ First you need ot get the library and add it to your project. There are few poss org.telegram telegrambots - 4.9.2 + 5.0.0 ``` * With **Gradle**: ```groovy - compile group: 'org.telegram', name: 'telegrambots', version: '4.9.2' + compile group: 'org.telegram', name: 'telegrambots', version: '5.0.0' ``` 2. Don't like **Maven Central Repository**? It can also be taken from [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots). diff --git a/TelegramBots.wiki/abilities/Simple-Example.md b/TelegramBots.wiki/abilities/Simple-Example.md index c687f25e..0a4e2567 100644 --- a/TelegramBots.wiki/abilities/Simple-Example.md +++ b/TelegramBots.wiki/abilities/Simple-Example.md @@ -9,12 +9,12 @@ As with any Java project, you will need to set your dependencies. org.telegram telegrambots-abilities - 4.9.2 + 5.0.0 ``` * **Gradle** ```groovy - implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '4.9.2' + implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '5.0.0' ``` * [JitPack](https://jitpack.io/#rubenlagus/TelegramBots) diff --git a/pom.xml b/pom.xml index 7899d19a..37b23037 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots pom - 4.9.2 + 5.0.0 telegrambots @@ -67,12 +67,12 @@ ${java.version} ${java.version} - 5.6.2 - 3.1.0 - 3.1.0 - 2.10.1 - 2.10.1 - 1.7.29 + 5.7.0 + 3.6.0 + 3.6.0 + 2.11.3 + 2.11.3 + 1.7.30 1.3.5 1.18.16 diff --git a/telegrambots-abilities/README.md b/telegrambots-abilities/README.md index c7455741..6c58330e 100644 --- a/telegrambots-abilities/README.md +++ b/telegrambots-abilities/README.md @@ -18,19 +18,19 @@ Usage org.telegram telegrambots-abilities - 4.9.2 + 5.0.0 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-abilities:4.9.2" + compile "org.telegram:telegrambots-abilities:5.0.0" ``` -**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v4.9.2) +**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v5.0.0) -**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v4.9.2) +**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v5.0.0) Motivation ---------- diff --git a/telegrambots-abilities/pom.xml b/telegrambots-abilities/pom.xml index a52cfb24..7d4b10fb 100644 --- a/telegrambots-abilities/pom.xml +++ b/telegrambots-abilities/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambots-abilities @@ -76,15 +76,15 @@ UTF-8 UTF-8 - 3.9 - 3.0.7 + 3.11 + 3.0.8 org.telegram telegrambots - 4.9.2 + 5.0.0 org.apache.commons 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 a50aa81d..acbb9f25 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 @@ -3,11 +3,12 @@ package org.telegram.abilitybots.api.bot; import org.telegram.abilitybots.api.db.DBContext; import org.telegram.abilitybots.api.toggle.AbilityToggle; import org.telegram.abilitybots.api.toggle.DefaultToggle; -import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.bots.TelegramWebhookBot; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.WebhookBot; import org.telegram.telegrambots.util.WebhookUtils; @@ -63,8 +64,8 @@ public abstract class AbilityWebhookBot extends BaseAbilityBot implements Webhoo } @Override - public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { - WebhookUtils.setWebhook(this, url, publicCertificatePath); + public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { + WebhookUtils.setWebhook(this, setWebhook); } @Override 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 ce6d5cb5..f8beaab1 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 @@ -258,7 +258,7 @@ public abstract class BaseAbilityBot extends DefaultAbsSender implements Ability } public boolean isGroupAdmin(long chatId, int id) { - GetChatAdministrators admins = new GetChatAdministrators().setChatId(chatId); + GetChatAdministrators admins = GetChatAdministrators.builder().chatId(Long.toString(chatId)).build(); return silent.execute(admins) .orElse(new ArrayList<>()).stream() .anyMatch(member -> member.getUser().getId() == 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 6e1139bb..0c9f6707 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 @@ -14,6 +14,7 @@ import org.telegram.abilitybots.api.util.AbilityUtils; import org.telegram.abilitybots.api.util.Pair; import org.telegram.telegrambots.meta.api.methods.GetFile; import org.telegram.telegrambots.meta.api.methods.send.SendDocument; +import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; @@ -221,9 +222,10 @@ public final class DefaultAbilities implements AbilityExtension { try (PrintStream printStream = new PrintStream(backup)) { printStream.print(bot.db.backup()); - bot.sender.sendDocument(new SendDocument() - .setDocument(backup) - .setChatId(ctx.chatId()) + bot.sender.sendDocument(SendDocument.builder() + .document(new InputFile(backup)) + .chatId(ctx.chatId().toString()) + .build() ); } catch (FileNotFoundException e) { log.error("Error while fetching backup", e); @@ -472,6 +474,6 @@ public final class DefaultAbilities implements AbilityExtension { } protected File downloadFileWithId(String fileId) throws TelegramApiException { - return bot.sender.downloadFile(bot.sender.execute(new GetFile().setFileId(fileId))); + return bot.sender.downloadFile(bot.sender.execute(GetFile.builder().fileId(fileId).build())); } } diff --git a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/SilentSender.java b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/SilentSender.java index 0e3aeb6c..4c677875 100644 --- a/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/SilentSender.java +++ b/telegrambots-abilities/src/main/java/org/telegram/abilitybots/api/sender/SilentSender.java @@ -38,7 +38,7 @@ public class SilentSender { public Optional forceReply(String message, long id) { SendMessage msg = new SendMessage(); msg.setText(message); - msg.setChatId(id); + msg.setChatId(Long.toString(id)); msg.setReplyMarkup(new ForceReplyKeyboard()); return execute(msg); @@ -64,7 +64,7 @@ public class SilentSender { private Optional doSendMessage(String txt, long groupId, boolean format) { SendMessage smsg = new SendMessage(); - smsg.setChatId(groupId); + smsg.setChatId(Long.toString(groupId)); smsg.setText(txt); smsg.enableMarkdown(format); 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 c69daef3..9fedf218 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 @@ -702,6 +702,7 @@ public class AbilityBotTest { Message botMessage = mock(Message.class); Document document = mock(Document.class); + when(document.getFileId()).thenReturn("FAKEFILEID"); when(message.getFrom()).thenReturn(CREATOR); when(update.getMessage()).thenReturn(message); when(message.getDocument()).thenReturn(document); diff --git a/telegrambots-chat-session-bot/README.md b/telegrambots-chat-session-bot/README.md index 479c1d5c..5cfd0cf7 100644 --- a/telegrambots-chat-session-bot/README.md +++ b/telegrambots-chat-session-bot/README.md @@ -15,7 +15,7 @@ Usage org.telegram telegrambots-chat-session-bot - 4.9.2 + 5.0.0 ``` diff --git a/telegrambots-chat-session-bot/pom.xml b/telegrambots-chat-session-bot/pom.xml index e5e0138a..00b9368f 100644 --- a/telegrambots-chat-session-bot/pom.xml +++ b/telegrambots-chat-session-bot/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambots-chat-session-bot @@ -76,7 +76,7 @@ UTF-8 UTF-8 - 1.4.2 + 1.7.0 @@ -84,7 +84,7 @@ org.telegram telegrambots - 4.9.2 + 5.0.0 diff --git a/telegrambots-extensions/README.md b/telegrambots-extensions/README.md index 91fa288b..e56cf766 100644 --- a/telegrambots-extensions/README.md +++ b/telegrambots-extensions/README.md @@ -16,12 +16,12 @@ Just import add the library to your project with one of these options: org.telegram telegrambotsextensions - 4.9.2 + 5.0.0 ``` 2. Using Gradle: ```gradle - compile "org.telegram:telegrambotsextensions:4.9.2" + compile "org.telegram:telegrambotsextensions:5.0.0" ``` \ No newline at end of file diff --git a/telegrambots-extensions/pom.xml b/telegrambots-extensions/pom.xml index 0b16870d..4dd00ed0 100644 --- a/telegrambots-extensions/pom.xml +++ b/telegrambots-extensions/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambotsextensions @@ -75,7 +75,7 @@ org.telegram telegrambots - 4.9.2 + 5.0.0 diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/helpCommand/HelpCommand.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/helpCommand/HelpCommand.java index 65344615..39f7c291 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/helpCommand/HelpCommand.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/helpCommand/HelpCommand.java @@ -98,14 +98,14 @@ public class HelpCommand extends ManCommand { IBotCommand command = registry.getRegisteredCommand(arguments[0]); String reply = getManText(command); try { - absSender.execute(new SendMessage(chat.getId(), reply).setParseMode("HTML")); + absSender.execute(SendMessage.builder().chatId(chat.getId().toString()).text(reply).parseMode("HTML").build()); } catch (TelegramApiException e) { e.printStackTrace(); } } else { String reply = getHelpText(registry); try { - absSender.execute(new SendMessage(chat.getId(), reply).setParseMode("HTML")); + absSender.execute(SendMessage.builder().chatId(chat.getId().toString()).text(reply).parseMode("HTML").build()); } catch (TelegramApiException e) { e.printStackTrace(); } diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index 7d3ffc4e..0410cf24 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambots-meta @@ -70,8 +70,8 @@ UTF-8 UTF-8 4.2.3 - 2.10.1 - 2.10.1 + 2.11.3 + 2.11.3 20180813 30.0-jre 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 04f5b694..bd574a87 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,5 +1,7 @@ package org.telegram.telegrambots.meta; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; +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; @@ -11,8 +13,7 @@ import java.text.MessageFormat; /** * @author Ruben Bermudez * @version 1.0 - * @brief Bots manager - * @date 14 of January of 2016 + * Bots manager */ public class TelegramBotsApi { private static final String webhookUrlFormat = "{0}callback/"; @@ -130,12 +131,13 @@ 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 */ - public void registerBot(WebhookBot bot) throws TelegramApiRequestException { + public void registerBot(WebhookBot bot, SetWebhook setWebhook) throws TelegramApiException { if (useWebhook) { bot.onRegister(); webhook.registerWebhook(bot); - bot.setWebhook(externalUrl + bot.getBotPath(), pathToCertificate); + bot.setWebhook(setWebhook); } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerCallbackQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerCallbackQuery.java index 1f9790ae..6ce34521 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerCallbackQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerCallbackQuery.java @@ -2,7 +2,15 @@ package org.telegram.telegrambots.meta.api.methods; 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.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -16,10 +24,18 @@ import java.io.IOException; * will be displayed to the user as a notification at the top of the chat screen or as an alert. On * success, True is returned. * - * @note Alternatively, the user can be redirected to the specified URL. For this option to work, + * @apiNote Alternatively, the user can be redirected to the specified URL. For this option to work, * you must enable /setcustomurls for your bot via BotFather and accept the terms. * */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class AnswerCallbackQuery extends BotApiMethod { public static final String PATH = "answercallbackquery"; @@ -30,6 +46,7 @@ public class AnswerCallbackQuery extends BotApiMethod { private static final String CACHETIME_FIELD = "cache_time"; @JsonProperty(CALLBACKQUERYID_FIELD) + @NonNull private String callbackQueryId; ///< Unique identifier for the query to be answered @JsonProperty(TEXT_FIELD) private String text; ///< Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters @@ -47,60 +64,11 @@ public class AnswerCallbackQuery extends BotApiMethod { * Optional The maximum amount of time in seconds that the result of the callback query * may be cached client-side. * - * @note Telegram apps will support caching starting in version 3.14. Defaults to 0. + * @apiNote Telegram apps will support caching starting in version 3.14. Defaults to 0. */ @JsonProperty(CACHETIME_FIELD) private Integer cacheTime; - public AnswerCallbackQuery() { - super(); - } - - public String getCallbackQueryId() { - return this.callbackQueryId; - } - - public AnswerCallbackQuery setCallbackQueryId(String callbackQueryId) { - this.callbackQueryId = callbackQueryId; - return this; - } - - public String getText() { - return this.text; - } - - public AnswerCallbackQuery setText(String text) { - this.text = text; - return this; - } - - public Boolean getShowAlert() { - return this.showAlert; - } - - public AnswerCallbackQuery setShowAlert(Boolean showAlert) { - this.showAlert = showAlert; - return this; - } - - public String getUrl() { - return url; - } - - public AnswerCallbackQuery setUrl(String url) { - this.url = url; - return this; - } - - public Integer getCacheTime() { - return cacheTime; - } - - public AnswerCallbackQuery setCacheTime(Integer cacheTime) { - this.cacheTime = cacheTime; - return this; - } - @Override public String getMethod() { return PATH; @@ -127,15 +95,4 @@ public class AnswerCallbackQuery extends BotApiMethod { throw new TelegramApiValidationException("CallbackQueryId can't be null", this); } } - - @Override - public String toString() { - return "AnswerCallbackQuery{" + - "callbackQueryId='" + callbackQueryId + '\'' + - ", text='" + text + '\'' + - ", showAlert=" + showAlert + - ", url='" + url + '\'' + - ", cacheTime=" + cacheTime + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerInlineQuery.java index ee9a685e..649add7e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerInlineQuery.java @@ -1,16 +1,23 @@ package org.telegram.telegrambots.meta.api.methods; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; - -import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; +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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; @@ -19,6 +26,14 @@ import java.util.regex.Pattern; * @version 1.0 * Use this method to send answers to an inline query. On success, True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class AnswerInlineQuery extends BotApiMethod { public static final String PATH = "answerInlineQuery"; @@ -31,8 +46,11 @@ public class AnswerInlineQuery extends BotApiMethod { private static final String SWITCH_PM_PARAMETER_FIELD = "switch_pm_parameter"; @JsonProperty(INLINEQUERYID_FIELD) + @NonNull private String inlineQueryId; ///< Unique identifier for answered query @JsonProperty(RESULTS_FIELD) + @Singular + @NonNull private List results; ///< A JSON-serialized array of results for the inline query @JsonProperty(CACHETIME_FIELD) private Integer cacheTime; ///< Optional The maximum amount of time the result of the inline query may be cached on the server @@ -45,79 +63,6 @@ public class AnswerInlineQuery extends BotApiMethod { @JsonProperty(SWITCH_PM_PARAMETER_FIELD) private String switchPmParameter; ///< Optional. Parameter for the start message sent to the bot when user presses the switch button - public AnswerInlineQuery() { - super(); - } - - public String getInlineQueryId() { - return inlineQueryId; - } - - public AnswerInlineQuery setInlineQueryId(String inlineQueryId) { - this.inlineQueryId = inlineQueryId; - return this; - } - - public List getResults() { - return results; - } - - public AnswerInlineQuery setResults(List results) { - this.results = results; - return this; - } - - @JsonIgnore - public AnswerInlineQuery setResults(InlineQueryResult... results) { - this.results = Arrays.asList(results); - return this; - } - - public Integer getCacheTime() { - return cacheTime; - } - - public AnswerInlineQuery setCacheTime(Integer cacheTime) { - this.cacheTime = cacheTime; - return this; - } - - public Boolean isPersonal() { - return isPersonal; - } - - public AnswerInlineQuery setPersonal(Boolean personal) { - isPersonal = personal; - return this; - } - - public String getNextOffset() { - return nextOffset; - } - - public AnswerInlineQuery setNextOffset(String nextOffset) { - this.nextOffset = nextOffset; - return this; - } - - public String getSwitchPmText() { - return switchPmText; - } - - public AnswerInlineQuery setSwitchPmText(String switchPmText) { - this.switchPmText = switchPmText; - return this; - } - - public String getSwitchPmParameter() { - return switchPmParameter; - } - - public AnswerInlineQuery setSwitchPmParameter(String switchPmParameter) { - this.switchPmParameter = switchPmParameter; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (inlineQueryId == null || inlineQueryId.isEmpty()) { @@ -164,17 +109,4 @@ public class AnswerInlineQuery extends BotApiMethod { throw new TelegramApiRequestException("Unable to deserialize response", e); } } - - @Override - public String toString() { - return "AnswerInlineQuery{" + - "inlineQueryId='" + inlineQueryId + '\'' + - ", results=" + results + - ", cacheTime=" + cacheTime + - ", isPersonal=" + isPersonal + - ", switchPmText=" + switchPmText + - ", switchPmParameter=" + switchPmParameter + - ", nextOffset='" + nextOffset + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerPreCheckoutQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerPreCheckoutQuery.java index 3519c0da..5679fdfa 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerPreCheckoutQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerPreCheckoutQuery.java @@ -2,14 +2,21 @@ package org.telegram.telegrambots.meta.api.methods; 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.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 @@ -21,6 +28,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * * @apiNote The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class AnswerPreCheckoutQuery extends BotApiMethod { public static final String PATH = "answerPreCheckoutQuery"; @@ -29,56 +44,14 @@ public class AnswerPreCheckoutQuery extends BotApiMethod { private static final String ERROR_MESSAGE_FIELD = "error_message"; @JsonProperty(PRE_CHECKOUT_QUERY_ID_FIELD) + @NonNull private String preCheckoutQueryId; ///< Unique identifier for the query to be answered @JsonProperty(OK_FIELD) + @NonNull private Boolean ok; ///< Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. @JsonProperty(ERROR_MESSAGE_FIELD) private String errorMessage; ///< Optional. Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout - /** - * Creates an empty answer pre-checkout query - */ - public AnswerPreCheckoutQuery() { - super(); - } - - /** - * Creates an answer pre-checkout query with mandatory parameters - * @param preCheckoutQueryId Unique identifier for the query to be answered - * @param ok Specify True if delivery to the specified address is possible and False if there are any problems - */ - public AnswerPreCheckoutQuery(String preCheckoutQueryId, Boolean ok) { - this.preCheckoutQueryId = checkNotNull(preCheckoutQueryId); - this.ok = checkNotNull(ok); - } - - public String getPreCheckoutQueryId() { - return preCheckoutQueryId; - } - - public AnswerPreCheckoutQuery setPreCheckoutQueryId(String preCheckoutQueryId) { - this.preCheckoutQueryId = checkNotNull(preCheckoutQueryId); - return this; - } - - public Boolean getOk() { - return ok; - } - - public AnswerPreCheckoutQuery setOk(Boolean ok) { - this.ok = checkNotNull(ok); - return this; - } - - public String getErrorMessage() { - return errorMessage; - } - - public AnswerPreCheckoutQuery setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (preCheckoutQueryId == null || preCheckoutQueryId.isEmpty()) { @@ -113,13 +86,4 @@ public class AnswerPreCheckoutQuery extends BotApiMethod { throw new TelegramApiRequestException("Unable to deserialize response", e); } } - - @Override - public String toString() { - return "AnswerPreCheckoutQuery{" + - "preCheckoutQueryId='" + preCheckoutQueryId + '\'' + - ", ok=" + ok + - ", errorMessage='" + errorMessage + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerShippingQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerShippingQuery.java index d4af9fcf..07f77125 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerShippingQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerShippingQuery.java @@ -2,16 +2,23 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; -import org.telegram.telegrambots.meta.api.objects.payments.ShippingOption; +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.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.payments.ShippingOption; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 @@ -22,6 +29,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * * On success, True is returned */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class AnswerShippingQuery extends BotApiMethod { public static final String PATH = "answerShippingQuery"; @@ -31,67 +46,16 @@ public class AnswerShippingQuery extends BotApiMethod { private static final String ERROR_MESSAGE_FIELD = "error_message"; @JsonProperty(SHIPPING_QUERY_ID_FIELD) + @NonNull private String shippingQueryId; ///< Unique identifier for the query to be answered @JsonProperty(OK_FIELD) + @NonNull private Boolean ok; ///< Specify True if delivery to the specified address is possible and False if there are any problems @JsonProperty(SHIPPING_OPTIONS_FIELD) private List shippingOptions; ///< Optional. Required if ok is True. A JSON-serialized array of available shipping options. @JsonProperty(ERROR_MESSAGE_FIELD) private String errorMessage; ///< Optional. Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). - /** - * Creates an empty answer shipping query - */ - public AnswerShippingQuery() { - super(); - } - - /** - * Creates an answer shipping query with mandatory parameters - * @param shippingQueryId Unique identifier for the query to be answered - * @param ok Specify True if delivery to the specified address is possible and False if there are any problems - */ - public AnswerShippingQuery(String shippingQueryId, Boolean ok) { - this.shippingQueryId = checkNotNull(shippingQueryId); - this.ok = checkNotNull(ok); - } - - public String getShippingQueryId() { - return shippingQueryId; - } - - public AnswerShippingQuery setShippingQueryId(String shippingQueryId) { - this.shippingQueryId = checkNotNull(shippingQueryId); - return this; - } - - public Boolean getOk() { - return ok; - } - - public AnswerShippingQuery setOk(Boolean ok) { - this.ok = checkNotNull(ok); - return this; - } - - public List getShippingOptions() { - return shippingOptions; - } - - public AnswerShippingQuery setShippingOptions(List shippingOptions) { - this.shippingOptions = shippingOptions; - return this; - } - - public String getErrorMessage() { - return errorMessage; - } - - public AnswerShippingQuery setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (shippingQueryId == null || shippingQueryId.isEmpty()) { @@ -133,14 +97,4 @@ public class AnswerShippingQuery extends BotApiMethod { throw new TelegramApiRequestException("Unable to deserialize response", e); } } - - @Override - public String toString() { - return "AnswerShippingQuery{" + - "shippingQueryId='" + shippingQueryId + '\'' + - ", ok=" + ok + - ", shippingOptions=" + shippingOptions + - ", errorMessage='" + errorMessage + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/CopyMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/CopyMessage.java new file mode 100644 index 00000000..4f2fef63 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/CopyMessage.java @@ -0,0 +1,158 @@ +package org.telegram.telegrambots.meta.api.methods; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; +import org.telegram.telegrambots.meta.api.objects.MessageId; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; +import java.util.List; + +/** + * @author Ruben Bermudez + * @version 1.0 + * Use this method to copy messages of any kind. The method is analogous to the method forwardMessages, + * but the copied message doesn't have a link to the original message. + * Returns the MessageId of the sent message on success. + */ +@SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class CopyMessage extends BotApiMethod { + public static final String PATH = "copyMessage"; + + private static final String CHATID_FIELD = "chat_id"; + private static final String FROMCHATID_FIELD = "from_chat_id"; + private static final String MESSAGEID_FIELD = "message_id"; + private static final String CAPTION_FIELD = "caption"; + private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTIONENTITIES_FIELD = "caption_entities"; + private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; + private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + private static final String REPLYMARKUP_FIELD = "reply_markup"; + + @JsonProperty(CHATID_FIELD) + @NonNull + private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) + @JsonProperty(FROMCHATID_FIELD) + @NonNull + private String fromChatId; ///< Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) + @JsonProperty(MESSAGEID_FIELD) + @NonNull + private Integer messageId; ///< Message identifier in the chat specified in from_chat_id + @JsonProperty(CAPTION_FIELD) + private String caption; ///< Optional. New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + @JsonProperty(PARSEMODE_FIELD) + private String parseMode; ///< Optional. Mode for parsing entities in the new caption. See formatting options for more details. + @JsonProperty(CAPTIONENTITIES_FIELD) + private List captionEntities; ///< Optional. List of special entities that appear in the new caption, which can be specified instead of parse_mode + @JsonProperty(DISABLENOTIFICATION_FIELD) + private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. + @JsonProperty(REPLYTOMESSAGEID_FIELD) + private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional. Pass True, if the message should be sent even if the specified replied-to message is not found + /** + * Optional. + * + * Additional interface options. + * A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or + * to force a reply from the user. + */ + @JsonProperty(REPLYMARKUP_FIELD) + @JsonDeserialize() + private ReplyKeyboard replyMarkup; + + public void enableNotification() { + this.disableNotification = null; + } + + public void disableNotification() { + this.disableNotification = true; + } + + public void enableMarkdown(boolean enable) { + if (enable) { + this.parseMode = ParseMode.MARKDOWN; + } else { + this.parseMode = null; + } + } + + public void enableHtml(boolean enable) { + if (enable) { + this.parseMode = ParseMode.HTML; + } else { + this.parseMode = null; + } + } + + public void enableMarkdownV2(boolean enable) { + if (enable) { + this.parseMode = ParseMode.MARKDOWNV2; + } else { + this.parseMode = null; + } + } + + @Override + public String getMethod() { + return PATH; + } + + @Override + public MessageId 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 copying message", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (chatId == null) { + throw new TelegramApiValidationException("ChatId parameter can't be empty", this); + } + if (fromChatId == null) { + throw new TelegramApiValidationException("FromChatId parameter can't be empty", this); + } + if (messageId == null) { + throw new TelegramApiValidationException("MessageId parameter can't be empty", this); + } + + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } + if (replyMarkup != null) { + replyMarkup.validate(); + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/ForwardMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/ForwardMessage.java index f8e5580c..dfb76e4e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/ForwardMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/ForwardMessage.java @@ -2,20 +2,35 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; - -import org.telegram.telegrambots.meta.api.objects.Message; +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.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send text messages. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class ForwardMessage extends BotApiMethod { public static final String PATH = "forwardmessage"; @@ -25,10 +40,13 @@ public class ForwardMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (or username for channels) @JsonProperty(FROMCHATID_FIELD) + @NonNull private String fromChatId; ///< Unique identifier for the chat where the original message was sent — User or GroupChat id @JsonProperty(MESSAGEID_FIELD) + @NonNull private Integer messageId; ///< Unique message identifier /** * Optional. Sends the message silently. @@ -39,99 +57,6 @@ public class ForwardMessage extends BotApiMethod { @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; - public ForwardMessage() { - super(); - } - - public ForwardMessage(String chatId, String fromChatId, Integer messageId) { - this(); - Objects.requireNonNull(chatId); - Objects.requireNonNull(fromChatId); - this.chatId = chatId; - this.fromChatId = fromChatId; - this.messageId = messageId; - } - - public ForwardMessage(String chatId, Long fromChatId, Integer messageId) { - this(); - Objects.requireNonNull(chatId); - Objects.requireNonNull(fromChatId); - this.chatId = chatId; - this.fromChatId = fromChatId.toString(); - this.messageId = messageId; - } - - public ForwardMessage(Long chatId, String fromChatId, Integer messageId) { - this(); - Objects.requireNonNull(chatId); - Objects.requireNonNull(fromChatId); - this.chatId = chatId.toString(); - this.fromChatId = fromChatId; - this.messageId = messageId; - } - - public ForwardMessage(Long chatId, Long fromChatId, Integer messageId) { - this(); - Objects.requireNonNull(chatId); - Objects.requireNonNull(fromChatId); - this.chatId = chatId.toString(); - this.fromChatId = fromChatId.toString(); - this.messageId = messageId; - } - - public String getChatId() { - return chatId; - } - - public ForwardMessage setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public ForwardMessage setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getFromChatId() { - return fromChatId; - } - - public ForwardMessage setFromChatId(String fromChatId) { - this.fromChatId = fromChatId; - return this; - } - - public ForwardMessage setFromChatId(Long fromChatId) { - Objects.requireNonNull(fromChatId); - this.fromChatId = fromChatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public ForwardMessage setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public ForwardMessage enableNotification() { - this.disableNotification = false; - return this; - } - - public ForwardMessage disableNotification() { - this.disableNotification = true; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (chatId == null || chatId.isEmpty()) { @@ -164,14 +89,4 @@ public class ForwardMessage extends BotApiMethod { throw new TelegramApiRequestException("Unable to deserialize response", e); } } - - @Override - public String toString() { - return "ForwardMessage{" + - "chatId='" + chatId + '\'' + - ", fromChatId='" + fromChatId + '\'' + - ", messageId=" + messageId + - ", disableNotification=" + disableNotification + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetFile.java index 9b587833..8a089155 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetFile.java @@ -2,9 +2,16 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; - -import org.telegram.telegrambots.meta.api.objects.File; +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.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.File; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -21,27 +28,22 @@ import java.io.IOException; * It is guaranteed that the link will be valid for at least 1 hour. * When the link expires, a new one can be requested by calling getFile again. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetFile extends BotApiMethod { public static final String PATH = "getFile"; private static final String FILEID_FIELD = "file_id"; @JsonProperty(FILEID_FIELD) + @NonNull private String fileId; ///< File identifier to get info about - public GetFile() { - super(); - } - - public String getFileId() { - return fileId; - } - - public GetFile setFileId(String fileId) { - this.fileId = fileId; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileId == null) { @@ -68,11 +70,4 @@ public class GetFile extends BotApiMethod { throw new TelegramApiRequestException("Unable to deserialize response", e); } } - - @Override - public String toString() { - return "GetFile{" + - "fileId='" + fileId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetMe.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetMe.java index 26969574..fee2b8bc 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetMe.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/GetMe.java @@ -1,9 +1,14 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.core.type.TypeReference; - -import org.telegram.telegrambots.meta.api.objects.User; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -15,13 +20,15 @@ import java.io.IOException; * A simple method for testing your bot's auth token. Requires no parameters. * Returns basic information about the bot in form of a User object */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@AllArgsConstructor +@Builder public class GetMe extends BotApiMethod { public static final String PATH = "getme"; - public GetMe() { - super(); - } - @Override public String getMethod() { return PATH; 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 b0495dfa..b1c3ae5d 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 @@ -3,6 +3,15 @@ package org.telegram.telegrambots.meta.api.methods; 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.objects.UserProfilePhotos; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; @@ -15,6 +24,14 @@ import java.io.IOException; * @version 1.0 * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class GetUserProfilePhotos extends BotApiMethod { public static final String PATH = "getuserprofilephotos"; @@ -23,9 +40,10 @@ public class GetUserProfilePhotos extends BotApiMethod { private static final String LIMIT_FIELD = "limit"; @JsonProperty(USERID_FIELD) + @NonNull private Integer userId; ///< Unique identifier of the target user /** - * Sequential number of the first photo to be returned. By default, all photos are returned. + * Optional. Sequential number of the first photo to be returned. By default, all photos are returned. */ @JsonProperty(OFFSET_FIELD) private Integer offset; @@ -35,37 +53,6 @@ public class GetUserProfilePhotos extends BotApiMethod { @JsonProperty(LIMIT_FIELD) private Integer limit; - public GetUserProfilePhotos() { - super(); - } - - public Integer getUserId() { - return userId; - } - - public GetUserProfilePhotos setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public Integer getOffset() { - return offset; - } - - public GetUserProfilePhotos setOffset(Integer offset) { - this.offset = offset; - return this; - } - - public Integer getLimit() { - return limit; - } - - public GetUserProfilePhotos setLimit(Integer limit) { - this.limit = limit; - return this; - } - @Override public String getMethod() { return PATH; @@ -92,13 +79,4 @@ public class GetUserProfilePhotos extends BotApiMethod { throw new TelegramApiValidationException("UserId parameter can't be empty", this); } } - - @Override - public String toString() { - return "GetUserProfilePhotos{" + - "userId=" + userId + - ", offset=" + offset + - ", limit=" + limit + - '}'; - } } 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 c78fef8d..c8a5eeb3 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 @@ -2,17 +2,23 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; -import org.telegram.telegrambots.meta.api.objects.passport.dataerror.PassportElementError; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.passport.dataerror.PassportElementError; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.ArrayList; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -20,6 +26,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * Informs a user that some Telegram Passport data contains errors. * The user will not be able to resend data, until the errors are fixed */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetPassportDataErrors extends BotApiMethod { public static final String PATH = "setPassportDataErrors"; @@ -27,47 +40,13 @@ public class SetPassportDataErrors extends BotApiMethod { private static final String ERRORS_FIELD = "errors"; @JsonProperty(USERID_FIELD) + @NonNull private Integer userId; ///< User identifier @JsonProperty(ERRORS_FIELD) + @NonNull + @Singular private List errors; ///< A JSON-serialized array describing the errors - public SetPassportDataErrors(Integer userId, List errors) { - super(); - this.userId = checkNotNull(userId); - this.errors = checkNotNull(errors); - } - - public SetPassportDataErrors() { - super(); - } - - public Integer getUserId() { - return userId; - } - - public SetPassportDataErrors setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public List getErrors() { - return errors; - } - - public SetPassportDataErrors setErrors(List errors) { - this.errors = errors; - return this; - } - - public SetPassportDataErrors addError(PassportElementError error) { - error = checkNotNull(error); - if (this.errors == null) { - this.errors = new ArrayList<>(); - } - this.errors.add(error); - return this; - } - @Override public String getMethod() { return PATH; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/StopMessageLiveLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/StopMessageLiveLocation.java index 1f042017..bbddfcb1 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/StopMessageLiveLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/StopMessageLiveLocation.java @@ -2,8 +2,15 @@ package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; -import org.telegram.telegrambots.meta.api.objects.Message; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -18,6 +25,13 @@ import java.io.Serializable; * before live_period expires. On success, if the message was sent by the bot, the sent Message is returned, * otherwise True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class StopMessageLiveLocation extends BotApiMethod { public static final String PATH = "stopMessageLiveLocation"; @@ -45,51 +59,6 @@ public class StopMessageLiveLocation extends BotApiMethod { @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. - public StopMessageLiveLocation() { - super(); - } - - public String getChatId() { - return chatId; - } - - public StopMessageLiveLocation setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public StopMessageLiveLocation setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public StopMessageLiveLocation setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public StopMessageLiveLocation setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public StopMessageLiveLocation setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - @Override public String getMethod() { return PATH; @@ -142,14 +111,4 @@ public class StopMessageLiveLocation extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "StopMessageLiveLocation{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java index a1347bc3..ea339716 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.methods.commands; import com.fasterxml.jackson.core.type.TypeReference; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +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.commands.BotCommand; @@ -17,13 +23,15 @@ import java.util.ArrayList; * Requires no parameters. * Returns Array of BotCommand on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@Builder public class GetMyCommands extends BotApiMethod> { public static final String PATH = "getMyCommands"; - public GetMyCommands() { - super(); - } - @Override public String getMethod() { return PATH; @@ -47,9 +55,4 @@ public class GetMyCommands extends BotApiMethod> { @Override public void validate() throws TelegramApiValidationException { } - - @Override - public String toString() { - return "GetMyCommands{}"; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/SetMyCommands.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/SetMyCommands.java index 4828e0db..83aa2d1a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/SetMyCommands.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/SetMyCommands.java @@ -2,6 +2,15 @@ package org.telegram.telegrambots.meta.api.methods.commands; 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.Setter; +import lombok.Singular; +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.commands.BotCommand; @@ -11,13 +20,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.7 * Use this method to change the list of the bot's commands. Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetMyCommands extends BotApiMethod { public static final String PATH = "setMyCommands"; @@ -28,25 +42,10 @@ public class SetMyCommands extends BotApiMethod { * At most 100 commands can be specified. */ @JsonProperty(COMMANDS_FIELD) + @Singular + @NonNull private List commands; - public SetMyCommands() { - super(); - } - - public SetMyCommands(List commands) { - this.commands = checkNotNull(commands); - } - - public List getCommands() { - return commands; - } - - public SetMyCommands setCommands(List commands) { - this.commands = checkNotNull(commands); - return this; - } - @Override public String getMethod() { return PATH; @@ -79,11 +78,4 @@ public class SetMyCommands extends BotApiMethod { command.validate(); } } - - @Override - public String toString() { - return "SetMyCommands{" + - "commands=" + commands + - '}'; - } } 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 2671ffdf..03422be2 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 @@ -19,6 +19,15 @@ package org.telegram.telegrambots.meta.api.methods.games; 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.games.GameHighScore; import org.telegram.telegrambots.meta.api.objects.ApiResponse; @@ -35,12 +44,20 @@ import java.util.ArrayList; * Will return the score of the specified user and several of his neighbors in a game. * On success, returns an Array of GameHighScore objects. * - * @note This method will currently return scores for the target user, + * @apiNote This method will currently return scores for the target user, * plus two of his closest neighbors on each side. Will also return the top three users * if the user and his neighbors are not among them. * Please note that this behavior is subject to change. * */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class GetGameHighScores extends BotApiMethod> { public static final String PATH = "getGameHighScores"; @@ -56,53 +73,9 @@ public class GetGameHighScores extends BotApiMethod> { @JsonProperty(INLINE_MESSAGE_ID_FIELD) 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; ///> { } } } - - @Override - public String toString() { - return "GetGameHighScores{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", userId=" + userId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/SetGameScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/SetGameScore.java index c7c7c48a..d0999a94 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/SetGameScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/games/SetGameScore.java @@ -20,6 +20,15 @@ package org.telegram.telegrambots.meta.api.methods.games; 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.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; @@ -39,6 +48,14 @@ import java.io.Serializable; * Returns an error, if the new score is not greater than the user's current score in * the chat and force is False. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class SetGameScore extends BotApiMethod { public static final String PATH = "setGameScore"; @@ -59,84 +76,14 @@ public class SetGameScore extends BotApiMethod { @JsonProperty(DISABLEEDITMESSAGE_FIELD) 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 @JsonProperty(SCORE_FIELD) + @NonNull private Integer score; ///< New score, must be positive @JsonProperty(FORCE_FIELD) private Boolean force; ///< Optional. Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters - public SetGameScore() { - super(); - } - - public String getChatId() { - return chatId; - } - - public Integer getMessageId() { - return messageId; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public Boolean getDisableEditMessage() { - return disableEditMessage; - } - - public Integer getUserId() { - return userId; - } - - public Integer getScore() { - return score; - } - - public Boolean getForce() { - return force; - } - - public SetGameScore setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetGameScore setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public SetGameScore setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public SetGameScore setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public SetGameScore setDisableEditMessage(Boolean disableEditMessage) { - this.disableEditMessage = disableEditMessage; - return this; - } - - public SetGameScore setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public SetGameScore setScore(Integer score) { - this.score = score; - return this; - } - - public SetGameScore setForce(Boolean force) { - this.force = force; - return this; - } - @Override public String getMethod() { return PATH; @@ -192,17 +139,4 @@ public class SetGameScore extends BotApiMethod { } } } - - @Override - public String toString() { - return "SetGameScore{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", disableEditMessage=" + disableEditMessage + - ", userId=" + userId + - ", score=" + score + - ", force=" + force + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatPhoto.java index 8ee13e40..4b17550c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatPhoto.java @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -21,43 +26,22 @@ import static com.google.common.base.Preconditions.checkNotNull; * * @apiNote In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class DeleteChatPhoto extends BotApiMethod { public static final String PATH = "deleteChatPhoto"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) - public DeleteChatPhoto() { - super(); - } - - public DeleteChatPhoto(String chatId) { - super(); - this.chatId = checkNotNull(chatId); - } - - public DeleteChatPhoto(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public DeleteChatPhoto setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public DeleteChatPhoto setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -84,11 +68,4 @@ public class DeleteChatPhoto extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be null", this); } } - - @Override - public String toString() { - return "DeleteChatPhoto{" + - "chatId='" + chatId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatStickerSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatStickerSet.java index 60d5fdff..bcda48fd 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatStickerSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/DeleteChatStickerSet.java @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -20,43 +25,22 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class DeleteChatStickerSet extends BotApiMethod { public static final String PATH = "deleteChatStickerSet"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public DeleteChatStickerSet() { - super(); - } - - public DeleteChatStickerSet(String chatId) { - super(); - this.chatId = checkNotNull(chatId); - } - - public DeleteChatStickerSet(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public DeleteChatStickerSet setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public DeleteChatStickerSet setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -83,11 +67,4 @@ public class DeleteChatStickerSet extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be empty", this); } } - - @Override - public String toString() { - return "DeleteChatStickerSet{" + - "chatId='" + chatId + '\'' + - '}'; - } } 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 41a49474..3f58b587 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 @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -18,43 +23,22 @@ import static com.google.common.base.Preconditions.checkNotNull; * 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. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class ExportChatInviteLink extends BotApiMethod { public static final String PATH = "exportChatInviteLink"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public ExportChatInviteLink() { - super(); - } - - public ExportChatInviteLink(String chatId) { - super(); - this.chatId = checkNotNull(chatId); - } - - public ExportChatInviteLink(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public ExportChatInviteLink setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public ExportChatInviteLink setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -81,11 +65,4 @@ public class ExportChatInviteLink extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be empty", this); } } - - @Override - public String toString() { - return "ExportChatInviteLink{" + - "chatId='" + chatId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChat.java index 30887fab..7c746df2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChat.java @@ -2,60 +2,43 @@ 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez * @version 1.0 * Use this method to get information about the chat. Returns Chat object on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetChat extends BotApiMethod { public static final String PATH = "getChat"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public GetChat() { - super(); - } - - public GetChat(String chatId) { - super(); - this.chatId = checkNotNull(chatId); - } - - public GetChat(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public GetChat setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public GetChat setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -82,11 +65,4 @@ public class GetChat extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be empty", this); } } - - @Override - public String toString() { - return "GetChat{" + - "chatId='" + chatId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatAdministrators.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatAdministrators.java index a77c0006..71a33493 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatAdministrators.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatAdministrators.java @@ -2,16 +2,22 @@ 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.ChatMember; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.ChatMember; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.ArrayList; -import java.util.Objects; /** * @author Ruben Bermudez @@ -22,33 +28,22 @@ import java.util.Objects; * If the chat is a group or a supergroup and no administrators were appointed, * only the creator will be returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetChatAdministrators extends BotApiMethod> { public static final String PATH = "getChatAdministrators"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public GetChatAdministrators() { - super(); - } - - public String getChatId() { - return chatId; - } - - public GetChatAdministrators setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public GetChatAdministrators setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -75,11 +70,4 @@ public class GetChatAdministrators extends BotApiMethod> { throw new TelegramApiValidationException("ChatId can't be empty", this); } } - - @Override - public String toString() { - return "GetChatAdministrators{" + - "chatId='" + chatId + '\'' + - '}'; - } } 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 7e54179e..d42252d5 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 @@ -2,15 +2,21 @@ 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.ChatMember; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.ChatMember; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez @@ -18,6 +24,13 @@ import java.util.Objects; * Use this method to get information about a member of a chat. * Returns a ChatMember object on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetChatMember extends BotApiMethod { public static final String PATH = "getChatMember"; @@ -25,38 +38,12 @@ public class GetChatMember extends BotApiMethod { private static final String USERID_FIELD = "user_id"; @JsonProperty(CHATID_FIELD) + @NonNull 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 - public GetChatMember() { - super(); - } - - public String getChatId() { - return chatId; - } - - public GetChatMember setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public GetChatMember setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public GetChatMember setUserId(Integer userId) { - this.userId = userId; - return this; - } - @Override public String getMethod() { return PATH; @@ -86,12 +73,4 @@ public class GetChatMember extends BotApiMethod { throw new TelegramApiValidationException("UserId can't be null", this); } } - - @Override - public String toString() { - return "GetChatMember{" + - "chatId='" + chatId + '\'' + - ", userId='" + userId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMembersCount.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMembersCount.java index 6461f195..f8ea4861 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMembersCount.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/GetChatMembersCount.java @@ -2,46 +2,42 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method to get the number of members in a chat. Returns Int on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetChatMembersCount extends BotApiMethod { public static final String PATH = "getChatMembersCount"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public GetChatMembersCount() { - super(); - } - - public String getChatId() { - return chatId; - } - - public GetChatMembersCount setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public GetChatMembersCount setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -68,11 +64,4 @@ public class GetChatMembersCount extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be empty", this); } } - - @Override - public String toString() { - return "GetChatMembersCount{" + - "chatId='" + chatId + '\'' + - '}'; - } } 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 b3b574a1..86ca18a8 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 @@ -3,7 +3,15 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration; import com.fasterxml.jackson.annotation.JsonIgnore; 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.exceptions.TelegramApiRequestException; @@ -13,9 +21,6 @@ import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.time.ZonedDateTime; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -28,6 +33,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * group. Otherwise members may only be removed by the group's creator or by the member that added * them. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class KickChatMember extends BotApiMethod { public static final String PATH = "kickchatmember"; @@ -36,72 +49,27 @@ public class KickChatMember extends BotApiMethod { private static final String UNTILDATE_FIELD = "until_date"; @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 @JsonProperty(UNTILDATE_FIELD) - private Integer untilDate; ///< 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 + 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 - public KickChatMember() { - super(); - } - - public KickChatMember(String chatId, Integer userId) { - this.chatId = checkNotNull(chatId); - this.userId = checkNotNull(userId); - } - - public KickChatMember(Long chatId, Integer userId) { - this.chatId = checkNotNull(chatId).toString(); - this.userId = checkNotNull(userId); - } - - - public String getChatId() { - return chatId; - } - - public KickChatMember setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public KickChatMember setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public KickChatMember setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public Integer getUntilDate() { - return untilDate; - } - - public KickChatMember setUntilDate(Integer untilDateInSeconds) { - this.untilDate = untilDateInSeconds; - return this; + @JsonIgnore + public void setUntilDateInstant(Instant instant) { + setUntilDate((int) instant.getEpochSecond()); } @JsonIgnore - public KickChatMember setUntilDate(Instant instant) { - return setUntilDate((int) instant.getEpochSecond()); + public void setUntilDateDateTime(ZonedDateTime date) { + setUntilDateInstant(date.toInstant()); } @JsonIgnore - public KickChatMember setUntilDate(ZonedDateTime date) { - return setUntilDate(date.toInstant()); - } - - public KickChatMember forTimePeriod(Duration duration) { - return setUntilDate(Instant.now().plusMillis(duration.toMillis())); + public void forTimePeriodDuration(Duration duration) { + setUntilDateInstant(Instant.now().plusMillis(duration.toMillis())); } @Override @@ -133,13 +101,4 @@ public class KickChatMember extends BotApiMethod { throw new TelegramApiValidationException("UserId can't be null", this); } } - - @Override - public String toString() { - return "KickChatMember{" + - "chatId='" + chatId + '\'' + - ", userId=" + userId + - ", untilDate=" + untilDate + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/LeaveChat.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/LeaveChat.java index ea4d9a9d..b3ac05a8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/LeaveChat.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/LeaveChat.java @@ -2,47 +2,42 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method for your bot to leave a group, supergroup or channel. Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class LeaveChat extends BotApiMethod { public static final String PATH = "leaveChat"; private static final String CHATID_FIELD = "chat_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) - public LeaveChat() { - super(); - } - - public String getChatId() { - return chatId; - } - - public LeaveChat setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public LeaveChat setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @Override public String getMethod() { return PATH; @@ -69,11 +64,4 @@ public class LeaveChat extends BotApiMethod { throw new TelegramApiValidationException("ChatId can't be null", this); } } - - @Override - public String toString() { - return "LeaveChat{" + - "chatId='" + chatId + '\'' + - '}'; - } } 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 94932ba9..ad8f5116 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 @@ -2,15 +2,21 @@ 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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -20,6 +26,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * Pass False for all boolean parameters to demote a user. Returns True on success. * */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PromoteChatMember extends BotApiMethod { public static final String PATH = "promoteChatMember"; @@ -33,137 +47,32 @@ public class PromoteChatMember extends BotApiMethod { private static final String CANRESTRICTMEMBERS_FIELD = "can_restrict_members"; 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"; @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 @JsonProperty(CANCHANGEINFORMATION_FIELD) - private Boolean canChangeInformation; ///< Pass True, if the administrator can change chat title, photo and other settings + private Boolean canChangeInformation; ///< Optional. Pass True, if the administrator can change chat title, photo and other settings @JsonProperty(CANPOSTMESSAGES_FIELD) - private Boolean canPostMessages; ///< Pass True, if the administrator can create channel posts, channels only + private Boolean canPostMessages; ///< Optional. Pass True, if the administrator can create channel posts, channels only @JsonProperty(CANEDITMESSAGES_FIELD) - private Boolean canEditMessages; ///< Pass True, if the administrator can edit messages of other users, channels only + private Boolean canEditMessages; ///< Optional. Pass True, if the administrator can edit messages of other users, channels only @JsonProperty(CANDELETEMESSAGES_FIELD) - private Boolean canDeleteMessages; ///< Pass True, if the administrator can delete messages of other users + private Boolean canDeleteMessages; ///< Optional. Pass True, if the administrator can delete messages of other users @JsonProperty(CANINVITEUSERS_FIELD) - private Boolean canInviteUsers; ///< Pass True, if the administrator can invite new users to the chat + private Boolean canInviteUsers; ///< Optional. Pass True, if the administrator can invite new users to the chat @JsonProperty(CANRESTRICTMEMBERS_FIELD) - private Boolean canRestrictMembers; ///< Pass True, if the administrator can restrict, ban or unban chat members + private Boolean canRestrictMembers; ///< Optional. Pass True, if the administrator can restrict, ban or unban chat members @JsonProperty(CANPINMESSAGES_FIELD) - private Boolean canPinMessages; ///< Pass True, if the administrator can pin messages + private Boolean canPinMessages; ///< Optional. Pass True, if the administrator can pin messages @JsonProperty(CANPROMOTEMEMBERS_FIELD) - private Boolean canPromoteMembers; ///< 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) - - public PromoteChatMember() { - super(); - } - - public PromoteChatMember(String chatId, Integer userId) { - this.chatId = checkNotNull(chatId); - this.userId = checkNotNull(userId); - } - - public PromoteChatMember(Long chatId, Integer userId) { - this.chatId = checkNotNull(chatId).toString(); - this.userId = checkNotNull(userId); - } - - public String getChatId() { - return chatId; - } - - public PromoteChatMember setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public PromoteChatMember setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public PromoteChatMember setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public Boolean getCanChangeInformation() { - return canChangeInformation; - } - - public PromoteChatMember setCanChangeInformation(Boolean canChangeInformation) { - this.canChangeInformation = canChangeInformation; - return this; - } - - public Boolean getCanPostMessages() { - return canPostMessages; - } - - public PromoteChatMember setCanPostMessages(Boolean canPostMessages) { - this.canPostMessages = canPostMessages; - return this; - } - - public Boolean getCanEditMessages() { - return canEditMessages; - } - - public PromoteChatMember setCanEditMessages(Boolean canEditMessages) { - this.canEditMessages = canEditMessages; - return this; - } - - public Boolean getCanDeleteMessages() { - return canDeleteMessages; - } - - public PromoteChatMember setCanDeleteMessages(Boolean canDeleteMessages) { - this.canDeleteMessages = canDeleteMessages; - return this; - } - - public Boolean getCanInviteUsers() { - return canInviteUsers; - } - - public PromoteChatMember setCanInviteUsers(Boolean canInviteUsers) { - this.canInviteUsers = canInviteUsers; - return this; - } - - public Boolean getCanRestrictMembers() { - return canRestrictMembers; - } - - public PromoteChatMember setCanRestrictMembers(Boolean canRestrictMembers) { - this.canRestrictMembers = canRestrictMembers; - return this; - } - - public Boolean getCanPinMessages() { - return canPinMessages; - } - - public PromoteChatMember setCanPinMessages(Boolean canPinMessages) { - this.canPinMessages = canPinMessages; - return this; - } - - public Boolean getCanPromoteMembers() { - return canPromoteMembers; - } - - public PromoteChatMember setCanPromoteMembers(Boolean canPromoteMembers) { - this.canPromoteMembers = canPromoteMembers; - return this; - } + 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 @Override public String getMethod() { @@ -195,20 +104,4 @@ public class PromoteChatMember extends BotApiMethod { throw new TelegramApiValidationException("UserId can't be null", this); } } - - @Override - public String toString() { - return "PromoteChatMember{" + - "chatId='" + chatId + '\'' + - ", userId=" + userId + - ", canChangeInformation=" + canChangeInformation + - ", canPostMessages=" + canPostMessages + - ", canEditMessages=" + canEditMessages + - ", canDeleteMessages=" + canDeleteMessages + - ", canInviteUsers=" + canInviteUsers + - ", canRestrictMembers=" + canRestrictMembers + - ", canPinMessages=" + canPinMessages + - ", canPromoteMembers=" + canPromoteMembers + - '}'; - } } 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 137c66bb..d4f8acee 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 @@ -3,6 +3,15 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration; import com.fasterxml.jackson.annotation.JsonIgnore; 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.ChatPermissions; @@ -13,9 +22,6 @@ import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.time.ZonedDateTime; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -26,6 +32,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * */ @SuppressWarnings("WeakerAccess") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class RestrictChatMember extends BotApiMethod { public static final String PATH = "restrictchatmember"; @@ -39,19 +53,11 @@ public class RestrictChatMember extends BotApiMethod { private static final String PERMISSIONS_FIELD = "permissions"; @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 - @JsonProperty(UNTILDATE_FIELD) - private Integer untilDate; ///< Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be banned forever - @JsonProperty(CANSENDMESSAGES_FIELD) - private Boolean canSendMessages; ///< Pass True, if the user can send text messages, contacts, locations and venues - @JsonProperty(CANSENDMEDIAMESSAGES_FIELD) - private Boolean canSendMediaMessages; ///< Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages - @JsonProperty(CANSENDOTHERMESSAGES_FIELD) - private Boolean canSendOtherMessages; ///< Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages - @JsonProperty(CANADDWEBPAGEPREVIEWS_FIELD) - private Boolean canAddWebPagePreviews; ///< Pass True, if the user may add web page previews to their messages, implies can_send_messages /** * Optional * Date when restrictions will be lifted for the user, unix time. @@ -59,76 +65,24 @@ public class RestrictChatMember extends BotApiMethod { * from the current time, they are considered to be restricted forever */ @JsonProperty(PERMISSIONS_FIELD) + @NonNull private ChatPermissions permissions; + @JsonProperty(UNTILDATE_FIELD) + private Integer untilDate; ///< Optional. Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be banned forever - public RestrictChatMember() { - super(); - } - - public RestrictChatMember(String chatId, Integer userId) { - this.chatId = checkNotNull(chatId); - this.userId = checkNotNull(userId); - } - - public RestrictChatMember(Long chatId, Integer userId) { - this.chatId = checkNotNull(chatId).toString(); - this.userId = checkNotNull(userId); - } - - public String getChatId() { - return chatId; - } - - public RestrictChatMember setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public RestrictChatMember setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public RestrictChatMember setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public Integer getUntilDate() { - return untilDate; - } - - public RestrictChatMember setUntilDate(Integer untilDateInSeconds) { - this.untilDate = untilDateInSeconds; - return this; + @JsonIgnore + public void setUntilDateInstant(Instant instant) { + setUntilDate((int) instant.getEpochSecond()); } @JsonIgnore - public RestrictChatMember setUntilDate(Instant instant) { - return setUntilDate((int) instant.getEpochSecond()); + public void setUntilDateDateTime(ZonedDateTime date) { + setUntilDateInstant(date.toInstant()); } @JsonIgnore - public RestrictChatMember setUntilDate(ZonedDateTime date) { - return setUntilDate(date.toInstant()); - } - - @JsonIgnore - public RestrictChatMember forTimePeriod(Duration duration) { - return setUntilDate(Instant.now().plusMillis(duration.toMillis())); - } - - public ChatPermissions getPermissions() { - return permissions; - } - - public void setPermissions(ChatPermissions permissions) { - this.permissions = permissions; + public void forTimePeriodDuration(Duration duration) { + setUntilDateInstant(Instant.now().plusMillis(duration.toMillis())); } @Override @@ -163,18 +117,4 @@ public class RestrictChatMember extends BotApiMethod { throw new TelegramApiValidationException("Permissions can't be empty", this); } } - - @Override - public String toString() { - return "RestrictChatMember{" + - "chatId='" + chatId + '\'' + - ", userId=" + userId + - ", untilDate=" + untilDate + - ", canSendMessages=" + canSendMessages + - ", canSendMediaMessages=" + canSendMediaMessages + - ", canSendOtherMessages=" + canSendOtherMessages + - ", canAddWebPagePreviews=" + canAddWebPagePreviews + - ", permissions=" + permissions + - '}'; - } } 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 c88a3d54..05e5c7ae 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 @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -18,6 +23,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use this method to set a custom title for an administrator in a supergroup promoted by the bot. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetChatAdministratorCustomTitle extends BotApiMethod { public static final String PATH = "setChatAdministratorCustomTitle"; @@ -26,65 +38,15 @@ public class SetChatAdministratorCustomTitle extends BotApiMethod { private static final String CUSTOMTITLE_FIELD = "custom_title"; @JsonProperty(CHATID_FIELD) + @NonNull 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 @JsonProperty(CUSTOMTITLE_FIELD) + @NonNull private String customTitle; ///< New custom title for the administrator; 0-16 characters, emoji are not allowed - public SetChatAdministratorCustomTitle() { - super(); - } - - public SetChatAdministratorCustomTitle(String chatId, Integer userId, String customTitle) { - super(); - this.chatId = checkNotNull(chatId); - this.userId = checkNotNull(userId); - this.customTitle = checkNotNull(customTitle); - } - - public SetChatAdministratorCustomTitle(Long chatId, Integer userId, String customTitle) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.userId = checkNotNull(userId); - this.customTitle = checkNotNull(customTitle); - } - - public String getChatId() { - return chatId; - } - - public SetChatAdministratorCustomTitle setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatAdministratorCustomTitle setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public SetChatAdministratorCustomTitle setUserId(Integer userId) { - checkNotNull(userId); - this.userId = userId; - return this; - } - - public String getCustomTitle() { - return customTitle; - } - - public SetChatAdministratorCustomTitle setCustomTitle(String customTitle) { - checkNotNull(customTitle); - this.customTitle = customTitle; - return this; - } - @Override public String getMethod() { return PATH; @@ -117,13 +79,4 @@ public class SetChatAdministratorCustomTitle extends BotApiMethod { throw new TelegramApiValidationException("CustomTitle can't be null", this); } } - - @Override - public String toString() { - return "SetChatDescription{" + - "chatId='" + chatId + '\'' + - "userId='" + userId + '\'' + - ", customTitle='" + customTitle + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatDescription.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatDescription.java index fc2a3754..57c5ec35 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatDescription.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatDescription.java @@ -2,15 +2,21 @@ 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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -19,6 +25,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class SetChatDescription extends BotApiMethod { public static final String PATH = "setChatDescription"; @@ -26,50 +40,10 @@ public class SetChatDescription extends BotApiMethod { private static final String DESCRIPTION_FIELD = "description"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(DESCRIPTION_FIELD) - private String description; ///< New chat description, 0-255 characters - - public SetChatDescription() { - super(); - } - - public SetChatDescription(String chatId, String description) { - super(); - this.chatId = checkNotNull(chatId); - this.description = checkNotNull(description); - } - - public SetChatDescription(Long chatId, String description) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.description = checkNotNull(description); - } - - public String getChatId() { - return chatId; - } - - public SetChatDescription setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatDescription setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getDescription() { - return description; - } - - public SetChatDescription setDescription(String description) { - Objects.requireNonNull(description); - this.description = description; - return this; - } + private String description; ///< Optional. New chat description, 0-255 characters @Override public String getMethod() { @@ -100,12 +74,4 @@ public class SetChatDescription extends BotApiMethod { throw new TelegramApiValidationException("Description can't be null", this); } } - - @Override - public String toString() { - return "SetChatDescription{" + - "chatId='" + chatId + '\'' + - ", description='" + description + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPermissions.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPermissions.java index 790c172d..f92a7791 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPermissions.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPermissions.java @@ -2,6 +2,14 @@ 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.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.ChatPermissions; @@ -9,9 +17,6 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -20,6 +25,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The bot must be an administrator in the group or a supergroup * for this to work and must have the can_restrict_members admin rights. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetChatPermissions extends BotApiMethod { public static final String PATH = "setChatPermissions"; @@ -27,51 +39,12 @@ public class SetChatPermissions extends BotApiMethod { private static final String PERMISSIONS_FIELD = "permissions"; @JsonProperty(CHAT_ID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) @JsonProperty(PERMISSIONS_FIELD) + @NonNull private ChatPermissions permissions; ///< New default chat permissions - public SetChatPermissions() { - super(); - } - - public SetChatPermissions(String chatId, ChatPermissions permissions) { - super(); - this.chatId = checkNotNull(chatId); - this.permissions = checkNotNull(permissions); - } - - public SetChatPermissions(Long chatId, ChatPermissions permissions) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.permissions = checkNotNull(permissions); - } - - public String getChatId() { - return chatId; - } - - public SetChatPermissions setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatPermissions setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public ChatPermissions getPermissions() { - return permissions; - } - - public SetChatPermissions setPermissions(ChatPermissions permissions) { - Objects.requireNonNull(permissions); - this.permissions = permissions; - return this; - } - @Override public String getMethod() { return PATH; @@ -101,12 +74,4 @@ public class SetChatPermissions extends BotApiMethod { throw new TelegramApiValidationException("Permissions can't be null", this); } } - - @Override - public String toString() { - return "SetChatPermissions{" + - "chatId='" + chatId + '\'' + - ", permissions=" + permissions + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPhoto.java index 5d47a4f1..f8497edd 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatPhoto.java @@ -1,17 +1,21 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration; 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -22,87 +26,23 @@ import static com.google.common.base.Preconditions.checkNotNull; * * @apiNote In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetChatPhoto extends PartialBotApiMethod { public static final String PATH = "setChatPhoto"; public static final String CHATID_FIELD = "chat_id"; public static final String PHOTO_FIELD = "photo"; + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) - private String photoName; ///< Name of new chat photo - private InputStream photoStream; ///< New chat photo as InputStream, uploaded using multipart/form-data - private File photo; ///< New chat photo as File, uploaded using multipart/form-data - - public SetChatPhoto() { - super(); - } - - public SetChatPhoto(String chatId, File photo) { - super(); - this.chatId = checkNotNull(chatId); - this.photo = checkNotNull(photo); - } - - public SetChatPhoto(String chatId, InputStream photoStream, String photoName) { - super(); - this.chatId = checkNotNull(chatId); - this.photoStream = checkNotNull(photoStream); - this.photoName = checkNotNull(photoName); - } - - - public SetChatPhoto(Long chatId, File photo) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.photo = checkNotNull(photo); - } - - public SetChatPhoto(Long chatId, InputStream photoStream, String photoName) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.photoStream = checkNotNull(photoStream); - this.photoName = checkNotNull(photoName); - } - - public String getChatId() { - return chatId; - } - - public SetChatPhoto setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatPhoto setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public SetChatPhoto setPhoto(File file) { - this.photo = file; - return this; - } - - public SetChatPhoto setNewPhoto(String photoName, InputStream inputStream) { - Objects.requireNonNull(photoName, "photoName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.photoName = photoName; - this.photoStream = inputStream; - return this; - } - - public String getPhotoName() { - return photoName; - } - - public InputStream getPhotoStream() { - return photoStream; - } - - public File getPhoto() { - return photo; - } + @NonNull + private InputFile photo; ///< New chat photo as InputStream, uploaded using multipart/form-data @Override public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { @@ -124,22 +64,8 @@ public class SetChatPhoto extends PartialBotApiMethod { if (chatId == null || chatId.isEmpty()) { throw new TelegramApiValidationException("ChatId can't be empty", this); } - if (photo == null) { - if (photoStream == null) { - throw new TelegramApiValidationException("Photo parameter is required", this); - } else if (photoName == null || photoName.isEmpty()){ - throw new TelegramApiValidationException("Photo name can't be empty", this); - } + if (photo == null || !photo.isNew()) { + throw new TelegramApiValidationException("Photo parameter is required and must be a new file to upload", this); } } - - @Override - public String toString() { - return "SetChatPhoto{" + - "chatId='" + chatId + '\'' + - ", photoName='" + photoName + '\'' + - ", photoStream=" + photoStream + - ", photo=" + photo + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatStickerSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatStickerSet.java index 12044405..6aefd939 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatStickerSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatStickerSet.java @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -20,6 +25,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetChatStickerSet extends BotApiMethod { public static final String PATH = "setChatStickerSet"; @@ -27,50 +39,12 @@ public class SetChatStickerSet extends BotApiMethod { private static final String STICKERSETNAME_FIELD = "sticker_set_name"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(STICKERSETNAME_FIELD) + @NonNull private String stickerSetName; ///< Name of the sticker set to be set as the group sticker set - public SetChatStickerSet() { - super(); - } - - public SetChatStickerSet(String chatId, String stickerSetName) { - super(); - this.chatId = checkNotNull(chatId); - this.stickerSetName = checkNotNull(stickerSetName); - } - - public SetChatStickerSet(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public SetChatStickerSet setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatStickerSet setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getStickerSetName() { - return stickerSetName; - } - - public SetChatStickerSet setStickerSetName(String stickerSetName) { - Objects.requireNonNull(stickerSetName); - this.stickerSetName = stickerSetName; - return this; - } - @Override public String getMethod() { return PATH; @@ -100,12 +74,4 @@ public class SetChatStickerSet extends BotApiMethod { throw new TelegramApiValidationException("StickerSetName can't be empty", this); } } - - @Override - public String toString() { - return "SetChatStickerSet{" + - "chatId='" + chatId + '\'' + - ", stickerSetName='" + stickerSetName + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatTitle.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatTitle.java index aad15419..5138a561 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatTitle.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/SetChatTitle.java @@ -2,15 +2,20 @@ 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -21,6 +26,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * * @apiNote In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetChatTitle extends BotApiMethod { public static final String PATH = "setChatTitle"; @@ -28,51 +40,12 @@ public class SetChatTitle extends BotApiMethod { private static final String TITLE_FIELD = "title"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Required. New chat title, 1-255 characters - public SetChatTitle() { - super(); - } - - public SetChatTitle(String chatId, String title) { - super(); - this.chatId = checkNotNull(chatId); - this.title = checkNotNull(title); - } - - public SetChatTitle(Long chatId, String title) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.title = checkNotNull(title); - } - - public String getChatId() { - return chatId; - } - - public SetChatTitle setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SetChatTitle setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getTitle() { - return title; - } - - public SetChatTitle setTitle(String title) { - Objects.requireNonNull(title); - this.title = title; - return this; - } - @Override public String getMethod() { return PATH; @@ -102,12 +75,4 @@ public class SetChatTitle extends BotApiMethod { throw new TelegramApiValidationException("Title can't be empty", this); } } - - @Override - public String toString() { - return "SetChatTitle{" + - "chatId='" + chatId + '\'' + - ", title='" + title + '\'' + - '}'; - } } 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 adfd5202..f3b31ea1 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 @@ -2,74 +2,58 @@ 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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez * @version 1.0 - * Use this method to unban a previously kicked user in a supergroup. The user will not - * return to the group automatically, but will be able to join via link, etc. The bot must be an - * administrator in the group for this to work. Returns True on success. + * Use this method to unban a previously kicked user in a supergroup or channel. + * Returns True on success. + * + * @apiNote The user will not return to the group or channel automatically, but will be able to join via link, etc. + * @apiNote The bot must be an administrator for this to work. + * @apiNote By default, this method guarantees that after the call the user is not a member of the chat, + * but will be able to join it. + * @apiNote So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class UnbanChatMember extends BotApiMethod { public static final String PATH = "unbanchatmember"; private static final String CHATID_FIELD = "chat_id"; - private static final String USER_ID_FIELD = "user_id"; + private static final String USERID_FIELD = "user_id"; + private static final String ONLYISBANNED_FIELD = "only_if_banned"; @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) + @JsonProperty(USERID_FIELD) + @NonNull private Integer userId; ///< Required. Unique identifier of the target user + @JsonProperty(ONLYISBANNED_FIELD) + private Boolean onlyIfBanned; ///< Optional. Do nothing if the user is not banned - public UnbanChatMember() { - super(); - } - - public UnbanChatMember(String chatId, Integer userId) { - super(); - this.chatId = checkNotNull(chatId); - this.userId = checkNotNull(userId); - } - - public UnbanChatMember(Long chatId, Integer userId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.userId = checkNotNull(userId); - } - - public String getChatId() { - return chatId; - } - - public UnbanChatMember setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public UnbanChatMember setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getUserId() { - return userId; - } - - public UnbanChatMember setUserId(Integer userId) { - this.userId = userId; - return this; - } @Override public String getMethod() { @@ -100,12 +84,4 @@ public class UnbanChatMember extends BotApiMethod { throw new TelegramApiValidationException("UserId can't be null", this); } } - - @Override - public String toString() { - return "UnbanChatMember{" + - "chatId='" + chatId + '\'' + - ", userId='" + userId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/PinChatMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/PinChatMessage.java index cfbf0bd1..dd5c5ae0 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/PinChatMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/PinChatMessage.java @@ -2,24 +2,39 @@ package org.telegram.telegrambots.meta.api.methods.pinnedmessages; 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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez * @version 3.1 - * Use this method to pin a message in a group, a supergroup or a channel. - * The bot must be an administrator in the chat for this to work and must - * have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ - * admin right in the channel. Returns True on success. + * Use this method to add a message to the list of pinned messages in a chat. + * Returns True on success. + * + * @apiNote If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must + * have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PinChatMessage extends BotApiMethod { public static final String PATH = "pinChatMessage"; @@ -28,8 +43,10 @@ public class PinChatMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(MESSAGEID_FIELD) + @NonNull private Integer messageId; ///< Required. Identifier of a message to pin /** * Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. @@ -38,56 +55,6 @@ public class PinChatMessage extends BotApiMethod { @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; - public PinChatMessage() { - super(); - } - - public PinChatMessage(String chatId, Integer messageId) { - super(); - this.chatId = checkNotNull(chatId); - this.messageId = checkNotNull(messageId); - } - - public PinChatMessage(Long chatId, Integer messageId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.messageId = checkNotNull(messageId); - } - - public String getChatId() { - return chatId; - } - - public PinChatMessage setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public PinChatMessage setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public PinChatMessage setMessageId(Integer messageId) { - Objects.requireNonNull(messageId); - this.messageId = messageId; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public PinChatMessage setDisableNotification(Boolean disableNotification) { - this.disableNotification = disableNotification; - return this; - } - @Override public String getMethod() { return PATH; @@ -117,13 +84,4 @@ public class PinChatMessage extends BotApiMethod { throw new TelegramApiValidationException("MessageId parameter can't be null", this); } } - - @Override - public String toString() { - return "PinChatMessage{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", disableNotification=" + disableNotification + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinAllChatMessages.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinAllChatMessages.java new file mode 100644 index 00000000..e63ee5a7 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinAllChatMessages.java @@ -0,0 +1,72 @@ +package org.telegram.telegrambots.meta.api.methods.pinnedmessages; + +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.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.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 3.1 + * Use this method to clear the list of pinned messages in a chat. + * Returns True on success. + * + * @apiNote If the chat is not a private chat, the bot must be an administrator in the chat for this to + * work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin + * right in a channel. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class UnpinAllChatMessages extends BotApiMethod { + public static final String PATH = "unpinAllChatMessages"; + + private static final String CHATID_FIELD = "chat_id"; + + @JsonProperty(CHATID_FIELD) + @NonNull + private String chatId; ///< Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + + @Override + public String getMethod() { + return PATH; + } + + @Override + public Boolean 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 unpinning chat message", 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 parameter can't be empty", this); + } + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinChatMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinChatMessage.java index b489a2f4..c5a44bce 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinChatMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/pinnedmessages/UnpinChatMessage.java @@ -2,60 +2,57 @@ package org.telegram.telegrambots.meta.api.methods.pinnedmessages; 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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez * @version 3.1 - * Use this method to unpin a message in a group, a supergroup or a channel. - * The bot must be an administrator in the chat for this to work and must have - * the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ - * admin right in the channel. Returns True on success. + * Use this method to remove a message from the list of pinned messages in a chat. + * Returns True on success. + * + * @apiNote If the chat is not a private chat, the bot must be an administrator in the chat for this to work + * and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' + * admin right in a channel. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class UnpinChatMessage extends BotApiMethod { public static final String PATH = "unpinChatMessage"; private static final String CHATID_FIELD = "chat_id"; + private static final String MESSAGEID_FIELD = "message_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - - public UnpinChatMessage() { - super(); - } - - public UnpinChatMessage(String chatId) { - super(); - this.chatId = checkNotNull(chatId); - } - - public UnpinChatMessage(Long chatId) { - super(); - this.chatId = checkNotNull(chatId).toString(); - } - - public String getChatId() { - return chatId; - } - - public UnpinChatMessage setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public UnpinChatMessage setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } + /** + * Optional. + * Identifier of a message to unpin. + * + * @apiNote If not specified, the most recent pinned message (by send date) will be unpinned. + */ + @JsonProperty(MESSAGEID_FIELD) + private Integer messageId; @Override public String getMethod() { @@ -83,11 +80,4 @@ public class UnpinChatMessage extends BotApiMethod { throw new TelegramApiValidationException("ChatId parameter can't be empty", this); } } - - @Override - public String toString() { - return "UnpinChatMessage{" + - "chatId='" + chatId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/SendPoll.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/SendPoll.java index 8a6dd3a9..b4c6e24a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/SendPoll.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/SendPoll.java @@ -3,19 +3,26 @@ package org.telegram.telegrambots.meta.api.methods.polls; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +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.Message; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.ArrayList; import java.util.List; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -25,6 +32,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * * On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendPoll extends BotApiMethod { public static final String PATH = "sendPoll"; @@ -43,17 +58,23 @@ public class SendPoll extends BotApiMethod { private static final String CLOSEDATE_FIELD = "close_date"; private static final String EXPLANATION_FIELD = "explanation"; private static final String EXPLANATIONPARSEMODE_FIELD = "explanation_parse_mode"; + private static final String EXPLANATION_ENTITIES_FIELD = "explanation_entities"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; /** * Unique identifier for the target chat or username of the target channel (in the format @channelusername). * A native poll can't be sent to a private chat. */ @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(QUESTION_FIELD) - private String question; ///< Poll question, 1-255 characters + @NonNull + private String question; ///< Poll question, 1-300 characters @JsonProperty(OPTIONS_FIELD) - private List options = new ArrayList<>(); ///< List of answer options, 2-10 strings 1-100 characters each + @Singular + @NonNull + private List options; ///< List of answer options, 2-10 strings 1-100 characters each @JsonProperty(ISANONYMOUS_FIELD) private Boolean isAnonymous; ///< Optional True, if the poll needs to be anonymous, defaults to True @JsonProperty(TYPE_FIELD) @@ -79,168 +100,18 @@ public class SendPoll extends BotApiMethod { private String explanation; ///< Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing @JsonProperty(EXPLANATIONPARSEMODE_FIELD) private String explanationParseMode; ///< Optional. Mode for parsing entities in the explanation. See formatting options for more details. + @JsonProperty(EXPLANATION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the poll explanation, which can be specified instead of parse_mode + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendPoll() { - super(); - } - - public SendPoll(String chatId, String question, List options) { - this.chatId = checkNotNull(chatId); - this.question = checkNotNull(question); - this.options = checkNotNull(options); - } - - public SendPoll(Long chatId, String question, List options) { - this.chatId = checkNotNull(chatId).toString(); - this.question = checkNotNull(question); - this.options = checkNotNull(options); - } - - public String getChatId() { - return chatId; - } - - public SendPoll setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendPoll setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getQuestion() { - return question; - } - - public SendPoll setQuestion(String question) { - this.question = question; - return this; - } - - public List getOptions() { - return options; - } - - public SendPoll setOptions(List options) { - this.options = options; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendPoll setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendPoll setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendPoll enableNotification() { + public void enableNotification() { this.disableNotification = null; - return this; } - public SendPoll disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public Boolean getAnonymous() { - return isAnonymous; - } - - public SendPoll setAnonymous(Boolean anonymous) { - isAnonymous = anonymous; - return this; - } - - public String getType() { - return type; - } - - public SendPoll setType(String type) { - this.type = type; - return this; - } - - public Boolean getAllowMultipleAnswers() { - return allowMultipleAnswers; - } - - public SendPoll setAllowMultipleAnswers(Boolean allowMultipleAnswers) { - this.allowMultipleAnswers = allowMultipleAnswers; - return this; - } - - public Integer getCorrectOptionId() { - return correctOptionId; - } - - public SendPoll setCorrectOptionId(Integer correctOptionId) { - this.correctOptionId = correctOptionId; - return this; - } - - public Boolean getClosed() { - return isClosed; - } - - public SendPoll setClosed(Boolean closed) { - isClosed = closed; - return this; - } - - public Integer getOpenPeriod() { - return openPeriod; - } - - public SendPoll setOpenPeriod(Integer openPeriod) { - this.openPeriod = openPeriod; - return this; - } - - public Integer getCloseDate() { - return closeDate; - } - - public SendPoll setCloseDate(Integer closeDate) { - this.closeDate = closeDate; - return this; - } - - public String getExplanation() { - return explanation; - } - - public SendPoll setExplanation(String explanation) { - this.explanation = explanation; - return this; - } - - public String getExplanationParseMode() { - return explanationParseMode; - } - - public SendPoll setExplanationParseMode(String explanationParseMode) { - this.explanationParseMode = explanationParseMode; - return this; } @Override @@ -287,57 +158,11 @@ public class SendPoll extends BotApiMethod { if (options.parallelStream().anyMatch(x -> x.isEmpty() || x.length() > 100)) { throw new TelegramApiValidationException("Options parameter values must be between 1 and 100 chars length", this); } + if (explanationParseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SendPoll)) return false; - SendPoll sendPoll = (SendPoll) o; - return Objects.equals(chatId, sendPoll.chatId) && - Objects.equals(question, sendPoll.question) && - Objects.equals(options, sendPoll.options) && - Objects.equals(isAnonymous, sendPoll.isAnonymous) && - Objects.equals(type, sendPoll.type) && - Objects.equals(allowMultipleAnswers, sendPoll.allowMultipleAnswers) && - Objects.equals(correctOptionId, sendPoll.correctOptionId) && - Objects.equals(isClosed, sendPoll.isClosed) && - Objects.equals(disableNotification, sendPoll.disableNotification) && - Objects.equals(replyToMessageId, sendPoll.replyToMessageId) && - Objects.equals(replyMarkup, sendPoll.replyMarkup) && - Objects.equals(openPeriod, sendPoll.openPeriod) && - Objects.equals(closeDate, sendPoll.closeDate) && - Objects.equals(explanation, sendPoll.explanation) && - Objects.equals(explanationParseMode, sendPoll.explanationParseMode); - } - - @Override - public int hashCode() { - return Objects.hash(chatId, question, options, isAnonymous, type, allowMultipleAnswers, correctOptionId, isClosed, - disableNotification, replyToMessageId, replyMarkup, openPeriod, closeDate, explanation, explanationParseMode); - } - - @Override - public String toString() { - return "SendPoll{" + - "chatId='" + chatId + '\'' + - ", question='" + question + '\'' + - ", options=" + options + - ", isAnonymous=" + isAnonymous + - ", type='" + type + '\'' + - ", allowMultipleAnswers=" + allowMultipleAnswers + - ", correctOptionId=" + correctOptionId + - ", isClosed=" + isClosed + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", openPeriod=" + openPeriod + - ", closeDate=" + closeDate + - ", explanation='" + explanation + '\'' + - ", explanationParseMode='" + explanationParseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/StopPoll.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/StopPoll.java index 915e5de5..457c852b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/StopPoll.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/polls/StopPoll.java @@ -2,16 +2,21 @@ package org.telegram.telegrambots.meta.api.methods.polls; 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.polls.Poll; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.polls.Poll; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -20,6 +25,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * * On success, the stopped Poll with the final results is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class StopPoll extends BotApiMethod { public static final String PATH = "stopPoll"; @@ -27,48 +39,12 @@ public class StopPoll extends BotApiMethod { private static final String MESSAGEID_FIELD = "message_id"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(MESSAGEID_FIELD) + @NonNull private Integer messageId; ///< Identifier of the original message with the poll - public StopPoll() { - super(); - } - - public StopPoll(String chatId, Integer messageId) { - this.chatId = checkNotNull(chatId); - this.messageId = checkNotNull(messageId); - } - - public StopPoll(Long chatId, Integer messageId) { - this.chatId = checkNotNull(chatId).toString(); - this.messageId = checkNotNull(messageId); - } - - public String getChatId() { - return chatId; - } - - public StopPoll setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public StopPoll setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public StopPoll setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - @Override public String getMethod() { return PATH; @@ -98,31 +74,4 @@ public class StopPoll extends BotApiMethod { throw new TelegramApiValidationException("Message Id parameter can't be empty", this); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof StopPoll)) { - return false; - } - StopPoll sendMessage = (StopPoll) o; - return Objects.equals(chatId, sendMessage.chatId) - && Objects.equals(messageId, sendMessage.messageId) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - chatId, - messageId); - } - - @Override - public String toString() { - return "StopPoll{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAnimation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAnimation.java index e98e6da8..6d847a68 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAnimation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendAnimation.java @@ -1,18 +1,27 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; +import java.util.List; /** * @author Ruben Bermudez @@ -22,6 +31,14 @@ import java.util.Objects; * * Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendAnimation extends PartialBotApiMethod { public static final String PATH = "sendAnimation"; @@ -36,14 +53,17 @@ public class SendAnimation extends PartialBotApiMethod { public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String THUMB_FIELD = "thumb"; + public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; - + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) /** * Animation to send. Pass a file_id as String to send an animation that exists on the * Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation * from the Internet, or upload a new animation using multipart/form-data. */ + @NonNull private InputFile animation; private Integer duration; ///< Optional. Duration of sent animation in seconds private String caption; ///< Optional. Animation caption (may also be used when resending videos by file_id). @@ -54,6 +74,7 @@ public class SendAnimation extends PartialBotApiMethod { private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard 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. /** + * Optional. * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. * A thumbnail’s width and height should not exceed 320. * Ignored if the file is not uploaded using multipart/form-data. @@ -61,137 +82,16 @@ public class SendAnimation extends PartialBotApiMethod { * if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendAnimation() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendAnimation setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public InputFile getAnimation() { - return animation; - } - - public SendAnimation setAnimation(String animation) { - this.animation = new InputFile(animation); - return this; - } - - public SendAnimation setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getDuration() { - return duration; - } - - public SendAnimation setDuration(Integer duration) { - this.duration = duration; - return this; - } - - public String getCaption() { - return caption; - } - - public SendAnimation setCaption(String caption) { - this.caption = caption; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendAnimation setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendAnimation setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendAnimation enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendAnimation disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public Integer getWidth() { - return width; - } - - public SendAnimation setWidth(Integer width) { - this.width = width; - return this; - } - - public Integer getHeight() { - return height; - } - - public SendAnimation setHeight(Integer height) { - this.height = height; - return this; - } - - public SendAnimation setAnimation(File file) { - this.animation = new InputFile(file, file.getName()); - return this; - } - - public SendAnimation setAnimation(String animationName, InputStream inputStream) { - Objects.requireNonNull(animationName, "animationName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.animation = new InputFile(inputStream, animationName); - return this; - } - - public SendAnimation setAnimation(InputFile animation) { - Objects.requireNonNull(animation, "animation cannot be null!"); - this.animation = animation; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendAnimation setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public SendAnimation setThumb(InputFile thumb) { - this.thumb = thumb; - return this; } @Override @@ -219,6 +119,10 @@ public class SendAnimation extends PartialBotApiMethod { throw new TelegramApiValidationException("Animation parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } + animation.validate(); if (replyMarkup != null) { @@ -228,20 +132,4 @@ public class SendAnimation extends PartialBotApiMethod { thumb.validate(); } } - - @Override - public String toString() { - return "SendAnimation{" + "chatId='" + chatId + '\'' + - ", animation=" + animation + - ", duration=" + duration + - ", caption='" + caption + '\'' + - ", width=" + width + - ", height=" + height + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - ", thumb=" + thumb + - '}'; - } } 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 8fe312e8..1aca6cff 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 @@ -1,18 +1,27 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; +import java.util.List; /** * @author Ruben Bermudez @@ -21,8 +30,16 @@ import java.util.Objects; * Telegram clients to display them in the music player. Your audio must be in an .mp3 format. On * success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in * size, this limit may be changed in the future. - * @note For sending voice notes, use sendVoice method instead. + * @apiNote For sending voice notes, use sendVoice method instead. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendAudio extends PartialBotApiMethod { public static final String PATH = "sendaudio"; @@ -37,9 +54,14 @@ public class SendAudio extends PartialBotApiMethod { public static final String CAPTION_FIELD = "caption"; public static final String PARSEMODE_FIELD = "parse_mode"; public static final String THUMB_FIELD = "thumb"; + 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 private InputFile audio; ///< Audio file to send. file_id as String to resend an audio that is already on the Telegram servers or Url to upload it private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. @@ -47,8 +69,9 @@ public class SendAudio extends PartialBotApiMethod { private String performer; ///< Optional. Performer of sent audio 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; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. /** + * Optional. * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. * A thumbnail’s width and height should not exceed 320. * Ignored if the file is not uploaded using multipart/form-data. @@ -56,149 +79,16 @@ public class SendAudio extends PartialBotApiMethod { * “attach://” if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendAudio() { - super(); - } - - public Integer getDuration() { - return this.duration; - } - - public SendAudio setDuration(Integer duration) { - this.duration = duration; - return this; - } - - public String getChatId() { - return chatId; - } - - public SendAudio setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendAudio setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public InputFile getAudio() { - return audio; - } - - /** - * Use this method to set the audio to an audio existing in Telegram system - * - * @param audio File_id of the audio to send - * @note The file_id must have already been received or sent by your bot - */ - public SendAudio setAudio(String audio) { - this.audio = new InputFile(audio); - return this; - } - - /** - * Use this method to set the audio to a new file - * - * @param file New audio file - */ - public SendAudio setAudio(File file) { - Objects.requireNonNull(file, "file cannot be null!"); - this.audio = new InputFile(file, file.getName()); - return this; - } - - public SendAudio setAudio(String audioName, InputStream inputStream) { - Objects.requireNonNull(audioName, "audioName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.audio = new InputFile(inputStream, audioName); - return this; - } - - public SendAudio setAudio(InputFile audio) { - Objects.requireNonNull(audio, "audio cannot be null!"); - this.audio = audio; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendAudio setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendAudio setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getPerformer() { - return performer; - } - - public SendAudio setPerformer(String performer) { - this.performer = performer; - return this; - } - - public String getTitle() { - return title; - } - - public SendAudio setTitle(String title) { - this.title = title; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendAudio enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendAudio disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getCaption() { - return caption; - } - - public SendAudio setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendAudio setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public SendAudio setThumb(InputFile thumb) { - this.thumb = thumb; - return this; } @Override @@ -226,6 +116,10 @@ public class SendAudio extends PartialBotApiMethod { throw new TelegramApiValidationException("Audio parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } + audio.validate(); if (thumb != null) { @@ -236,21 +130,4 @@ public class SendAudio extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendAudio{" + - "duration=" + duration + - ", chatId='" + chatId + '\'' + - ", audio=" + audio + - ", replyToMessageId=" + replyToMessageId + - ", disableNotification=" + disableNotification + - ", replyMarkup=" + replyMarkup + - ", performer='" + performer + '\'' + - ", title='" + title + '\'' + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - ", thumb=" + thumb + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendChatAction.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendChatAction.java index 66cab9ec..f1eef0b3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendChatAction.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendChatAction.java @@ -3,7 +3,14 @@ package org.telegram.telegrambots.meta.api.methods.send; import com.fasterxml.jackson.annotation.JsonIgnore; 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.ActionType; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.objects.ApiResponse; @@ -11,9 +18,6 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -22,6 +26,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram * clients clear its typing status). */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendChatAction extends BotApiMethod { public static final String PATH = "sendChatAction"; @@ -30,6 +41,7 @@ public class SendChatAction extends BotApiMethod { private static final String ACTION_FIELD = "action"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) /** * Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, @@ -38,46 +50,17 @@ public class SendChatAction extends BotApiMethod { * record_video_note or upload_video_note for video notes. */ @JsonProperty(ACTION_FIELD) + @NonNull private String action; - public SendChatAction() { - super(); - } - - public SendChatAction(String chatId, String action) { - this.chatId = checkNotNull(chatId); - this.action = checkNotNull(action); - } - - public SendChatAction(Long chatId, String action) { - this.chatId = checkNotNull(chatId).toString(); - this.action = checkNotNull(action); - } - - public String getChatId() { - return chatId; - } - @JsonIgnore - public ActionType getAction() { + public ActionType getActionType() { return ActionType.get(action); } - public SendChatAction setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendChatAction setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - @JsonIgnore - public SendChatAction setAction(ActionType action) { + public void setAction(ActionType action) { this.action = action.toString(); - return this; } @Override @@ -109,12 +92,4 @@ public class SendChatAction extends BotApiMethod { throw new TelegramApiValidationException("Action parameter can't be empty", this); } } - - @Override - public String toString() { - return "SendChatAction{" + - "chatId='" + chatId + '\'' + - ", action='" + action + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendContact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendContact.java index 2b9a9604..a81b2000 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendContact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendContact.java @@ -2,16 +2,23 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez @@ -19,6 +26,14 @@ import java.util.Objects; * Use this method to send information about user contact. On success, the sent Message is * returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendContact extends BotApiMethod { public static final String PATH = "sendContact"; @@ -30,12 +45,16 @@ public class SendContact extends BotApiMethod { private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; private static final String VCARD_FIELD = "vcard"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(PHONE_NUMBER_FIELD) + @NonNull private String phoneNumber; ///< User's phone number @JsonProperty(FIRST_NAME_FIELD) + @NonNull private String firstName; ///< User's first name @JsonProperty(LAST_NAME_FIELD) private String lastName; ///< Optional. User's last name @@ -47,91 +66,15 @@ public class SendContact extends BotApiMethod { private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard @JsonProperty(VCARD_FIELD) private String vCard; ///< Optional. Additional data about the contact in the form of a vCard + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendContact() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendContact setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendContact setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendContact setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendContact setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendContact enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendContact disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public SendContact setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public String getFirstName() { - return firstName; - } - - public SendContact setFirstName(String firstName) { - this.firstName = firstName; - return this; - } - - public String getLastName() { - return lastName; - } - - public SendContact setLastName(String lastName) { - this.lastName = lastName; - return this; - } - - public String getvCard() { - return vCard; - } - - public void setvCard(String vCard) { - this.vCard = vCard; } @Override @@ -169,18 +112,4 @@ public class SendContact extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendContact{" + - "chatId='" + chatId + '\'' + - ", phoneNumber='" + phoneNumber + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", vCard='" + vCard + '\'' + - '}'; - } } 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 a81c0fe4..f18f455b 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 @@ -2,6 +2,15 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; @@ -19,8 +28,16 @@ import java.util.List; * @version 4.7 * Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendDice extends BotApiMethod { - private static final List VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("\uD83C\uDFB2", "\uD83C\uDFAF", "\uD83C\uDFC0")); + private static final List VALIDEMOJIS = Collections.unmodifiableList(Arrays.asList("🎲", "🎯", "🏀", "⚽", "🎰")); public static final String PATH = "sendDice"; @@ -29,14 +46,19 @@ public class SendDice extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) /** - * Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, or “🏀”. - * Dice can have values 1-6 for “🎲” and “🎯”, and values 1-5 for “🏀”. Defauts to “🎲” + * 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 “🎰”. + * 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. @@ -44,64 +66,15 @@ public class SendDice extends BotApiMethod { private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional. Pass True, if the message should be sent even if the specified replied-to message is not found - public SendDice() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendDice setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendDice setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendDice setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendDice setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendDice enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendDice disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getEmoji() { - return emoji; - } - - public SendDice setEmoji(String emoji) { - this.emoji = emoji; - return this; } @Override @@ -130,21 +103,10 @@ public class SendDice extends BotApiMethod { throw new TelegramApiValidationException("ChatId parameter can't be empty", this); } if (emoji != null && !VALIDEMOJIS.contains(emoji)) { - throw new TelegramApiValidationException("Only \uD83C\uDFB2, \uD83C\uDFAF or \uD83C\uDFC0 are allowed in Emoji field ", this); + throw new TelegramApiValidationException("Only \"\uD83C\uDFB2\", \"\uD83C\uDFAF\", \"\uD83C\uDFC0\", \"⚽\", \"\uD83C\uDFB0\" are allowed in Emoji field ", this); } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendDice{" + - "chatId='" + chatId + '\'' + - ", emoji='" + emoji + '\'' + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java index fa87167f..deb094af 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendDocument.java @@ -1,24 +1,41 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; +import java.util.List; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send general files. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendDocument extends PartialBotApiMethod { public static final String PATH = "senddocument"; @@ -30,15 +47,20 @@ public class SendDocument extends PartialBotApiMethod { public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String PARSEMODE_FIELD = "parse_mode"; public static final String THUMB_FIELD = "thumb"; + public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to or Username for the channel to send the message to + @NonNull private InputFile document; ///< File file to send. file_id as String to resend a file that is already on the Telegram servers or Url to upload it private String caption; ///< Optional. Document caption (may also be used when resending documents by file_id), 0-200 characters private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. /** + * Optional. * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. * A thumbnail’s width and height should not exceed 320. * Ignored if the file is not uploaded using multipart/form-data. @@ -46,122 +68,16 @@ public class SendDocument extends PartialBotApiMethod { * if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendDocument() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendDocument setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendDocument setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public InputFile getDocument() { - return document; - } - - /** - * Use this method to set the document to an document existing in Telegram system - * - * @param document File_id of the document to send - * @note The file_id must have already been received or sent by your bot - */ - public SendDocument setDocument(String document) { - this.document = new InputFile(document); - return this; - } - - /** - * Use this method to set the document to a new file - * - * @param file New document file - */ - public SendDocument setDocument(File file) { - Objects.requireNonNull(file, "documentName cannot be null!"); - this.document = new InputFile(file, file.getName()); - return this; - } - - public SendDocument setDocument(InputFile document) { - Objects.requireNonNull(document, "document cannot be null!"); - this.document = document; - return this; - } - - public SendDocument setDocument(String documentName, InputStream inputStream) { - Objects.requireNonNull(documentName, "documentName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.document = new InputFile(inputStream, documentName); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendDocument setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendDocument enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendDocument disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getCaption() { - return caption; - } - - public SendDocument setCaption(String caption) { - this.caption = caption; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendDocument setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendDocument setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public SendDocument setThumb(InputFile thumb) { - this.thumb = thumb; - return this; } @Override @@ -189,6 +105,10 @@ public class SendDocument extends PartialBotApiMethod { throw new TelegramApiValidationException("Document parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } + document.validate(); if (thumb != null) { @@ -199,18 +119,4 @@ public class SendDocument extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendDocument{" + - "chatId='" + chatId + '\'' + - ", document=" + document + - ", caption='" + caption + '\'' + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - ", thumb=" + thumb + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendGame.java index 54838120..898fbc09 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendGame.java @@ -19,22 +19,37 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send a game. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendGame extends BotApiMethod { public static final String PATH = "sendGame"; @@ -43,10 +58,13 @@ public class SendGame extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(GAMESHORTNAME_FIELD) + @NonNull private String gameShortName; ///< Short name of the game @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. @@ -54,65 +72,15 @@ public class SendGame extends BotApiMethod { private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message @JsonProperty(REPLYMARKUP_FIELD) private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendGame() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendGame setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendGame setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendGame setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendGame setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendGame enableNotification() { + public void enableNotification() { this.disableNotification = null; - return this; } - public SendGame disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getGameShortName() { - return gameShortName; - } - - public SendGame setGameShortName(String gameShortName) { - this.gameShortName = gameShortName; - return this; } @Override @@ -147,15 +115,4 @@ public class SendGame extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendGame{" + - "chatId='" + chatId + '\'' + - ", gameShortName='" + gameShortName + '\'' + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendInvoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendInvoice.java index 5fa8debf..0e0da430 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendInvoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendInvoice.java @@ -2,10 +2,19 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; import org.telegram.telegrambots.meta.api.objects.payments.LabeledPrice; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -13,13 +22,19 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * Use this method to send an invoice. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendInvoice extends BotApiMethod { public static final String PATH = "sendinvoice"; @@ -46,22 +61,31 @@ public class SendInvoice extends BotApiMethod { private static final String REPLY_TO_MESSAGE_ID_FIELD = "reply_to_message_id"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PROVIDER_DATA_FIELD = "provider_data"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private Integer chatId; ///< Unique identifier for the target private chat @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Product name @JsonProperty(DESCRIPTION_FIELD) + @NonNull private String description; ///< Product description @JsonProperty(PAYLOAD_FIELD) + @NonNull private String payload; ///< Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. @JsonProperty(PROVIDER_TOKEN_FIELD) + @NonNull private String providerToken; ///< Payments provider token, obtained via Botfather @JsonProperty(START_PARAMETER_FIELD) + @NonNull private String startParameter; ///< Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter. @JsonProperty(CURRENCY_FIELD) + @NonNull private String currency; ///< 3-letter ISO 4217 currency code @JsonProperty(PRICES_FIELD) + @NonNull private List prices; ///< Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) /** * Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. @@ -97,250 +121,19 @@ public class SendInvoice extends BotApiMethod { /** * Optional. A JSON-serialized object for an inline keyboard. * - * @note If empty, one 'Buy title' button will be shown. If not empty, the first button must be a Pay button. + * @apiNote If empty, one 'Buy title' button will be shown. If not empty, the first button must be a Pay button. */ @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; /** * Optional JSON-encoded data about the invoice, which will be shared with the payment provider. * - * @note A detailed description of required fields should be provided by the payment provider. + * @apiNote A detailed description of required fields should be provided by the payment provider. */ @JsonProperty(PROVIDER_DATA_FIELD) private String providerData; - - /** - * Build an empty SendInvoice object - */ - public SendInvoice() { - super(); - } - - /** - * Build a SendInvoice object with empty parameters - * @param chatId Unique identifier for the target private chat - * @param title Product name - * @param description Product description - * @param payload Bot defined invoice payload, 1-128 bytes. - * @param providerToken Payments provider token - * @param startParameter Unique deep-linking parameter. - * @param currency 3-letter ISO 4217 currency code - * @param prices Price breakdown, a list of components - */ - public SendInvoice(Integer chatId, String title, String description, String payload, String providerToken, - String startParameter, String currency, List prices) { - this.chatId = checkNotNull(chatId); - this.title = checkNotNull(title); - this.description = checkNotNull(description); - this.payload = checkNotNull(payload); - this.providerToken = checkNotNull(providerToken); - this.startParameter = checkNotNull(startParameter); - this.currency = checkNotNull(currency); - this.prices = checkNotNull(prices); - } - - public Integer getChatId() { - return chatId; - } - - public SendInvoice setChatId(Integer chatId) { - this.chatId = checkNotNull(chatId); - return this; - } - - public String getTitle() { - return title; - } - - public SendInvoice setTitle(String title) { - this.title = checkNotNull(title); - return this; - } - - public String getDescription() { - return description; - } - - public SendInvoice setDescription(String description) { - this.description = checkNotNull(description); - return this; - } - - public String getPayload() { - return payload; - } - - public SendInvoice setPayload(String payload) { - this.payload = checkNotNull(payload); - return this; - } - - public String getProviderToken() { - return providerToken; - } - - public SendInvoice setProviderToken(String providerToken) { - this.providerToken = checkNotNull(providerToken); - return this; - } - - public String getStartParameter() { - return startParameter; - } - - public SendInvoice setStartParameter(String startParameter) { - this.startParameter = checkNotNull(startParameter); - return this; - } - - public String getCurrency() { - return currency; - } - - public SendInvoice setCurrency(String currency) { - this.currency = checkNotNull(currency); - return this; - } - - public List getPrices() { - return prices; - } - - public SendInvoice setPrices(List prices) { - this.prices = checkNotNull(prices); - return this; - } - - public String getPhotoUrl() { - return photoUrl; - } - - public SendInvoice setPhotoUrl(String photoUrl) { - this.photoUrl = photoUrl; - return this; - } - - public Integer getPhotoSize() { - return photoSize; - } - - public SendInvoice setPhotoSize(Integer photoSize) { - this.photoSize = photoSize; - return this; - } - - public Integer getPhotoWidth() { - return photoWidth; - } - - public SendInvoice setPhotoWidth(Integer photoWidth) { - this.photoWidth = photoWidth; - return this; - } - - public Integer getPhotoHeight() { - return photoHeight; - } - - public SendInvoice setPhotoHeight(Integer photoHeight) { - this.photoHeight = photoHeight; - return this; - } - - public Boolean getNeedName() { - return needName; - } - - public SendInvoice setNeedName(Boolean needName) { - this.needName = needName; - return this; - } - - public Boolean getNeedPhoneNumber() { - return needPhoneNumber; - } - - public SendInvoice setNeedPhoneNumber(Boolean needPhoneNumber) { - this.needPhoneNumber = needPhoneNumber; - return this; - } - - public Boolean getNeedEmail() { - return needEmail; - } - - public SendInvoice setNeedEmail(Boolean needEmail) { - this.needEmail = needEmail; - return this; - } - - public Boolean getNeedShippingAddress() { - return needShippingAddress; - } - - public SendInvoice setNeedShippingAddress(Boolean needShippingAddress) { - this.needShippingAddress = needShippingAddress; - return this; - } - - public Boolean getSendPhoneNumberToProvider() { return sendPhoneNumberToProvider; } - - public SendInvoice setSendPhoneNumberToProvider(Boolean sendPhoneNumberToProvider) { - this.sendPhoneNumberToProvider = sendPhoneNumberToProvider; - return this; - } - - public Boolean getSendEmailToProvider() { return sendEmailToProvider; } - - public SendInvoice setSendEmailToProvider(Boolean sendEmailToProvider) { - this.sendEmailToProvider = sendEmailToProvider; - return this; - } - - public Boolean getFlexible() { - return isFlexible; - } - - public SendInvoice setFlexible(Boolean flexible) { - isFlexible = flexible; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendInvoice setDisableNotification(Boolean disableNotification) { - this.disableNotification = disableNotification; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendInvoice setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public SendInvoice setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getProviderData() { - return providerData; - } - - public SendInvoice setProviderData(String providerData) { - this.providerData = providerData; - return this; - } + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found @Override public String getMethod() { @@ -396,33 +189,4 @@ public class SendInvoice extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendInvoice{" + - "chatId=" + chatId + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", payload='" + payload + '\'' + - ", providerToken='" + providerToken + '\'' + - ", startParameter='" + startParameter + '\'' + - ", currency='" + currency + '\'' + - ", prices=" + prices + - ", photoUrl='" + photoUrl + '\'' + - ", photoSize=" + photoSize + - ", photoWidth=" + photoWidth + - ", photoHeight=" + photoHeight + - ", needName=" + needName + - ", needPhoneNumber=" + needPhoneNumber + - ", needEmail=" + needEmail + - ", needShippingAddress=" + needShippingAddress + - ", sendPhoneNumberToProvider=" + sendPhoneNumberToProvider + - ", sendEmailToProvider=" + sendEmailToProvider + - ", isFlexible=" + isFlexible + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", providerData='" + providerData + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendLocation.java index 28a889d6..720f9eb0 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendLocation.java @@ -2,23 +2,37 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send point on the map. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendLocation extends BotApiMethod { public static final String PATH = "sendlocation"; @@ -29,13 +43,20 @@ public class SendLocation extends BotApiMethod { private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; private static final String LIVEPERIOD_FIELD = "live_period"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + private static final String HORIZONTALACCURACY_FIELD = "horizontal_accuracy"; + private static final String HEADING_FIELD = "heading"; + private static final String APPROACHINGNOTIFICATIONDISTANCE_FIELD = "approaching_notification_distance"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(LATITUDE_FIELD) - private Float latitude; ///< Latitude of location + @NonNull + private Double latitude; ///< Latitude of location @JsonProperty(LONGITUDE_FIELD) - private Float longitude; ///< Longitude of location + @NonNull + private Double longitude; ///< Longitude of location @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. @JsonProperty(REPLYTOMESSAGEID_FIELD) @@ -44,91 +65,35 @@ public class SendLocation extends BotApiMethod { private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard @JsonProperty(LIVEPERIOD_FIELD) private Integer livePeriod; ///< Optional. Period in seconds for which the location will be updated (see Live Locations), should be between 60 and 86400. + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found + /** + * Optional. + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + @JsonProperty(HORIZONTALACCURACY_FIELD) + private Double horizontalAccuracy; + /** + * Optional. + * For live locations, a direction in which the user is moving, in degrees. + * Must be between 1 and 360 if specified. + */ + @JsonProperty(HEADING_FIELD) + private Integer heading; + /** + * Optional. + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. + * Must be between 1 and 100000 if specified. + */ + @JsonProperty(APPROACHINGNOTIFICATIONDISTANCE_FIELD) + private Integer approachingNotificationDistance; - public SendLocation() { - super(); - } - - public SendLocation(Float latitude, Float longitude) { - super(); - this.latitude = checkNotNull(latitude); - this.longitude = checkNotNull(longitude); - } - - - public String getChatId() { - return chatId; - } - - public SendLocation setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendLocation setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Float getLatitude() { - return latitude; - } - - public SendLocation setLatitude(Float latitude) { - Objects.requireNonNull(latitude); - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public SendLocation setLongitude(Float longitude) { - Objects.requireNonNull(longitude); - this.longitude = longitude; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendLocation setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendLocation setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendLocation enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendLocation disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public Integer getLivePeriod() { - return livePeriod; - } - - public SendLocation setLivePeriod(Integer livePeriod) { - this.livePeriod = livePeriod; - return this; } @Override @@ -162,6 +127,15 @@ public class SendLocation extends BotApiMethod { if (longitude == null) { throw new TelegramApiValidationException("Longitude parameter can't be empty", this); } + if (horizontalAccuracy != null && (horizontalAccuracy < 0 || horizontalAccuracy > 1500)) { + throw new TelegramApiValidationException("Horizontal Accuracy parameter must be between 0 and 1500", this); + } + if (heading != null && (heading < 1 || heading > 360)) { + throw new TelegramApiValidationException("Heading Accuracy parameter must be between 0 and 1500", this); + } + if (approachingNotificationDistance != null && (approachingNotificationDistance < 1 || approachingNotificationDistance > 100000)) { + throw new TelegramApiValidationException("Approaching notification distance parameter must be between 0 and 1500", this); + } if (replyMarkup != null) { replyMarkup.validate(); } @@ -169,17 +143,4 @@ public class SendLocation extends BotApiMethod { throw new TelegramApiValidationException("Live period parameter must be between 60 and 86400", this); } } - - @Override - public String toString() { - return "SendLocation{" + - "chatId='" + chatId + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", livePeriod=" + livePeriod + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMediaGroup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMediaGroup.java index dd1341a0..25494265 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMediaGroup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMediaGroup.java @@ -2,12 +2,22 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.media.InputMedia; -import org.telegram.telegrambots.meta.api.objects.media.InputMediaPhoto; -import org.telegram.telegrambots.meta.api.objects.media.InputMediaVideo; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaAnimation; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaAudio; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaDocument; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -15,16 +25,23 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 3.5 * - * Use this method to send a group of photos or videos as an album. - * On success, an array of the sent Messages is returned. + * Use this method to send a group of photos, videos, documents or audios as an album. + * Documents and audio files can be only group in an album with messages of the same type. + * On success, an array of Messages that were sent is returned. */ @SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendMediaGroup extends PartialBotApiMethod> { public static final String PATH = "sendMediaGroup"; @@ -32,75 +49,27 @@ public class SendMediaGroup extends PartialBotApiMethod> { public static final String MEDIA_FIELD = "media"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the target chat or username of the target channel (in the format @channelusername) @JsonProperty(MEDIA_FIELD) - private List media; ///< A JSON-serialized array describing photos and videos to be sent, must include 2–10 items + @NonNull + private List medias; ///< A JSON-serialized array describing photos and videos to be sent, must include 2–10 items @JsonProperty(REPLYTOMESSAGEID_FIELD) private Integer replyToMessageId; ///< Optional. If the messages are a reply, ID of the original message @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; ///< Optional. Sends the messages silently. Users will receive a notification with no sound. + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendMediaGroup() { - super(); - } - - public SendMediaGroup(String chatId, List media) { - super(); - this.chatId = checkNotNull(chatId); - this.media = checkNotNull(media); - } - - public SendMediaGroup(Long chatId, List media) { - super(); - this.chatId = checkNotNull(chatId).toString(); - this.media = checkNotNull(media); - } - - public String getChatId() { - return chatId; - } - - public SendMediaGroup setChatId(String chatId) { - this.chatId = checkNotNull(chatId); - return this; - } - - public SendMediaGroup setChatId(Long chatId) { - this.chatId = checkNotNull(chatId).toString(); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendMediaGroup setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendMediaGroup enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendMediaGroup disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public List getMedia() { - return media; - } - - public void setMedia(List media) { - this.media = media; } @Override @@ -125,26 +94,30 @@ public class SendMediaGroup extends PartialBotApiMethod> { throw new TelegramApiValidationException("ChatId parameter can't be empty", this); } - if (media == null || media.isEmpty()) { + if (medias == null || medias.isEmpty()) { throw new TelegramApiValidationException("Media parameter can't be empty", this); + } else if (medias.size() < 2 || medias.size() > 10) { + throw new TelegramApiValidationException("Number of media should be between 2 and 10", this); } - for (InputMedia inputMedia : media) { - if (inputMedia instanceof InputMediaPhoto || inputMedia instanceof InputMediaVideo) { - inputMedia.validate(); + for (InputMedia inputMedia : medias) { + if (inputMedia == null) { + throw new TelegramApiValidationException("Media parameter can not be empty", this); + } else if (inputMedia instanceof InputMediaAnimation) { + throw new TelegramApiValidationException("Media parameter can not be an Animation", this); } else { - throw new TelegramApiValidationException("Media parameter can only be Photo or Video", this); + inputMedia.validate(); + } + } + + if (medias.stream().anyMatch(x -> x instanceof InputMediaAudio)) { + if (!medias.stream().allMatch(x -> x instanceof InputMediaAudio)) { + throw new TelegramApiValidationException("Media parameter containing Audio can not have other types", this); + } + } else if (medias.stream().anyMatch(x -> x instanceof InputMediaDocument)) { + if (!medias.stream().allMatch(x -> x instanceof InputMediaDocument)) { + throw new TelegramApiValidationException("Media parameter containing Document can not have other types", this); } } } - - @Override - public String toString() { - return "SendMediaGroup{" + - "chatId='" + chatId + '\'' + - ", media=" + media + - ", replyToMessageId=" + replyToMessageId + - ", disableNotification=" + disableNotification + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMessage.java index 5377de33..337c22e0 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendMessage.java @@ -3,24 +3,41 @@ package org.telegram.telegrambots.meta.api.methods.send; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.methods.ParseMode; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; +import java.util.List; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send text messages. On success, the sent Message is returned. */ +@SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendMessage extends BotApiMethod { public static final String PATH = "sendmessage"; @@ -31,10 +48,14 @@ public class SendMessage extends BotApiMethod { private static final String DISABLENOTIFICATION_FIELD = "disable_notification"; private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + private static final String ENTITIES_FIELD = "entities"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(TEXT_FIELD) + @NonNull private String text; ///< Text of the message to be sent @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Optional. Send Markdown, if you want Telegram apps to show bold, italic and URL text in your bot's message. @@ -47,121 +68,49 @@ public class SendMessage extends BotApiMethod { @JsonProperty(REPLYMARKUP_FIELD) @JsonDeserialize() private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard + @JsonProperty(ENTITIES_FIELD) + private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendMessage() { - super(); - } - - public SendMessage(String chatId, String text) { - this.chatId = checkNotNull(chatId); - this.text = checkNotNull(text); - } - - public SendMessage(Long chatId, String text) { - this.chatId = checkNotNull(chatId).toString(); - this.text = checkNotNull(text); - } - - public String getChatId() { - return chatId; - } - - public SendMessage setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendMessage setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public String getText() { - return text; - } - - public SendMessage setText(String text) { - this.text = text; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendMessage setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendMessage setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableWebPagePreview() { - return disableWebPagePreview; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendMessage disableWebPagePreview() { + public void disableWebPagePreview() { disableWebPagePreview = true; - return this; } - public SendMessage enableWebPagePreview() { + public void enableWebPagePreview() { disableWebPagePreview = null; - return this; } - public SendMessage enableNotification() { + public void enableNotification() { this.disableNotification = null; - return this; } - public SendMessage disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; } - public SendMessage setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public SendMessage enableMarkdown(boolean enable) { + public void enableMarkdown(boolean enable) { if (enable) { this.parseMode = ParseMode.MARKDOWN; } else { this.parseMode = null; } - return this; } - public SendMessage enableHtml(boolean enable) { + public void enableHtml(boolean enable) { if (enable) { this.parseMode = ParseMode.HTML; } else { this.parseMode = null; } - return this; } - public SendMessage enableMarkdownV2(boolean enable) { + public void enableMarkdownV2(boolean enable) { if (enable) { this.parseMode = ParseMode.MARKDOWNV2; } else { this.parseMode = null; } - return this; } @Override @@ -192,50 +141,11 @@ public class SendMessage extends BotApiMethod { if (text == null || text.isEmpty()) { throw new TelegramApiValidationException("Text parameter can't be empty", this); } + if (parseMode != null && (entities != null && !entities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof SendMessage)) { - return false; - } - SendMessage sendMessage = (SendMessage) o; - return Objects.equals(chatId, sendMessage.chatId) - && Objects.equals(disableNotification, sendMessage.disableNotification) - && Objects.equals(disableWebPagePreview, sendMessage.disableWebPagePreview) - && Objects.equals(parseMode, sendMessage.parseMode) - && Objects.equals(replyMarkup, sendMessage.replyMarkup) - && Objects.equals(replyToMessageId, sendMessage.replyToMessageId) - && Objects.equals(text, sendMessage.text) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - chatId, - disableNotification, - disableWebPagePreview, - parseMode, - replyMarkup, - replyToMessageId, - text); - } - - @Override - public String toString() { - return "SendMessage{" + - "chatId='" + chatId + '\'' + - ", text='" + text + '\'' + - ", parseMode='" + parseMode + '\'' + - ", disableNotification='" + disableNotification + '\'' + - ", disableWebPagePreview=" + disableWebPagePreview + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendPhoto.java index c5c225da..6a643f05 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendPhoto.java @@ -1,17 +1,27 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; +import java.util.List; import java.util.Objects; /** @@ -19,6 +29,14 @@ import java.util.Objects; * @version 1.0 * Use this method to send photos. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendPhoto extends PartialBotApiMethod { public static final String PATH = "sendphoto"; @@ -29,110 +47,33 @@ public class SendPhoto extends PartialBotApiMethod { public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String PARSEMODE_FIELD = "parse_mode"; + public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @NonNull private InputFile photo; ///< Photo to send. file_id as String to resend a photo that is already on the Telegram servers or URL to upload it private String caption; ///< Optional Photo caption (may also be used when resending photos by file_id). private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendPhoto() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendPhoto setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendPhoto setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public InputFile getPhoto() { - return photo; - } - - public SendPhoto setPhoto(String photo) { - this.photo = new InputFile(photo); - return this; - } - - public String getCaption() { - return caption; - } - - public SendPhoto setCaption(String caption) { - this.caption = caption; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendPhoto setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendPhoto setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendPhoto enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendPhoto disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; } - public SendPhoto setPhoto(File file) { - Objects.requireNonNull(file, "file cannot be null!"); - this.photo = new InputFile(file, file.getName()); - return this; - } - - public SendPhoto setPhoto(InputFile photo) { + public void setPhoto(InputFile photo) { Objects.requireNonNull(photo, "photo cannot be null!"); this.photo = photo; - return this; - } - - public SendPhoto setPhoto(String photoName, InputStream inputStream) { - Objects.requireNonNull(photoName, "photoName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.photo = new InputFile(inputStream, photoName); - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendPhoto setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; } @Override @@ -160,23 +101,13 @@ public class SendPhoto extends PartialBotApiMethod { throw new TelegramApiValidationException("Photo parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } photo.validate(); if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendPhoto{" + - "chatId='" + chatId + '\'' + - ", photo=" + photo + - ", caption='" + caption + '\'' + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendSticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendSticker.java index 94cada4e..9796bc1e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendSticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendSticker.java @@ -1,24 +1,38 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method to send .webp stickers. On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendSticker extends PartialBotApiMethod { public static final String PATH = "sendsticker"; @@ -27,89 +41,27 @@ public class SendSticker extends PartialBotApiMethod { public static final String DISABLENOTIFICATION_FIELD = "disable_notification"; public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @NonNull private InputFile sticker; ///< Sticker file to send. file_id as String to resend a sticker that is already on the Telegram servers or URL to upload it private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - - public SendSticker() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendSticker setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendSticker setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public InputFile getSticker() { - return sticker; - } - - public SendSticker setSticker(String sticker) { - this.sticker = new InputFile(sticker); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendSticker setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendSticker setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public SendSticker setSticker(InputFile sticker) { - Objects.requireNonNull(sticker, "sticker cannot be null!"); - this.sticker = sticker; - return this; - } - - public SendSticker setSticker(File file) { - Objects.requireNonNull(file, "file cannot be null!"); - this.sticker = new InputFile(file, file.getName()); - return this; - } - - public SendSticker setSticker(String stickerName, InputStream inputStream) { - Objects.requireNonNull(stickerName, "stickerName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.sticker = new InputFile(inputStream, stickerName); - return this; - } + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found public Boolean getDisableNotification() { return disableNotification; } - public SendSticker enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendSticker disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; } @Override @@ -143,15 +95,4 @@ public class SendSticker extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendSticker{" + - "chatId='" + chatId + '\'' + - ", sticker=" + sticker + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVenue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVenue.java index 6d3281f2..574166b4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVenue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVenue.java @@ -2,16 +2,23 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; /** * @author Ruben Bermudez @@ -19,6 +26,14 @@ import java.util.Objects; * Use this method to send information about a venue. On success, the sent Message is * returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendVenue extends BotApiMethod { public static final String PATH = "sendVenue"; @@ -32,19 +47,27 @@ public class SendVenue extends BotApiMethod { private static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; private static final String REPLYMARKUP_FIELD = "reply_markup"; private static final String FOURSQUARETYPE_FIELD = "foursquare_type"; + private static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + private static final String GOOGLEPLACEID_FIELD = "google_place_id"; + private static final String GOOGLEPLACETYPE_FIELD = "google_place_type"; @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) @JsonProperty(LATITUDE_FIELD) - private Float latitude; ///< Latitude of venue location + @NonNull + private Double latitude; ///< Latitude of venue location @JsonProperty(LONGITUDE_FIELD) - private Float longitude; ///< Longitude of venue location + @NonNull + private Double longitude; ///< Longitude of venue location @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Title of the venue + @JsonProperty(ADDRESS_FIELD) + @NonNull + private String address; ///< Address of the venue @JsonProperty(DISABLENOTIFICATION_FIELD) private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. - @JsonProperty(ADDRESS_FIELD) - private String address; ///< Address of the venue @JsonProperty(FOURSQUAREID_FIELD) private String foursquareId; ///< Optional. Foursquare identifier of the venue @JsonProperty(REPLYTOMESSAGEID_FIELD) @@ -53,110 +76,19 @@ public class SendVenue extends BotApiMethod { private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard @JsonProperty(FOURSQUARETYPE_FIELD) private String foursquareType; ///< Optional. Foursquare type of the venue, if known. + @JsonProperty(ALLOWSENDINGWITHOUTREPLY_FIELD) + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found + @JsonProperty(GOOGLEPLACEID_FIELD) + private String googlePlaceId; ///< Optional. Google Places identifier of the venue + @JsonProperty(GOOGLEPLACETYPE_FIELD) + private String googlePlaceType; ///< Optional. Google Places type of the venue. (See supported types.) - public SendVenue() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendVenue setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendVenue setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Float getLatitude() { - return latitude; - } - - public SendVenue setLatitude(Float latitude) { - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public SendVenue setLongitude(Float longitude) { - this.longitude = longitude; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendVenue setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendVenue setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendVenue enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendVenue disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getTitle() { - return title; - } - - public SendVenue setTitle(String title) { - this.title = title; - return this; - } - - public String getAddress() { - return address; - } - - public SendVenue setAddress(String address) { - this.address = address; - return this; - } - - public String getFoursquareId() { - return foursquareId; - } - - public SendVenue setFoursquareId(String foursquareId) { - this.foursquareId = foursquareId; - return this; - } - - public String getFoursquareType() { - return foursquareType; - } - - public SendVenue setFoursquareType(String foursquareType) { - this.foursquareType = foursquareType; - return this; } @Override @@ -200,20 +132,4 @@ public class SendVenue extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendVenue{" + - "chatId='" + chatId + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", title='" + title + '\'' + - ", disableNotification=" + disableNotification + - ", address='" + address + '\'' + - ", foursquareId='" + foursquareId + '\'' + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", foursquareType='" + foursquareType + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideo.java index 998dd97a..4aa91dab 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideo.java @@ -1,18 +1,27 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; +import java.util.List; /** * @author Ruben Bermudez @@ -20,6 +29,14 @@ import java.util.Objects; * Use this method to send video files, Telegram clients support mp4 videos (other formats * may be sent as Document). On success, the sent Message is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendVideo extends PartialBotApiMethod { public static final String PATH = "sendvideo"; @@ -35,8 +52,12 @@ public class SendVideo extends PartialBotApiMethod { public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String PARSEMODE_FIELD = "parse_mode"; public static final String THUMB_FIELD = "thumb"; + public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @NonNull private InputFile video; ///< Video to send. file_id as String to resend a video that is already on the Telegram servers or URL to upload it private Integer duration; ///< Optional. Duration of sent video in seconds private String caption; ///< Optional. Video caption (may also be used when resending videos by file_id). @@ -46,8 +67,9 @@ public class SendVideo extends PartialBotApiMethod { private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. /** + * Optional. * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. * A thumbnail’s width and height should not exceed 320. * Ignored if the file is not uploaded using multipart/form-data. @@ -55,147 +77,16 @@ public class SendVideo extends PartialBotApiMethod { * if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendVideo() { - super(); - } - - public String getChatId() { - return chatId; - } - - public SendVideo setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public InputFile getVideo() { - return video; - } - - public SendVideo setVideo(String video) { - this.video = new InputFile(video); - return this; - } - - public SendVideo setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getDuration() { - return duration; - } - - public SendVideo setDuration(Integer duration) { - this.duration = duration; - return this; - } - - public String getCaption() { - return caption; - } - - public SendVideo setCaption(String caption) { - this.caption = caption; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendVideo setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendVideo setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendVideo enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendVideo disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public Integer getWidth() { - return width; - } - - public SendVideo setWidth(Integer width) { - this.width = width; - return this; - } - - public Integer getHeight() { - return height; - } - - public SendVideo setHeight(Integer height) { - this.height = height; - return this; - } - - public SendVideo setVideo(InputFile video) { - Objects.requireNonNull(video, "video cannot be null!"); - this.video = video; - return this; - } - - public SendVideo setVideo(File file) { - Objects.requireNonNull(file, "file cannot be null!"); - this.video = new InputFile(file, file.getName()); - return this; - } - - public SendVideo setVideo(String videoName, InputStream inputStream) { - Objects.requireNonNull(videoName, "videoName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.video = new InputFile(inputStream, videoName); - return this; - } - - public Boolean getSupportsStreaming() { - return supportsStreaming; - } - - public SendVideo setSupportsStreaming(Boolean supportsStreaming) { - this.supportsStreaming = supportsStreaming; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendVideo setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public SendVideo setThumb(InputFile thumb) { - this.thumb = thumb; - return this; } @Override @@ -223,6 +114,10 @@ public class SendVideo extends PartialBotApiMethod { throw new TelegramApiValidationException("Video parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } + video.validate(); if (thumb != null) { @@ -232,22 +127,4 @@ public class SendVideo extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendVideo{" + - "chatId='" + chatId + '\'' + - ", video=" + video + - ", duration=" + duration + - ", caption='" + caption + '\'' + - ", width=" + width + - ", height=" + height + - ", supportsStreaming=" + supportsStreaming + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - ", thumb=" + thumb + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideoNote.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideoNote.java index 9da68295..0fba958d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideoNote.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVideoNote.java @@ -1,20 +1,24 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -23,6 +27,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use this method to send video messages. On success, the sent Message is returned. */ @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendVideoNote extends PartialBotApiMethod { public static final String PATH = "sendvideonote"; @@ -34,8 +46,11 @@ public class SendVideoNote extends PartialBotApiMethod { public static final String REPLYTOMESSAGEID_FIELD = "reply_to_message_id"; public static final String REPLYMARKUP_FIELD = "reply_markup"; public static final String THUMB_FIELD = "thumb"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + @NonNull private String chatId; ///< Unique identifier for the chat to send the message to (Or username for channels) + @NonNull private InputFile videoNote; ///< Videonote to send. file_id as String to resend a video that is already on the Telegram servers. private Integer duration; ///< Optional. Duration of sent video in seconds private Integer length; ///< Optional. Video width and height @@ -50,174 +65,14 @@ public class SendVideoNote extends PartialBotApiMethod { * if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendVideoNote() { - super(); - } - - /** - * Creates a new video note with a video already present in telegram servers - * @param chatId Chat Id to send the video note - * @param videoNote Video note file_id to send - */ - public SendVideoNote(String chatId, String videoNote) { - this.chatId = checkNotNull(chatId); - this.setVideoNote(checkNotNull(videoNote)); - } - - /** - * Creates a new video note with a video already present in telegram servers - * @param chatId Chat Id to send the video note - * @param videoNote Video note file_id to send - */ - public SendVideoNote(Long chatId, String videoNote) { - - this.chatId = checkNotNull(chatId).toString(); - this.setVideoNote(checkNotNull(videoNote)); - } - - /** - * Creates a new video note with a new video note - * @param chatId Chat Id to send the video note - * @param videoNote Video note file to upload - */ - public SendVideoNote(String chatId, File videoNote) { - this.chatId = checkNotNull(chatId); - this.setVideoNote(videoNote); - } - - /** - * Creates a new video note with a video already present in telegram servers - * @param chatId Chat Id to send the video note - * @param videoNote Video note file to upload - */ - public SendVideoNote(Integer chatId, File videoNote) { - this.chatId = checkNotNull(chatId).toString(); - this.setVideoNote(videoNote); - } - - /** - * Creates a new video note with a new video note - * @param chatId Chat Id to send the video note - * @param videoNoteName Name of the video note file - * @param videoNote Video note file to upload - */ - public SendVideoNote(String chatId, String videoNoteName, InputStream videoNote) { - this.chatId = checkNotNull(chatId); - this.setVideoNote(videoNoteName, videoNote); - } - - /** - * Creates a new video note with a video already present in telegram servers - * @param chatId Chat Id to send the video note - * @param videoNoteName Name of the video note file - * @param videoNote Video note file to upload - */ - public SendVideoNote(Integer chatId, String videoNoteName, InputStream videoNote) { - this.chatId = checkNotNull(chatId).toString(); - this.setVideoNote(videoNoteName, videoNote); - } - - public String getChatId() { - return chatId; - } - - public SendVideoNote setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public InputFile getVideoNote() { - return videoNote; - } - - public SendVideoNote setVideoNote(String videoNote) { - this.videoNote = new InputFile(videoNote); - return this; - } - - public Integer getLength() { - return length; - } - - public SendVideoNote setLength(Integer length) { - this.length = length; - return this; - } - - public SendVideoNote setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getDuration() { - return duration; - } - - public SendVideoNote setDuration(Integer duration) { - this.duration = duration; - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendVideoNote setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendVideoNote setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendVideoNote enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendVideoNote disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public SendVideoNote setVideoNote(InputFile videoNote) { - Objects.requireNonNull(videoNote, "videoNote cannot be null!"); - this.videoNote = videoNote; - return this; - } - - public SendVideoNote setVideoNote(File file) { - Objects.requireNonNull(file, "file cannot be null!"); - this.videoNote = new InputFile(file, file.getName()); - return this; - } - - public SendVideoNote setVideoNote(String videoName, InputStream inputStream) { - Objects.requireNonNull(videoName, "videoName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.videoNote = new InputFile(inputStream, videoName); - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public SendVideoNote setThumb(InputFile thumb) { - this.thumb = thumb; - return this; } @Override @@ -254,18 +109,4 @@ public class SendVideoNote extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendVideoNote{" + - "chatId='" + chatId + '\'' + - ", videoNote=" + videoNote + - ", duration=" + duration + - ", length=" + length + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", thumb=" + thumb + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVoice.java index da19e0e4..61347bbd 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/send/SendVoice.java @@ -1,18 +1,27 @@ package org.telegram.telegrambots.meta.api.methods.send; 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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; +import java.util.List; /** * @author Ruben Bermudez @@ -21,6 +30,14 @@ import java.util.Objects; * playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS * (other formats may be sent as Audio or Document). */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SendVoice extends PartialBotApiMethod { public static final String PATH = "sendvoice"; @@ -32,121 +49,29 @@ public class SendVoice extends PartialBotApiMethod { public static final String DURATION_FIELD = "duration"; public static final String CAPTION_FIELD = "caption"; public static final String PARSEMODE_FIELD = "parse_mode"; + public static final String CAPTION_ENTITIES_FIELD = "caption_entities"; + public static final String ALLOWSENDINGWITHOUTREPLY_FIELD = "allow_sending_without_reply"; + @NonNull private String chatId; ///< Unique identifier for the chat sent message to (Or username for channels) + @NonNull private InputFile voice; ///< Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data. private Boolean disableNotification; ///< Optional. Sends the message silently. Users will receive a notification with no sound. private Integer replyToMessageId; ///< Optional. If the message is a reply, ID of the original message private ReplyKeyboard replyMarkup; ///< Optional. JSON-serialized object for a custom reply keyboard private Integer duration; ///< Optional. Duration of sent audio in seconds private String caption; ///< Optional. Voice caption (may also be used when resending videos by file_id). - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode + private Boolean allowSendingWithoutReply; ///< Optional Pass True, if the message should be sent even if the specified replied-to message is not found - public SendVoice() { - super(); - } - - public Boolean getDisableNotification() { - return disableNotification; - } - - public SendVoice enableNotification() { + public void enableNotification() { this.disableNotification = false; - return this; } - public SendVoice disableNotification() { + public void disableNotification() { this.disableNotification = true; - return this; - } - - public String getChatId() { - return chatId; - } - - public SendVoice setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public SendVoice setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public InputFile getVoice() { - return voice; - } - - public SendVoice setVoice(String voice) { - Objects.requireNonNull(voice, "voice cannot be null!"); - this.voice = new InputFile(voice); - return this; - } - - public SendVoice setVoice(File voice) { - Objects.requireNonNull(voice, "voice cannot be null!"); - this.voice = new InputFile(voice, voice.getName()); - return this; - } - - public SendVoice setVoice(InputFile voice) { - Objects.requireNonNull(voice, "voice cannot be null!"); - this.voice = voice; - return this; - } - - public SendVoice setVoice(String voiceName, InputStream inputStream) { - Objects.requireNonNull(voiceName, "voiceName cannot be null!"); - Objects.requireNonNull(inputStream, "inputStream cannot be null!"); - this.voice = new InputFile(inputStream, voiceName); - return this; - } - - public Integer getReplyToMessageId() { - return replyToMessageId; - } - - public SendVoice setReplyToMessageId(Integer replyToMessageId) { - this.replyToMessageId = replyToMessageId; - return this; - } - - public ReplyKeyboard getReplyMarkup() { - return replyMarkup; - } - - public SendVoice setReplyMarkup(ReplyKeyboard replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Integer getDuration() { - return duration; - } - - public SendVoice setDuration(Integer duration) { - this.duration = duration; - return this; - } - - public String getCaption() { - return caption; - } - - public SendVoice setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public SendVoice setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; } @Override @@ -173,25 +98,13 @@ public class SendVoice extends PartialBotApiMethod { if (voice == null) { throw new TelegramApiValidationException("Voice parameter can't be empty", this); } - + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } voice.validate(); if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "SendVoice{" + - "chatId='" + chatId + '\'' + - ", voice=" + voice + - ", disableNotification=" + disableNotification + - ", replyToMessageId=" + replyToMessageId + - ", replyMarkup=" + replyMarkup + - ", duration=" + duration + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - '}'; - } } 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 e1f433d0..7429c625 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 @@ -1,6 +1,15 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.PartialBotApiMethod; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; @@ -8,12 +17,7 @@ import org.telegram.telegrambots.meta.api.objects.stickers.MaskPosition; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -25,6 +29,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * Static sticker sets can have up to 120 stickers. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class AddStickerToSet extends PartialBotApiMethod { public static final String PATH = "addStickerToSet"; @@ -35,11 +47,15 @@ public class AddStickerToSet extends PartialBotApiMethod { public static final String EMOJIS_FIELD = "emojis"; public static final String MASKPOSITION_FIELD = "mask_position"; + @NonNull private Integer userId; ///< User identifier of sticker set owner + @NonNull private String name; ///< Sticker set name + @NonNull private String emojis; ///< One or more emoji corresponding to the sticker - private MaskPosition maskPosition; ///< Position where the mask should be placed on faces + private MaskPosition maskPosition; ///< Optional. Position where the mask should be placed on faces /** + * Optional. * 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. Pass a file_id as a String to send a file * that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram @@ -47,93 +63,12 @@ public class AddStickerToSet extends PartialBotApiMethod { */ private InputFile pngSticker; /** + * Optional. * TGS animation with the sticker, uploaded using multipart/form-data. * See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements */ private InputFile tgsSticker; - public AddStickerToSet() { - super(); - } - - public AddStickerToSet(Integer userId, String name, String emojis) { - this.userId = checkNotNull(userId); - this.name = checkNotNull(name); - this.emojis = checkNotNull(emojis); - } - - public Integer getUserId() { - return userId; - } - - public AddStickerToSet setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public InputFile getPngSticker() { - return pngSticker; - } - - public AddStickerToSet setPngSticker(String pngSticker) { - this.pngSticker = new InputFile(pngSticker); - return this; - } - - public AddStickerToSet setPngSticker(File pngSticker) { - Objects.requireNonNull(pngSticker, "pngSticker cannot be null!"); - this.pngSticker = new InputFile(pngSticker, pngSticker.getName()); - return this; - } - - public AddStickerToSet setPngSticker(String pngStickerName, InputStream pngSticker) { - Objects.requireNonNull(pngStickerName, "pngStickerName cannot be null!"); - Objects.requireNonNull(pngSticker, "pngSticker cannot be null!"); - this.pngSticker = new InputFile(pngSticker, pngStickerName); - return this; - } - - public AddStickerToSet setTgsSticker(File tgsSticker) { - this.tgsSticker = new InputFile(checkNotNull(tgsSticker), tgsSticker.getName()); - return this; - } - - public AddStickerToSet setTgsSticker(String tgsStickerName, InputStream tgsSticker) { - this.tgsSticker = new InputFile(checkNotNull(tgsSticker), checkNotNull(tgsStickerName)); - return this; - } - - public InputFile getTgsSticker() { - return tgsSticker; - } - - public String getName() { - return name; - } - - public AddStickerToSet setName(String name) { - this.name = name; - return this; - } - - public String getEmojis() { - return emojis; - } - - public AddStickerToSet setEmojis(String emojis) { - this.emojis = emojis; - return this; - } - - public MaskPosition getMaskPosition() { - return maskPosition; - } - - public AddStickerToSet setMaskPosition(MaskPosition maskPosition) { - this.maskPosition = maskPosition; - return this; - } - @Override public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { try { @@ -180,16 +115,4 @@ public class AddStickerToSet extends PartialBotApiMethod { maskPosition.validate(); } } - - @Override - public String toString() { - return "AddStickerToSet{" + - "userId=" + userId + - ", name='" + name + '\'' + - ", emojis='" + emojis + '\'' + - ", maskPosition=" + maskPosition + - ", pngSticker=" + pngSticker + - ", tgsSticker=" + tgsSticker + - '}'; - } } 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 f42fab7f..e324098e 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 @@ -1,6 +1,15 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.PartialBotApiMethod; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.InputFile; @@ -8,12 +17,7 @@ import org.telegram.telegrambots.meta.api.objects.stickers.MaskPosition; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -22,6 +26,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * You must use exactly one of the fields png_sticker or tgs_sticker. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class CreateNewStickerSet extends PartialBotApiMethod { public static final String PATH = "createNewStickerSet"; @@ -34,6 +46,7 @@ public class CreateNewStickerSet extends PartialBotApiMethod { public static final String CONTAINSMASKS_FIELD = "contains_masks"; public static final String MASKPOSITION_FIELD = "mask_position"; + @NonNull private Integer userId; ///< User identifier of created sticker set owner /** * Name of sticker set, to be used in t.me/addstickers/ URLs. @@ -41,12 +54,16 @@ public class CreateNewStickerSet extends PartialBotApiMethod { * Must begin with a letter, can't contain consecutive underscores and must end in “_by_”. * is case insensitive. 7-64 characters. */ + @NonNull private String name; ///< Sticker set title, 1-64 characters + @NonNull private String title; ///< User identifier of created sticker set owner + @NonNull private String emojis; ///< One or more emoji corresponding to the sticker - private Boolean containsMasks; ///< Pass True, if a set of mask stickers should be created - private MaskPosition maskPosition; ///< Position where the mask should be placed on faces + private Boolean containsMasks; ///< Optional. Pass True, if a set of mask stickers should be created + private MaskPosition maskPosition; ///< Optional. Position where the mask should be placed on faces /** + * Optional. * 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. * Pass a file_id as a String to send a file that already exists on the Telegram servers, @@ -56,117 +73,12 @@ public class CreateNewStickerSet extends PartialBotApiMethod { private InputFile pngSticker; /** + * @Optional * TGS animation with the sticker, uploaded using multipart/form-data. * See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements */ private InputFile tgsSticker; - public CreateNewStickerSet() { - super(); - } - - public CreateNewStickerSet(Integer userId, String name, String title, String emojis) { - this.userId = checkNotNull(userId); - this.name = checkNotNull(name); - this.title = checkNotNull(title); - this.emojis = checkNotNull(emojis); - } - - public Integer getUserId() { - return userId; - } - - public void setUserId(Integer userId) { - this.userId = userId; - } - - public InputFile getPngSticker() { - return pngSticker; - } - - public CreateNewStickerSet setPngSticker(String pngSticker) { - this.pngSticker = new InputFile(pngSticker); - return this; - } - - public CreateNewStickerSet setPngStickerFile(InputFile pngStickerFile) { - Objects.requireNonNull(pngStickerFile, "pngStickerFile cannot be null!"); - this.pngSticker = pngStickerFile; - return this; - } - - public CreateNewStickerSet setPngStickerFile(File pngStickerFile) { - Objects.requireNonNull(pngStickerFile, "pngStickerFile cannot be null!"); - this.pngSticker = new InputFile(pngStickerFile, pngStickerFile.getName()); - return this; - } - - public CreateNewStickerSet setPngStickerStream(String pngStickerName, InputStream pngStickerStream) { - Objects.requireNonNull(pngStickerName, "pngStickerName cannot be null!"); - Objects.requireNonNull(pngStickerStream, "pngStickerStream cannot be null!"); - this.pngSticker = new InputFile(pngStickerStream, pngStickerName); - return this; - } - - public CreateNewStickerSet setTgsSticker(InputFile tgsSticker) { - this.tgsSticker = checkNotNull(tgsSticker); - return this; - } - - public CreateNewStickerSet setTgsSticker(File tgsStickerFile) { - this.tgsSticker = new InputFile(checkNotNull(tgsStickerFile), tgsStickerFile.getName());; - return this; - } - - public CreateNewStickerSet setTgsSticker(String tgsStickerName, InputStream tgsStickerStream) { - this.pngSticker = new InputFile(checkNotNull(tgsStickerStream), checkNotNull(tgsStickerName)); - return this; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getEmojis() { - return emojis; - } - - public void setEmojis(String emojis) { - this.emojis = emojis; - } - - public Boolean getContainsMasks() { - return containsMasks; - } - - public void setContainsMasks(Boolean containsMasks) { - this.containsMasks = containsMasks; - } - - public MaskPosition getMaskPosition() { - return maskPosition; - } - - public void setMaskPosition(MaskPosition maskPosition) { - this.maskPosition = maskPosition; - } - - public InputFile getTgsSticker() { - return tgsSticker; - } - @Override public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { try { @@ -216,18 +128,4 @@ public class CreateNewStickerSet extends PartialBotApiMethod { maskPosition.validate(); } } - - @Override - public String toString() { - return "CreateNewStickerSet{" + - "userId=" + userId + - ", name='" + name + '\'' + - ", title='" + title + '\'' + - ", emojis='" + emojis + '\'' + - ", containsMasks=" + containsMasks + - ", maskPosition=" + maskPosition + - ", pngSticker=" + pngSticker + - ", tgsSticker=" + tgsSticker + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/DeleteStickerFromSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/DeleteStickerFromSet.java index bd9cffd7..4f447fa5 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/DeleteStickerFromSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/DeleteStickerFromSet.java @@ -2,6 +2,14 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.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.exceptions.TelegramApiRequestException; @@ -9,30 +17,27 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * Use this method to delete a sticker from a set created by the bot. Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class DeleteStickerFromSet extends BotApiMethod { private static final String PATH = "deleteStickerFromSet"; private static final String STICKER_FIELD = "sticker"; @JsonProperty(STICKER_FIELD) + @NonNull private String sticker; ///< File identifier of the sticker - public DeleteStickerFromSet() { - super(); - } - - public DeleteStickerFromSet(String sticker) { - super(); - this.sticker = checkNotNull(sticker); - } - @Override public String getMethod() { return PATH; @@ -59,20 +64,4 @@ public class DeleteStickerFromSet extends BotApiMethod { throw new TelegramApiValidationException("sticker can't be null", this); } } - - public String getSticker() { - return sticker; - } - - public DeleteStickerFromSet setSticker(String sticker) { - this.sticker = sticker; - return this; - } - - @Override - public String toString() { - return "DeleteStickerFromSet{" + - "sticker='" + sticker + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/GetStickerSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/GetStickerSet.java index 28703f56..fa7fc277 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/GetStickerSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/GetStickerSet.java @@ -2,6 +2,14 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.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.stickers.StickerSet; @@ -10,30 +18,27 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * Use this method to get a sticker set. On success, a StickerSet object is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetStickerSet extends BotApiMethod { private static final String PATH = "getStickerSet"; private static final String NAME_FIELD = "name"; @JsonProperty(NAME_FIELD) + @NonNull private String name; ///< Name of the sticker set - public GetStickerSet(String name) { - super(); - this.name = checkNotNull(name); - } - - public GetStickerSet() { - super(); - } - @Override public String getMethod() { return PATH; @@ -60,20 +65,4 @@ public class GetStickerSet extends BotApiMethod { throw new TelegramApiValidationException("Name can't be null", this); } } - - public String getName() { - return name; - } - - public GetStickerSet setName(String name) { - this.name = name; - return this; - } - - @Override - public String toString() { - return "GetStickerSet{" + - "name='" + name + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerPositionInSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerPositionInSet.java index 7289ad6c..43c8ffb7 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerPositionInSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/stickers/SetStickerPositionInSet.java @@ -2,6 +2,14 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.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.exceptions.TelegramApiRequestException; @@ -9,13 +17,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetStickerPositionInSet extends BotApiMethod { private static final String PATH = "setStickerPositionInSet"; @@ -23,19 +36,12 @@ public class SetStickerPositionInSet extends BotApiMethod { private static final String POSITION_FIELD = "position"; @JsonProperty(STICKER_FIELD) + @NonNull private String sticker; ///< File identifier of the sticker @JsonProperty(POSITION_FIELD) + @NonNull private Integer position; ///< New sticker position in the set, zero-based - public SetStickerPositionInSet(String sticker, Integer position) { - this.sticker = checkNotNull(sticker); - this.position = checkNotNull(position); - } - - public SetStickerPositionInSet() { - super(); - } - @Override public String getMethod() { return PATH; @@ -65,30 +71,4 @@ public class SetStickerPositionInSet extends BotApiMethod { throw new TelegramApiValidationException("position can't be null", this); } } - - public String getSticker() { - return sticker; - } - - public SetStickerPositionInSet setSticker(String sticker) { - this.sticker = checkNotNull(sticker); - return this; - } - - public Integer getPosition() { - return position; - } - - public SetStickerPositionInSet setPosition(Integer position) { - this.position = checkNotNull(position); - return this; - } - - @Override - public String toString() { - return "SetStickerPositionInSet{" + - "sticker='" + sticker + '\'' + - ", position=" + position + - '}'; - } } 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 5dad0304..87d8f22e 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 @@ -1,17 +1,21 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.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.InputFile; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.io.File; import java.io.IOException; -import java.io.InputStream; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -19,6 +23,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class SetStickerSetThumb extends BotApiMethod { private static final String PATH = "setStickerSetThumb"; @@ -26,7 +37,9 @@ public class SetStickerSetThumb extends BotApiMethod { public static final String USERID_FIELD = "user_id"; public static final String THUMB_FIELD = "thumb"; + @NonNull private String name; ///< Sticker set name + @NonNull private Integer 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, @@ -36,58 +49,9 @@ public class SetStickerSetThumb extends BotApiMethod { * String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. * Animated sticker set thumbnail can't be uploaded via HTTP URL. */ + @NonNull private InputFile thumb; - public SetStickerSetThumb() { - super(); - } - - public SetStickerSetThumb(String name, Integer userId, InputFile thumb) { - this.name = name; - this.userId = userId; - this.thumb = thumb; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getUserId() { - return userId; - } - - public void setUserId(Integer userId) { - this.userId = userId; - } - - public InputFile getThumb() { - return thumb; - } - - public SetStickerSetThumb setThumb(String thumb) { - this.thumb = new InputFile(thumb); - return this; - } - - public SetStickerSetThumb setThumb(InputFile thumb) { - this.thumb = thumb; - return this; - } - - public SetStickerSetThumb setThumb(File thumbFile) { - this.thumb = new InputFile(checkNotNull(thumbFile), thumbFile.getName());; - return this; - } - - public SetStickerSetThumb setThumb(String thumbName, InputStream thumbStream) { - this.thumb = new InputFile(checkNotNull(thumbStream), checkNotNull(thumbName)); - return this; - } - @Override public String getMethod() { return PATH; @@ -121,13 +85,4 @@ public class SetStickerSetThumb extends BotApiMethod { } thumb.validate(); } - - @Override - public String toString() { - return "SetStickerSetThumb{" + - "name='" + name + '\'' + - ", userId=" + userId + - ", thumb=" + thumb + - '}'; - } } 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 894625b4..d64b006b 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 @@ -1,17 +1,22 @@ package org.telegram.telegrambots.meta.api.methods.stickers; 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.File; import org.telegram.telegrambots.meta.api.objects.InputFile; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.io.InputStream; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -19,28 +24,28 @@ import static com.google.common.base.Preconditions.checkNotNull; * Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet * methods (can be used multiple times). Returns the uploaded File on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class UploadStickerFile extends PartialBotApiMethod { public static final String PATH = "uploadStickerFile"; public static final String USERID_FIELD = "user_id"; public static final String PNGSTICKER_FIELD = "png_sticker"; + @NonNull private Integer 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 » */ + @NonNull private InputFile pngSticker; ///< New sticker file - public UploadStickerFile() { - super(); - } - - public UploadStickerFile(Integer userId) { - super(); - this.userId = checkNotNull(userId); - } - @Override public File deserializeResponse(String answer) throws TelegramApiRequestException { try { @@ -68,35 +73,4 @@ public class UploadStickerFile extends PartialBotApiMethod { pngSticker.validate(); } - - public Integer getUserId() { - return userId; - } - - public UploadStickerFile setUserId(Integer userId) { - this.userId = userId; - return this; - } - - public InputFile getPngSticker() { - return pngSticker; - } - - public UploadStickerFile setPngSticker(java.io.File pngSticker) { - this.pngSticker = new InputFile(pngSticker, pngSticker.getName()); - return this; - } - - public UploadStickerFile setPngSticker(String pngStickerName, InputStream pngStickerStream) { - this.pngSticker = new InputFile(pngStickerStream, pngStickerName); - return this; - } - - @Override - public String toString() { - return "UploadStickerFile{" + - "userId=" + userId + - ", pngSticker=" + pngSticker + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java new file mode 100644 index 00000000..0e40a1f1 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java @@ -0,0 +1,60 @@ +package org.telegram.telegrambots.meta.api.methods.updates; + +import com.fasterxml.jackson.core.type.TypeReference; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +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.WebhookInfo; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.4 + * Use this method to close the bot instance before moving it from one local server to another. + * You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. + * The method will return error 429 in the first 10 minutes after the bot is launched. + * Returns True on success. + * Requires no parameters. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@Builder +public class Close extends BotApiMethod { + public static final String PATH = "close"; + + @Override + public String getMethod() { + return PATH; + } + + @Override + public WebhookInfo 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 logging out info", result); + } + } catch (IOException e2) { + throw new TelegramApiRequestException("Unable to deserialize response", e2); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + } +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/DeleteWebhook.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/DeleteWebhook.java index f55154a1..7a471cd2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/DeleteWebhook.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/DeleteWebhook.java @@ -1,7 +1,14 @@ package org.telegram.telegrambots.meta.api.methods.updates; +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.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.exceptions.TelegramApiRequestException; @@ -15,12 +22,20 @@ import java.io.IOException; * Use this method to receive incoming updates using long polling (wiki). An Array of Update * objects is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class DeleteWebhook extends BotApiMethod{ public static final String PATH = "deleteWebhook"; - public DeleteWebhook() { - super(); - } + private static final String DROPPENDINGUPDATES_FIELD = "drop_pending_updates"; + + @JsonProperty(DROPPENDINGUPDATES_FIELD) + private Boolean dropPendingUpdates; ///< Optional. Pass True to drop all pending updates @Override public String getMethod() { @@ -46,9 +61,4 @@ public class DeleteWebhook extends BotApiMethod{ @Override public void validate() throws TelegramApiValidationException { } - - @Override - public String toString() { - return "DeleteWebhook{}"; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetUpdates.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetUpdates.java index 7a8ea35c..5da3e8f2 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetUpdates.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetUpdates.java @@ -2,10 +2,17 @@ package org.telegram.telegrambots.meta.api.methods.updates; 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.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -19,6 +26,13 @@ import java.util.List; * Use this method to receive incoming updates using long polling (wiki). An Array of Update * objects is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class GetUpdates extends BotApiMethod>{ public static final String PATH = "getupdates"; @@ -59,48 +73,9 @@ public class GetUpdates extends BotApiMethod>{ * so unwanted updates may be received for a short period of time. */ @JsonProperty(ALLOWEDUPDATES_FIELD) + @Singular private List allowedUpdates; - public GetUpdates() { - super(); - } - - public Integer getOffset() { - return offset; - } - - public GetUpdates setOffset(Integer offset) { - this.offset = offset; - return this; - } - - public Integer getLimit() { - return limit; - } - - public GetUpdates setLimit(Integer limit) { - this.limit = limit; - return this; - } - - public Integer getTimeout() { - return timeout; - } - - public GetUpdates setTimeout(Integer timeout) { - this.timeout = timeout; - return this; - } - - public List getAllowedUpdates() { - return allowedUpdates; - } - - public GetUpdates setAllowedUpdates(List allowedUpdates) { - this.allowedUpdates = allowedUpdates; - return this; - } - @Override public String getMethod() { return PATH; @@ -125,14 +100,4 @@ public class GetUpdates extends BotApiMethod>{ @Override public void validate() throws TelegramApiValidationException { } - - @Override - public String toString() { - return "GetUpdates{" + - "offset=" + offset + - ", limit=" + limit + - ", timeout=" + timeout + - ", allowedUpdates=" + allowedUpdates + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetWebhookInfo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetWebhookInfo.java index 5f966472..ffd0d242 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetWebhookInfo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/GetWebhookInfo.java @@ -1,10 +1,15 @@ package org.telegram.telegrambots.meta.api.methods.updates; import com.fasterxml.jackson.core.type.TypeReference; - +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.WebhookInfo; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.WebhookInfo; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -18,18 +23,15 @@ import java.io.IOException; * On success, returns a WebhookInfo object. * Will throw an error, if the bot is using getUpdates. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@AllArgsConstructor +@Builder public class GetWebhookInfo extends BotApiMethod { public static final String PATH = "getwebhookinfo"; - public GetWebhookInfo() { - super(); - } - - @Override - public String toString() { - return "GetWebhookInfo{}"; - } - @Override public String getMethod() { return PATH; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java new file mode 100644 index 00000000..5fa8dea4 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java @@ -0,0 +1,60 @@ +package org.telegram.telegrambots.meta.api.methods.updates; + +import com.fasterxml.jackson.core.type.TypeReference; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +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.WebhookInfo; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; + +/** + * @author Ruben Bermudez + * @version 2.4 + * Use this method to log out from the cloud Bot API server before launching the bot locally. + * You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. + * After a successful call, you will not be able to log in again using the same token for 10 minutes. + * Returns True on success. + * Requires no parameters. + */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@AllArgsConstructor +@Builder +public class LogOut extends BotApiMethod { + public static final String PATH = "logOut"; + + @Override + public String getMethod() { + return PATH; + } + + @Override + public WebhookInfo 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 logging out info", result); + } + } catch (IOException e2) { + throw new TelegramApiRequestException("Unable to deserialize response", e2); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + } +} 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 caee2cfe..551db122 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 @@ -1,31 +1,64 @@ package org.telegram.telegrambots.meta.api.methods.updates; +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.Singular; +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.InputFile; +import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; + +import java.io.IOException; import java.util.List; /** * @author Ruben Bermudez * @version 1.0 - * @brief Use this method to specify a url and receive incoming updates via an outgoing webhook. + * Use this method to specify a url and receive incoming updates via an outgoing webhook. * Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, * containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a * reasonable amount of attempts. - * @date 20 of June of 2015 + * 20 of June of 2015 */ -public class SetWebhook { - public static final String PATH = "setwebhook"; +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class SetWebhook extends BotApiMethod { + public static final String PATH = "setWebhook"; public static final String URL_FIELD = "url"; public static final String CERTIFICATE_FIELD = "certificate"; public static final String MAXCONNECTIONS_FIELD = "max_connections"; public static final String ALLOWEDUPDATES_FIELD = "allowed_updates"; + public static final String IPADDRESS_FIELD = "ip_address"; + public static final String DROPPENDINGUPDATES_FIELD = "drop_pending_updates"; + @JsonProperty(URL_FIELD) + @NonNull private String url; ///< Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration - private String certificateFile; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked + @JsonProperty(CERTIFICATE_FIELD) + private InputFile certificate; ///< Optional. Upload your public key certificate so that the root certificate in use can be checked /** * Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. * Defaults to 40. Use lower values to limit the load on your bot‘s server, * and higher values to increase your bot’s throughput. */ + @JsonProperty(MAXCONNECTIONS_FIELD) private Integer maxConnections; /** * List the types of updates you want your bot to receive. @@ -36,55 +69,43 @@ public class SetWebhook { * Please note that this parameter doesn't affect updates created before the call to the setWebhook, * so unwanted updates may be received for a short period of time. */ + @JsonProperty(ALLOWEDUPDATES_FIELD) + @Singular private List allowedUpdates; + @JsonProperty(IPADDRESS_FIELD) + private String ipAddress; + @JsonProperty(DROPPENDINGUPDATES_FIELD) + private Boolean dropPendingUpdates; - public SetWebhook() { - this.url = ""; - } - - public String getUrl() { - return url; - } - - public SetWebhook setUrl(String url) { - this.url = url; - return this; - } - - public String getCertificateFile() { - return certificateFile; - } - - public SetWebhook setCertificateFile(String certificateFile) { - this.certificateFile = certificateFile; - return this; - } - - public Integer getMaxConnections() { - return maxConnections; - } - - public SetWebhook setMaxConnections(Integer maxConnections) { - this.maxConnections = maxConnections; - return this; - } - - public List getAllowedUpdates() { - return allowedUpdates; - } - - public SetWebhook setAllowedUpdates(List allowedUpdates) { - this.allowedUpdates = allowedUpdates; - return this; + @Override + public String getMethod() { + return PATH; } @Override - public String toString() { - return "SetWebhook{" + - "url='" + url + '\'' + - ", certificateFile='" + certificateFile + '\'' + - ", maxConnections=" + maxConnections + - ", allowedUpdates=" + allowedUpdates + - '}'; + public Boolean 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 setting webhook", result); + } + } catch (IOException e) { + throw new TelegramApiRequestException("Unable to deserialize response", e); + } + } + + @Override + public void validate() throws TelegramApiValidationException { + if (url == null || url.isEmpty()) { + throw new TelegramApiValidationException("URL parameter can't be empty", this); + } + if (certificate != null) { + if (!certificate.isNew()) { + throw new TelegramApiValidationException("Certificate parameter must be a new file to upload", this); + } + } } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/DeleteMessage.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/DeleteMessage.java index ffabbcce..5a482899 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/DeleteMessage.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/DeleteMessage.java @@ -2,15 +2,20 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.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.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; /** * @author Ruben Bermudez @@ -25,6 +30,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class DeleteMessage extends BotApiMethod { public static final String PATH = "deleteMessage"; @@ -35,51 +47,15 @@ public class DeleteMessage extends BotApiMethod { * Unique identifier for the chat to send the message to (Or username for channels) */ @JsonProperty(CHATID_FIELD) + @NonNull private String chatId; /** * Identifier of the message to delete */ @JsonProperty(MESSAGEID_FIELD) + @NonNull private Integer messageId; - public DeleteMessage() { - super(); - } - - public DeleteMessage(String chatId, Integer messageId) { - this.chatId = checkNotNull(chatId); - this.messageId = checkNotNull(messageId); - } - - public DeleteMessage(Long chatId, Integer messageId) { - this.chatId = checkNotNull(chatId).toString(); - this.messageId = checkNotNull(messageId); - } - - public String getChatId() { - return chatId; - } - - public DeleteMessage setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public DeleteMessage setChatId(Long chatId) { - Objects.requireNonNull(chatId); - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public DeleteMessage setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - @Override public String getMethod() { return PATH; @@ -110,12 +86,4 @@ public class DeleteMessage extends BotApiMethod { throw new TelegramApiValidationException("MessageId parameter can't be empty", this); } } - - @Override - public String toString() { - return "DeleteMessage{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageCaption.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageCaption.java index 707b46b6..0ffb267c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageCaption.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageCaption.java @@ -2,16 +2,25 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.io.Serializable; +import java.util.List; /** * @author Ruben Bermudez @@ -19,6 +28,13 @@ import java.io.Serializable; * Use this method to edit captions of messages. * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class EditMessageCaption extends BotApiMethod { public static final String PATH = "editmessagecaption"; @@ -28,6 +44,7 @@ public class EditMessageCaption extends BotApiMethod { private static final String CAPTION_FIELD = "caption"; private static final String REPLYMARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; /** * Required if inline_message_id is not specified. Unique identifier for the chat to send the @@ -50,65 +67,10 @@ public class EditMessageCaption extends BotApiMethod { @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public EditMessageCaption() { - super(); - } - - public String getChatId() { - return chatId; - } - - public EditMessageCaption setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public EditMessageCaption setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public EditMessageCaption setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public String getCaption() { - return caption; - } - - public EditMessageCaption setCaption(String caption) { - this.caption = caption; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public EditMessageCaption setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public EditMessageCaption setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public String getMethod() { @@ -158,20 +120,11 @@ public class EditMessageCaption extends BotApiMethod { throw new TelegramApiValidationException("MessageId parameter must be empty if inlineMessageId is provided", this); } } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "EditMessageCaption{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", caption='" + caption + '\'' + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java index 2aa85ebc..823ba105 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageLiveLocation.java @@ -2,6 +2,14 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.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.Message; @@ -11,16 +19,22 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.io.Serializable; -import java.util.Objects; /** * @author Ruben Bermudez * @version 1.0 * Use this method to edit live location. * A location can be edited until its live_period expires or editing is explicitly disabled by a call to - * stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returned, + * stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, * otherwise True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class EditMessageLiveLocation extends BotApiMethod { public static final String PATH = "editMessageLiveLocation"; @@ -30,6 +44,9 @@ public class EditMessageLiveLocation extends BotApiMethod { private static final String LATITUDE_FIELD = "latitude"; private static final String LONGITUDE_FIELD = "longitude"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + private static final String HORIZONTALACCURACY_FIELD = "horizontal_accuracy"; + private static final String HEADING_FIELD = "heading"; + private static final String APPROACHINGNOTIFICATIONDISTANCE_FIELD = "approaching_notification_distance"; /** * Required if inline_message_id is not specified. Unique identifier for the chat to send the @@ -48,76 +65,33 @@ public class EditMessageLiveLocation extends BotApiMethod { @JsonProperty(INLINE_MESSAGE_ID_FIELD) private String inlineMessageId; @JsonProperty(LATITUDE_FIELD) - private Float latitude; ///< Latitude of new location + @NonNull + private Double latitude; ///< Latitude of new location @JsonProperty(LONGITUDE_FIELD) - private Float longitude; ///< Longitude of new location + @NonNull + private Double longitude; ///< Longitude of new location @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. - - public EditMessageLiveLocation() { - super(); - } - - public String getChatId() { - return chatId; - } - - public EditMessageLiveLocation setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public EditMessageLiveLocation setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public EditMessageLiveLocation setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public EditMessageLiveLocation setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public EditMessageLiveLocation setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Float getLatitude() { - return latitude; - } - - public EditMessageLiveLocation setLatitude(Float latitude) { - Objects.requireNonNull(latitude); - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public EditMessageLiveLocation setLongitude(Float longitude) { - Objects.requireNonNull(longitude); - this.longitude = longitude; - return this; - } + /** + * Optional. + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + @JsonProperty(HORIZONTALACCURACY_FIELD) + private Double horizontalAccuracy; + /** + * Optional. + * For live locations, a direction in which the user is moving, in degrees. + * Must be between 1 and 360 if specified. + */ + @JsonProperty(HEADING_FIELD) + private Integer heading; + /** + * Optional. + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. + * Must be between 1 and 100000 if specified. + */ + @JsonProperty(APPROACHINGNOTIFICATIONDISTANCE_FIELD) + private Integer approachingNotificationDistance; @Override public String getMethod() { @@ -173,20 +147,17 @@ public class EditMessageLiveLocation extends BotApiMethod { if (longitude == null) { throw new TelegramApiValidationException("Longitude parameter can't be empty", this); } + if (horizontalAccuracy != null && (horizontalAccuracy < 0 || horizontalAccuracy > 1500)) { + throw new TelegramApiValidationException("Horizontal Accuracy parameter must be between 0 and 1500", this); + } + if (heading != null && (heading < 1 || heading > 360)) { + throw new TelegramApiValidationException("Heading Accuracy parameter must be between 0 and 1500", this); + } + if (approachingNotificationDistance != null && (approachingNotificationDistance < 1 || approachingNotificationDistance > 100000)) { + throw new TelegramApiValidationException("Approaching notification distance parameter must be between 0 and 1500", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "EditMessageLiveLocation{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageMedia.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageMedia.java index 31a66cc7..1bd2348d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageMedia.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageMedia.java @@ -2,10 +2,19 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.PartialBotApiMethod; +import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.media.InputMedia; -import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -17,11 +26,20 @@ import java.io.Serializable; * @author Ruben Bermudez * @version 4.0.0 * Use this method to edit audio, document, photo, or video messages. - * If a message is a part of a message album, then it can be edited only to a photo or a video. - * Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. - * Use previously uploaded file via its file_id or specify a URL. + * f a message is part of a message album, then it can be edited only to an audio for audio albums, + * only to a document for document albums and to a photo or a video otherwise + * When an inline message is edited, a new file can't be uploaded. + * Use a previously uploaded file via its file_id or specify a URL. * On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class EditMessageMedia extends PartialBotApiMethod { public static final String PATH = "editMessageMedia"; @@ -50,65 +68,13 @@ public class EditMessageMedia extends PartialBotApiMethod { /** * A JSON-serialized object for a new media content of the message */ + @NonNull @JsonProperty(MEDIA_FIELD) private InputMedia media; @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. - public EditMessageMedia() { - super(); - } - - public String getChatId() { - return chatId; - } - - public EditMessageMedia setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public EditMessageMedia setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public EditMessageMedia setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public EditMessageMedia setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public InputMedia getMedia() { - return media; - } - - public void setMedia(InputMedia media) { - this.media = media; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public EditMessageMedia setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - @Override public Serializable deserializeResponse(String answer) throws TelegramApiRequestException { try { @@ -162,15 +128,4 @@ public class EditMessageMedia extends PartialBotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "EditMessageMedia{" + - "chatId='" + chatId + '\'' + - ", messageId=" + messageId + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", media=" + media + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageReplyMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageReplyMarkup.java index 2689e87f..ffa5bc0a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageReplyMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageReplyMarkup.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; -import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -20,6 +26,13 @@ import java.io.Serializable; * On success, if edited message is sent by the bot, the edited Message is returned, * otherwise True is returned. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class EditMessageReplyMarkup extends BotApiMethod { public static final String PATH = "editmessagereplymarkup"; @@ -47,51 +60,6 @@ public class EditMessageReplyMarkup extends BotApiMethod { @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. - public EditMessageReplyMarkup() { - super(); - } - - public String getChatId() { - return chatId; - } - - public EditMessageReplyMarkup setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public EditMessageReplyMarkup setChatId(Long chatId) { - this.chatId = chatId.toString(); - return this; - } - - public Integer getMessageId() { - return messageId; - } - - public EditMessageReplyMarkup setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public EditMessageReplyMarkup setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public EditMessageReplyMarkup setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - @Override public String getMethod() { return PATH; @@ -144,14 +112,4 @@ public class EditMessageReplyMarkup extends BotApiMethod { replyMarkup.validate(); } } - - @Override - public String toString() { - return "EditMessageReplyMarkup{" + - "chatId=" + chatId + - ", messageId=" + messageId + - ", inlineMessageId=" + inlineMessageId + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java index 5a0055f0..850fa5a3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java @@ -2,17 +2,27 @@ package org.telegram.telegrambots.meta.api.methods.updatingmessages; 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.methods.ParseMode; -import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.ApiResponse; +import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; import java.io.Serializable; +import java.util.List; /** * @author Ruben Bermudez @@ -20,6 +30,15 @@ import java.io.Serializable; * Use this method to edit text messages. On * success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. */ +@SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class EditMessageText extends BotApiMethod { public static final String PATH = "editmessagetext"; @@ -30,6 +49,7 @@ public class EditMessageText extends BotApiMethod { private static final String PARSE_MODE_FIELD = "parse_mode"; private static final String DISABLE_WEB_PREVIEW_FIELD = "disable_web_page_preview"; private static final String REPLYMARKUP_FIELD = "reply_markup"; + private static final String ENTITIES_FIELD = "entities"; /** * Required if inline_message_id is not specified. Unique identifier for the chat to send the @@ -51,6 +71,7 @@ public class EditMessageText extends BotApiMethod { * New text of the message */ @JsonProperty(TEXT_FIELD) + @NonNull private String text; /** * Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width @@ -62,93 +83,35 @@ public class EditMessageText extends BotApiMethod { private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in this message @JsonProperty(REPLYMARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. A JSON-serialized object for an inline keyboard. + @JsonProperty(ENTITIES_FIELD) + private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode - public EditMessageText() { - super(); - } - - public String getChatId() { - return chatId; - } - - public EditMessageText setChatId(String chatId) { - this.chatId = chatId; - return this; - } - - public EditMessageText setChatId(Long chatId) { + public void setChatId(Long chatId) { this.chatId = chatId.toString(); - return this; } - public Integer getMessageId() { - return messageId; - } - - public EditMessageText setMessageId(Integer messageId) { - this.messageId = messageId; - return this; - } - - public String getInlineMessageId() { - return inlineMessageId; - } - - public EditMessageText setInlineMessageId(String inlineMessageId) { - this.inlineMessageId = inlineMessageId; - return this; - } - - public String getText() { - return text; - } - - public EditMessageText setText(String text) { - this.text = text; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public EditMessageText setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public EditMessageText disableWebPagePreview() { + public void disableWebPagePreview() { disableWebPagePreview = true; - return this; } - public EditMessageText enableWebPagePreview() { + public void enableWebPagePreview() { disableWebPagePreview = null; - return this; } - public EditMessageText enableMarkdown(boolean enable) { + public void enableMarkdown(boolean enable) { if (enable) { this.parseMode = ParseMode.MARKDOWN; } else { this.parseMode = null; } - return this; } - public EditMessageText enableHtml(boolean enable) { + public void enableHtml(boolean enable) { if (enable) { this.parseMode = ParseMode.HTML; } else { this.parseMode = null; } - return this; - } - - - public EditMessageText setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; } @Override @@ -202,21 +165,11 @@ public class EditMessageText extends BotApiMethod { if (text == null || text.isEmpty()) { throw new TelegramApiValidationException("Text parameter can't be empty", this); } + if (parseMode != null && (entities != null && !entities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "EditMessageText{" + - "chatId=" + chatId + - ", messageId=" + messageId + - ", inlineMessageId=" + inlineMessageId + - ", text=" + text + - ", parseMode=" + parseMode + - ", disableWebPagePreview=" + disableWebPagePreview + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Audio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Audio.java index 62280fb7..7d8fb274 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Audio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Audio.java @@ -1,6 +1,12 @@ 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; /** @@ -8,6 +14,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 1.0 * This object represents an audio file */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Audio implements BotApiObject { private static final String FILEID_FIELD = "file_id"; @@ -18,6 +30,7 @@ public class Audio implements BotApiObject { private static final String TITLE_FIELD = "title"; private static final String PERFORMER_FIELD = "performer"; private static final String THUMB_FIELD = "thumb"; + private static final String FILENAME_FIELD = "file_name"; @JsonProperty(FILEID_FIELD) private String fileId; ///< Identifier for this file, which can be used to download or reuse the file @@ -39,54 +52,6 @@ public class Audio implements BotApiObject { private String performer; ///< Optional. Performer of the audio as defined by sender or by audio tags @JsonProperty(THUMB_FIELD) private PhotoSize thumb; ///< Optional. Thumbnail of the album cover to which the music file belongs - - public Audio() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getDuration() { - return duration; - } - - public String getMimeType() { - return mimeType; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getTitle() { - return title; - } - - public String getPerformer() { - return performer; - } - - public PhotoSize getThumb() { - return thumb; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Audio{" + - "fileId='" + fileId + '\'' + - ", duration=" + duration + - ", mimeType='" + mimeType + '\'' + - ", fileSize=" + fileSize + - ", title='" + title + '\'' + - ", performer='" + performer + '\'' + - ", thumb=" + thumb + - ", fileUniqueId=" + fileUniqueId + - '}'; - } + @JsonProperty(FILENAME_FIELD) + private String fileName; ///< Optional. Original filename as defined by sender } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/CallbackQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/CallbackQuery.java index 2f5b631d..2a7741c4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/CallbackQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/CallbackQuery.java @@ -1,24 +1,34 @@ 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 1.0 - * @brief This object represents an incoming callback query from a + * This object represents an incoming callback query from a * callback button in an inline keyboard. * If the button that originated the query was attached to a message sent by the bot, * the field message will be present. If the button was attached to a message sent via the bot * (in inline mode), the field inline_message_id will be present. - * @note Exactly one of the fields data or game_short_name will be present. - * @note After the user presses an inline button, Telegram clients will display a progress bar + * @apiNote Exactly one of the fields data or game_short_name will be present. + * @apiNote After the user presses an inline button, Telegram clients will display a progress bar * until you call answerCallbackQuery. It is, therefore, necessary to react by * calling answerCallbackQuery even if no notification to the user is needed * (e.g., without specifying any of the optional parameters). - * @date 10 of April of 2016 */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class CallbackQuery implements BotApiObject { private static final String ID_FIELD = "id"; @@ -37,7 +47,7 @@ public class CallbackQuery implements BotApiObject { * Optional. * Message with the callback button that originated the query. * - * @note The message content and message date will not be available if the message is too old + * @apiNote The message content and message date will not be available if the message is too old */ @JsonProperty(MESSAGE_FIELD) private Message message; @@ -46,7 +56,7 @@ public class CallbackQuery implements BotApiObject { /** * * Optional. Data associated with the callback button. - * @note Be aware that a bad client can send arbitrary data in this field + * @apiNote Be aware that a bad client can send arbitrary data in this field */ @JsonProperty(DATA_FIELD) private String data; @@ -61,49 +71,4 @@ public class CallbackQuery implements BotApiObject { */ @JsonProperty(CHAT_INSTANCE_FIELD) private String chatInstance; - - public CallbackQuery() { - super(); - } - - public String getId() { - return this.id; - } - - public User getFrom() { - return this.from; - } - - public Message getMessage() { - return this.message; - } - - public String getInlineMessageId() { - return this.inlineMessageId; - } - - public String getData() { - return data; - } - - public String getGameShortName() { - return gameShortName; - } - - public String getChatInstance() { - return chatInstance; - } - - @Override - public String toString() { - return "CallbackQuery{" + - "id='" + id + '\'' + - ", from=" + from + - ", message=" + message + - ", inlineMessageId='" + inlineMessageId + '\'' + - ", data='" + data + '\'' + - ", gameShortName='" + gameShortName + '\'' + - ", chatInstance='" + chatInstance + '\'' + - '}'; - } } 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 a02a06bc..67da7b76 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 @@ -3,10 +3,13 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +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.interfaces.BotApiObject; /** @@ -15,7 +18,10 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * This object represents a Telegram chat with an user or a group */ @SuppressWarnings("WeakerAccess") -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @@ -27,6 +33,7 @@ public class Chat implements BotApiObject { private static final String USERNAME_FIELD = "username"; private static final String FIRSTNAME_FIELD = "first_name"; private static final String LASTNAME_FIELD = "last_name"; + private static final String BIO_FIELD = "bio"; private static final String ALL_MEMBERS_ARE_ADMINISTRATORS_FIELD = "all_members_are_administrators"; private static final String PHOTO_FIELD = "photo"; private static final String DESCRIPTION_FIELD = "description"; @@ -36,6 +43,8 @@ public class Chat implements BotApiObject { private static final String CANSETSTICKERSET_FIELD = "can_set_sticker_set"; private static final String PERMISSIONS_FIELD = "permissions"; 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 USERCHATTYPE = "private"; private static final String GROUPCHATTYPE = "group"; @@ -53,7 +62,7 @@ public class Chat implements BotApiObject { private Long id; ///< Unique identifier for this chat, not exceeding 1e13 by absolute value @JsonProperty(TYPE_FIELD) @NonNull - private String type; ///< Type of the chat, one of “private”, “group” or “channel” + private String type; ///< Type of the chat, one of “private”, “group” or “channel” or "supergroup" @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title of the chat, only for channels and group chat @JsonProperty(FIRSTNAME_FIELD) @@ -80,7 +89,7 @@ public class Chat implements BotApiObject { @JsonProperty(INVITELINK_FIELD) private String inviteLink; @JsonProperty(PINNEDMESSAGE_FIELD) - private Message pinnedMessage; ///< Optional. Pinned message, for groups, supergroups and channels. Returned only in getChat. + private Message pinnedMessage; ///< Optional. The most recent pinned message (by sending date). Returned only in getChat. @JsonProperty(STICKERSETNAME_FIELD) private String stickerSetName; ///< Optional. For supergroups, name of Group sticker set. Returned only in getChat. @JsonProperty(CANSETSTICKERSET_FIELD) @@ -94,6 +103,22 @@ public class Chat implements BotApiObject { */ @JsonProperty(SLOWMODEDELAY_FIELD) private Integer slowModeDelay; + @JsonProperty(BIO_FIELD) + private String bio; ///< Optional. Bio of the other party in a private chat. Returned only in getChat. + /** + * Optional. + * Unique identifier for the linked chat, + * i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. + * This identifier may be greater than 32 bits and some programming + * languages may have difficulty/silent defects in interpreting it. + * But it is smaller than 52 bits, so a signed 64 bit integer or + * double-precision float type are safe for storing this identifier. + * Returned only in getChat. + */ + @JsonProperty(LINKEDCHATID_FIELD) + private Long linkedChatId; + @JsonProperty(LOCATION_FIELD) + private ChatLocation location; ///< Optional. For supergroups, the location to which the supergroup is connected. Returned only in getChat. @JsonIgnore public Boolean isGroupChat() { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatLocation.java new file mode 100644 index 00000000..08f4c1a7 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatLocation.java @@ -0,0 +1,33 @@ +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.0 + * Represents a location to which a chat is connected. + */ +@SuppressWarnings("WeakerAccess") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class ChatLocation implements BotApiObject { + + private static final String LOCATION_FIELD = "location"; + private static final String ADDRESS_FIELD = "address"; + + @JsonProperty(LOCATION_FIELD) + private Location location; ///< The location to which the supergroup is connected + @JsonProperty(ADDRESS_FIELD) + private String address; ///< Location address; 1-64 characters, as defined by the chat owner +} 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 3da476d3..cf69ca6e 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 @@ -1,6 +1,12 @@ 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; import java.time.Instant; @@ -10,6 +16,12 @@ import java.time.Instant; * @version 1.0 * This object contains information about one member of the chat. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class ChatMember implements BotApiObject { private static final String USER_FIELD = "user"; private static final String STATUS_FIELD = "status"; @@ -30,6 +42,7 @@ public class ChatMember implements BotApiObject { private static final String CAN_SEND_POLLS_FIELD = "can_send_polls"; private static final String ISMEMBER_FIELD = "is_member"; private static final String CUSTOMTITLE_FIELD = "custom_title"; + private static final String ISANONYMOUS_FIELD = "is_anonymous"; @JsonProperty(USER_FIELD) private User user; ///< Information about the user @@ -69,22 +82,8 @@ public class ChatMember implements BotApiObject { private Boolean isMemberField; ///< True, if the user is a member of the chat at the moment of the request. For example, it can be false for the chat creator or for a restricted user. @JsonProperty(CUSTOMTITLE_FIELD) private String customTitle; ///< Optional. Owner and administrators only. Custom title for this user - - public ChatMember() { - super(); - } - - public User getUser() { - return user; - } - - public String getStatus() { - return status; - } - - public Integer getUntilDate() { - return untilDate; - } + @JsonProperty(ISANONYMOUS_FIELD) + private Boolean isAnonymous; ///< Optional. Owner and administrators only. True, if the user's presence in the chat is hidden public Instant getUntilDateAsInstant() { if (untilDate == null) { @@ -92,93 +91,4 @@ public class ChatMember implements BotApiObject { } return Instant.ofEpochSecond(untilDate); } - - public Boolean getCanBeEdited() { - return canBeEdited; - } - - public Boolean getCanChangeInformation() { - return canChangeInformation; - } - - public Boolean getCanPostMessages() { - return canPostMessages; - } - - public Boolean getCanEditMessages() { - return canEditMessages; - } - - public Boolean getCanDeleteMessages() { - return canDeleteMessages; - } - - public Boolean getCanInviteUsers() { - return canInviteUsers; - } - - public Boolean getCanRestrictMembers() { - return canRestrictMembers; - } - - public Boolean getCanPinMessages() { - return canPinMessages; - } - - public Boolean getCanPromoteMembers() { - return canPromoteMembers; - } - - public Boolean getCanSendMessages() { - return canSendMessages; - } - - public Boolean getCanSendMediaMessages() { - return canSendMediaMessages; - } - - public Boolean getCanSendOtherMessages() { - return canSendOtherMessages; - } - - public Boolean getCanAddWebPagePreviews() { - return canAddWebPagePreviews; - } - - public Boolean getCanSendPolls() { - return canSendPolls; - } - - public Boolean getMemberField() { - return isMemberField; - } - - public String getCustomTitle() { - return customTitle; - } - - @Override - public String toString() { - return "ChatMember{" + - "user=" + user + - ", status='" + status + '\'' + - ", untilDate=" + untilDate + - ", canBeEdited=" + canBeEdited + - ", canChangeInformation=" + canChangeInformation + - ", canPostMessages=" + canPostMessages + - ", canEditMessages=" + canEditMessages + - ", canDeleteMessages=" + canDeleteMessages + - ", canInviteUsers=" + canInviteUsers + - ", canRestrictMembers=" + canRestrictMembers + - ", canPinMessages=" + canPinMessages + - ", canPromoteMembers=" + canPromoteMembers + - ", canSendMessages=" + canSendMessages + - ", canSendMediaMessages=" + canSendMediaMessages + - ", canSendOtherMessages=" + canSendOtherMessages + - ", canAddWebPagePreviews=" + canAddWebPagePreviews + - ", canSendPolls=" + canSendPolls + - ", isMemberField=" + isMemberField + - ", customTitle=" + customTitle + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java index 97c48de7..e75e9d66 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java @@ -1,6 +1,13 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** @@ -10,6 +17,13 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. * Returns True on success. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class ChatPermissions implements BotApiObject { private static final String CAN_SEND_MESSAGES_FIELD = "can_send_messages"; private static final String CAN_SEND_MEDIA_MESSAGES_FIELD = "can_send_media_messages"; @@ -36,86 +50,4 @@ public class ChatPermissions implements BotApiObject { private Boolean canInviteUsers; ///< Optional. True, if the user is allowed to invite new users to the chat @JsonProperty(CAN_PIN_MESSAGES_FIELD) private Boolean canPinMessages; ///< Optional. True, if the user is allowed to pin messages. Ignored in public supergroups - - public ChatPermissions() { - super(); - } - - public Boolean getCanSendMessages() { - return canSendMessages; - } - - public Boolean getGetCanSendMediaMessages() { - return getCanSendMediaMessages; - } - - public Boolean getCanSendPolls() { - return canSendPolls; - } - - public Boolean getCanSendOtherMessages() { - return canSendOtherMessages; - } - - public Boolean getCanAddWebPagePreviews() { - return canAddWebPagePreviews; - } - - public Boolean getCanChangeInfo() { - return canChangeInfo; - } - - public Boolean getCanInviteUsers() { - return canInviteUsers; - } - - public Boolean getCanPinMessages() { - return canPinMessages; - } - - public void setCanSendMessages(Boolean canSendMessages) { - this.canSendMessages = canSendMessages; - } - - public void setGetCanSendMediaMessages(Boolean getCanSendMediaMessages) { - this.getCanSendMediaMessages = getCanSendMediaMessages; - } - - public void setCanSendPolls(Boolean canSendPolls) { - this.canSendPolls = canSendPolls; - } - - public void setCanSendOtherMessages(Boolean canSendOtherMessages) { - this.canSendOtherMessages = canSendOtherMessages; - } - - public void setCanAddWebPagePreviews(Boolean canAddWebPagePreviews) { - this.canAddWebPagePreviews = canAddWebPagePreviews; - } - - public void setCanChangeInfo(Boolean canChangeInfo) { - this.canChangeInfo = canChangeInfo; - } - - public void setCanInviteUsers(Boolean canInviteUsers) { - this.canInviteUsers = canInviteUsers; - } - - public void setCanPinMessages(Boolean canPinMessages) { - this.canPinMessages = canPinMessages; - } - - @Override - public String toString() { - return "ChatPermissions{" + - "canSendMessages=" + canSendMessages + - ", getCanSendMediaMessages=" + getCanSendMediaMessages + - ", canSendPolls=" + canSendPolls + - ", canSendOtherMessages=" + canSendOtherMessages + - ", canAddWebPagePreviews=" + canAddWebPagePreviews + - ", canChangeInfo=" + canChangeInfo + - ", canInviteUsers=" + canInviteUsers + - ", canPinMessages=" + canPinMessages + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPhoto.java index aa7297a7..45f9a3f1 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPhoto.java @@ -1,6 +1,12 @@ 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; /** @@ -8,6 +14,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 1.0 * This object represents a chat photo (profile picture of a user, group or channel) */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class ChatPhoto implements BotApiObject { private static final String SMALLFILEID_FIELD = "small_file_id"; private static final String SMALLFILEUNIQUEID_FIELD = "small_file_unique_id"; @@ -40,34 +52,4 @@ public class ChatPhoto implements BotApiObject { */ @JsonProperty(BIGFILEUNIQUEID_FIELD) private String bigFileUniqueId; - - public ChatPhoto() { - super(); - } - - public String getSmallFileId() { - return smallFileId; - } - - public String getBigFileId() { - return bigFileId; - } - - public String getSmallFileUniqueId() { - return smallFileUniqueId; - } - - public String getBigFileUniqueId() { - return bigFileUniqueId; - } - - @Override - public String toString() { - return "ChatPhoto{" + - "smallFileId='" + smallFileId + '\'' + - ", smallFileUniqueId='" + smallFileUniqueId + '\'' + - ", bigFileId='" + bigFileId + '\'' + - ", bigFileUniqueId='" + bigFileUniqueId + '\'' + - '}'; - } } 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 ebcececf..580dbcb5 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 @@ -1,7 +1,12 @@ 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; /** @@ -9,6 +14,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 1.0 * This object represents a phone contact. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Contact implements BotApiObject { private static final String PHONENUMBER_FIELD = "phone_number"; @@ -27,39 +38,4 @@ public class Contact implements BotApiObject { private Integer 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 - - public Contact() { - super(); - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public Integer getUserID() { - return userID; - } - - public String getVCard() { - return vCard; - } - - @Override - public String toString() { - return "Contact{" + - "phoneNumber='" + phoneNumber + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", userID=" + userID + - ", vCard=" + 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 b0983a63..383ba043 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 @@ -1,6 +1,12 @@ 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; /** @@ -8,32 +14,24 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 4.7 * This object represents an animated emoji that displays a random value. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Dice implements BotApiObject { private static final String VALUE_FIELD = "value"; private static final String EMOJI_FIELD = "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) - private Integer value; ///< Value of the dice, 1-6 for “🎲” and “🎯” base emoji, 1-5 for “🏀” base emoji + private Integer value; @JsonProperty(EMOJI_FIELD) private String emoji; ///< Emoji on which the dice throw animation is based - - public Dice() { - super(); - } - - public Integer getValue() { - return value; - } - - public String getEmoji() { - return emoji; - } - - @Override - public String toString() { - return "Dice{" + - "value=" + value + - ", emoji='" + emoji + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Document.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Document.java index ff342b8c..b77dbfa6 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Document.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Document.java @@ -1,15 +1,26 @@ 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 1.0 - * @brief This object represents a general file (as opposed to photos and audio files). + * This object represents a general file (as opposed to photos and audio files). * Telegram users can send files of any type of up to 1.5 GB in size. - * @date 20 of June of 2015 */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Document implements BotApiObject { private static final String FILEID_FIELD = "file_id"; @@ -35,44 +46,4 @@ public class Document implements BotApiObject { private String mimeType; ///< Optional. Mime type of a file as defined by sender @JsonProperty(FILESIZE_FIELD) private Integer fileSize; ///< Optional. File size - - public Document() { - super(); - } - - public String getFileId() { - return fileId; - } - - public PhotoSize getThumb() { - return thumb; - } - - public String getFileName() { - return fileName; - } - - public String getMimeType() { - return mimeType; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Document{" + - "fileId='" + fileId + '\'' + - ", thumb=" + thumb + - ", fileName='" + fileName + '\'' + - ", mimeType='" + mimeType + '\'' + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/File.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/File.java index 24e00386..7d77abe3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/File.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/File.java @@ -1,6 +1,12 @@ 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; import java.security.InvalidParameterException; @@ -9,9 +15,14 @@ import java.text.MessageFormat; /** * @author Ruben Bermudez * @version 1.0 - * @brief This object represents a file ready to be downloaded - * @date 24 of June of 2015 + * This object represents a file ready to be downloaded */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class File implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -31,26 +42,6 @@ public class File implements BotApiObject { @JsonProperty(FILE_PATH_FIELD) private String filePath; ///< Optional. File path. Use https://api.telegram.org/file/bot/ to get the file. - public File() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFilePath() { - return filePath; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - public String getFileUrl(String botToken) { return getFileUrl(botToken, filePath); } @@ -61,14 +52,4 @@ public class File implements BotApiObject { } return MessageFormat.format("https://api.telegram.org/file/bot{0}/{1}", botToken, filePath); } - - @Override - public String toString() { - return "File{" + - "fileId='" + fileId + '\'' + - ", fileSize=" + fileSize + - ", filePath='" + filePath + '\'' + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java index 9326d2e9..0489b13a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/InputFile.java @@ -2,6 +2,10 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -17,6 +21,10 @@ import java.io.InputStream; */ @SuppressWarnings({"WeakerAccess", "UnusedReturnValue"}) @JsonSerialize(using = InputFileSerializer.class, as = String.class) +@EqualsAndHashCode(callSuper = false) +@ToString +@NoArgsConstructor +@AllArgsConstructor public class InputFile implements Validable, BotApiObject { private String attachName; @@ -30,15 +38,21 @@ public class InputFile implements Validable, BotApiObject { @JsonIgnore private boolean isNew; ///< True if the file is new, false if it is a file_id - public InputFile() { - super(); - } - public InputFile(String attachName) { this(); setMedia(attachName); } + /** + * Constructor to set a new file + * + * @param mediaFile File to send + */ + public InputFile(File mediaFile) { + this(); + setMedia(mediaFile, mediaFile.getName()); + } + /** * Constructor to set a new file * @@ -75,6 +89,19 @@ public class InputFile implements Validable, BotApiObject { return this; } + /** + * Use this setter to send new file. + * @param mediaFile File to send + * @return This object + */ + public InputFile setMedia(File mediaFile) { + this.newMediaFile = mediaFile; + this.mediaName = mediaFile.getName(); + this.attachName = "attach://" + mediaFile.getName(); + this.isNew = true; + return this; + } + /** * Use this setter to send new file as stream. * @param mediaStream File to send diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java index 6dac47db..e54bb614 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Location.java @@ -2,9 +2,12 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** @@ -12,13 +15,20 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 1.0 * This object represents a point on the map. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @AllArgsConstructor @NoArgsConstructor public class Location implements BotApiObject { private static final String LONGITUDE_FIELD = "longitude"; private static final String LATITUDE_FIELD = "latitude"; + private static final String HORIZONTALACCURACY_FIELD = "horizontal_accuracy"; + private static final String LIVEPERIOD_FIELD = "live_period"; + private static final String HEADING_FIELD = "heading"; + private static final String PROXMITYALERTDISTANCE_FIELD = "proximity_alert_distance"; @JsonProperty(LONGITUDE_FIELD) @NonNull @@ -26,4 +36,34 @@ public class Location implements BotApiObject { @JsonProperty(LATITUDE_FIELD) @NonNull private Double latitude; ///< Latitude as defined by sender + /** + * Optional. + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + @JsonProperty(HORIZONTALACCURACY_FIELD) + @NonNull + private Double horizontalAccuracy; + /** + * Optional. + * Time relative to the message sending date, during which the location will be updated, in seconds. + * For active live locations only. + */ + @JsonProperty(LIVEPERIOD_FIELD) + @NonNull + private Integer livePeriod; + /** + * Optional. + * The direction in which user is moving, in degrees; 1-360. For active live locations only. + */ + @JsonProperty(HEADING_FIELD) + @NonNull + private Integer heading; + /** + * Optional. + * A maximum distance for proximity alerts about approaching another chat member, in meters. + * For sent live locations only. + */ + @JsonProperty(PROXMITYALERTDISTANCE_FIELD) + @NonNull + private Integer proximityAlertDistance; } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java index 4b4821c7..b9c5514e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/LoginUrl.java @@ -1,14 +1,19 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.3 @@ -18,6 +23,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * All the user needs to do is tap/click a button and confirm that they want to log in. */ @SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class LoginUrl implements Validable, BotApiObject { private static final String URL_FIELD = "url"; private static final String FORWARD_TEXT_FIELD = "forward_text"; @@ -33,6 +46,7 @@ public class LoginUrl implements Validable, BotApiObject { * of the data as described in Checking authorization. */ @JsonProperty(URL_FIELD) + @NonNull private String url; @JsonProperty(FORWARD_TEXT_FIELD) private String forwardText; ///< Optional. New text of the button in forwarded messages. @@ -46,83 +60,10 @@ public class LoginUrl implements Validable, BotApiObject { @JsonProperty(REQUEST_WRITE_ACCESS_FIELD) private Boolean requestWriteAccess; ///< Optional. Pass True to request the permission for your bot to send messages to the user. - public LoginUrl() { - super(); - } - - public LoginUrl(String url) { - this.url = checkNotNull(url); - } - - public String getUrl() { - return url; - } - - public LoginUrl setUrl(String url) { - this.url = url; - return this; - } - - public String getForwardText() { - return forwardText; - } - - public LoginUrl setForwardText(String forwardText) { - this.forwardText = forwardText; - return this; - } - - public String getBotUsername() { - return botUsername; - } - - public LoginUrl setBotUsername(String botUsername) { - this.botUsername = botUsername; - return this; - - } - - public Boolean getRequestWriteAccess() { - return requestWriteAccess; - } - - public LoginUrl setRequestWriteAccess(Boolean requestWriteAccess) { - this.requestWriteAccess = requestWriteAccess; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (url == null || url.isEmpty()) { throw new TelegramApiValidationException("Url parameter can't be empty", this); } } - - @Override - public String toString() { - return "LoginUrl{" + - "url='" + url + '\'' + - ", forwardText='" + forwardText + '\'' + - ", botUsername='" + botUsername + '\'' + - ", requestWriteAccess=" + requestWriteAccess + - '}'; - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof LoginUrl)) { - return false; - } - LoginUrl loginUrl = (LoginUrl) o; - return Objects.equals(url, loginUrl.url) && - Objects.equals(forwardText, loginUrl.forwardText) && - Objects.equals(botUsername, loginUrl.botUsername) && - Objects.equals(requestWriteAccess, loginUrl.requestWriteAccess); - } - - @Override - public int hashCode() { - return Objects.hash(url, forwardText, botUsername, requestWriteAccess); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MemberStatus.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MemberStatus.java index 4b88a9c7..ebaeaad3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MemberStatus.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MemberStatus.java @@ -3,8 +3,7 @@ package org.telegram.telegrambots.meta.api.objects; /** * @author Ruben Bermudez * @version 1.0 - * @brief Group members categories - * @date 22 of May of 2016 + * Group members categories */ public final class MemberStatus { public static final String CREATOR = "creator"; 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 8db7b7cb..af516a77 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 @@ -3,10 +3,11 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.games.Animation; import org.telegram.telegrambots.meta.api.objects.games.Game; @@ -25,8 +26,10 @@ import java.util.List; * @version 1.0 * This object represents a message. */ -@Data -@RequiredArgsConstructor +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @NoArgsConstructor @AllArgsConstructor public class Message implements BotApiObject { @@ -79,22 +82,25 @@ public class Message implements BotApiObject { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String DICE_FIELD = "dice"; 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"; @JsonProperty(MESSAGEID_FIELD) - @NonNull private Integer messageId; ///< Integer Unique message identifier @JsonProperty(FROM_FIELD) private User from; ///< Optional. Sender, can be empty for messages sent to channels @JsonProperty(DATE_FIELD) - @NonNull - private Integer date; ///< ODate the message was sent in Unix time + private Integer date; ///< Date the message was sent in Unix time @JsonProperty(CHAT_FIELD) - @NonNull private Chat chat; ///< Conversation the message belongs to @JsonProperty(FORWARDFROM_FIELD) private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message + /** + * Optional. + * For messages forwarded from channels or from anonymous administrators, information about the original sender chat + */ @JsonProperty(FORWARDFROMCHAT_FIELD) - private Chat forwardFromChat; ///< Optional. For messages forwarded from a channel, information about the original channel + private Chat forwardFromChat; @JsonProperty(FORWARDDATE_FIELD) private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent @JsonProperty(TEXT_FIELD) @@ -201,8 +207,12 @@ public class Message implements BotApiObject { private SuccessfulPayment successfulPayment; ///< Optional. Message is a service message about a successful payment, information about the payment. @JsonProperty(VIDEO_NOTE_FIELD) private VideoNote videoNote; ///< Optional. Message is a video note, information about the video message + /** + * Optional. + * Signature of the post author for messages in channels, or the custom title of an anonymous group administrator + */ @JsonProperty(AUTHORSIGNATURE_FIELD) - private String authorSignature; ///< Optional. Post author signature for posts in channel chats + private String authorSignature; @JsonProperty(FORWARDSIGNATURE_FIELD) private String forwardSignature; ///< Optional. Post author signature for messages forwarded from channel chats @JsonProperty(MEDIAGROUPID_FIELD) @@ -226,6 +236,21 @@ public class Message implements BotApiObject { private Dice dice; // Optional. Message is a dice with random value from 1 to 6 @JsonProperty(VIABOT_FIELD) private User viaBot; // Optional. Bot through which the message was sent + /** + * Optional. + * Sender of the message, sent on behalf of a chat. The channel itself for channel messages. + * The supergroup itself for messages from anonymous group administrators. + * The linked channel for messages automatically forwarded to the discussion group + */ + @JsonProperty(SENDERCHAT_FIELD) + private Chat senderChat; + /** + * Optional. + * Service message. + * A user in the chat triggered another user's proximity alert while sharing Live Location. + */ + @JsonProperty(PROXIMITYALERTTRIGGERED_FIELD) + private ProximityAlertTriggered proximityAlertTriggered; public List getEntities() { if (entities != null) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageEntity.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageEntity.java index 801ab288..b65481de 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageEntity.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageEntity.java @@ -2,6 +2,15 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +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.interfaces.BotApiObject; /** @@ -11,6 +20,14 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * usernames, URL. */ @SuppressWarnings("WeakerAccess") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class MessageEntity implements BotApiObject { private static final String TYPE_FIELD = "type"; private static final String OFFSET_FIELD = "offset"; @@ -38,10 +55,13 @@ public class MessageEntity implements BotApiObject { */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(OFFSET_FIELD) + @NonNull private Integer offset; ///< Offset in UTF-16 code units to the start of the entity @JsonProperty(LENGTH_FIELD) + @NonNull private Integer length; ///< Length of the entity in UTF-16 code units @JsonProperty(URL_FIELD) private String url; ///< Optional. For “text_link” only, url that will be opened after user taps on the text @@ -52,54 +72,9 @@ public class MessageEntity implements BotApiObject { @JsonIgnore private String text; ///< Text present in the entity. Computed from offset and length - public MessageEntity() { - super(); - } - - public String getType() { - return type; - } - - public Integer getOffset() { - return offset; - } - - public Integer getLength() { - return length; - } - - public String getUrl() { - return url; - } - - public String getText() { - return text; - } - - public User getUser() { - return user; - } - - public String getLanguage() { - return language; - } - protected void computeText(String message) { if (message != null) { text = message.substring(offset, offset + length); } } - - @Override - public String toString() { - return "MessageEntity{" + - "type='" + type + '\'' + - ", offset=" + offset + - ", length=" + length + - ", url='" + url + '\'' + - ", user=" + user + - ", language='" + language + '\'' + - ", text='" + text + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageId.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageId.java new file mode 100644 index 00000000..cc9ffe01 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/MessageId.java @@ -0,0 +1,31 @@ +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.0 + * This object represents a unique message identifier. + */ +@SuppressWarnings("WeakerAccess") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class MessageId implements BotApiObject { + + private static final String MESSAGEID_FIELD = "message_id"; + + @JsonProperty(MESSAGEID_FIELD) + private Long messageId; ///< Unique message identifier + +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/PhotoSize.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/PhotoSize.java index d097d524..3c2ad13f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/PhotoSize.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/PhotoSize.java @@ -1,14 +1,25 @@ 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 1.0 - * @brief This object represents one size of a photo or a file / sticker thumbnail. - * @date 20 of June of 2015 + * This object represents one size of a photo or a file / sticker thumbnail. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PhotoSize implements BotApiObject { private static final String FILEID_FIELD = "file_id"; @@ -34,47 +45,4 @@ public class PhotoSize implements BotApiObject { private Integer fileSize; ///< Optional. File size @JsonProperty(FILEPATH_FIELD) private String filePath; ///< Undocumented field. Optional. Can contain the path to download the file directly without calling to getFile - - public PhotoSize() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFilePath() { - return filePath; - } - - public boolean hasFilePath() { - return filePath != null && !filePath.isEmpty(); - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "PhotoSize{" + - "fileId='" + fileId + '\'' + - ", width=" + width + - ", height=" + height + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ProximityAlertTriggered.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ProximityAlertTriggered.java new file mode 100644 index 00000000..089b43d2 --- /dev/null +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ProximityAlertTriggered.java @@ -0,0 +1,37 @@ +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.0 + * This object represents the content of a service message, + * sent whenever a user in the chat triggers a proximity alert set by another user. + */ +@SuppressWarnings("WeakerAccess") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class ProximityAlertTriggered implements BotApiObject { + + private static final String TRAVELER_FIELD = "traveler"; + private static final String WATCHER_FIELD = "watcher"; + private static final String DISTANCE_FIELD = "distance"; + + @JsonProperty(TRAVELER_FIELD) + private User traveler; ///< User that triggered the alert + @JsonProperty(WATCHER_FIELD) + private User watcher; ///< User that set the alert + @JsonProperty(DISTANCE_FIELD) + private Integer distance; ///< The distance between the users +} diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ResponseParameters.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ResponseParameters.java index 11a54f88..412a1d64 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ResponseParameters.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ResponseParameters.java @@ -19,14 +19,25 @@ 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 1.0 - * @brief Contains information about why a request was unsuccessfull. - * @date 28 of September of 2016 + * Contains information about why a request was unsuccessfull. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class ResponseParameters implements BotApiObject { private static final String MIGRATETOCHATID_FIELD = "migrate_to_chat_id"; private static final String RETRYAFTER_FIELD = "retry_after"; @@ -45,24 +56,4 @@ public class ResponseParameters implements BotApiObject { */ @JsonProperty(RETRYAFTER_FIELD) private Integer retryAfter; - - public ResponseParameters() { - super(); - } - - public Long getMigrateToChatId() { - return migrateToChatId; - } - - public Integer getRetryAfter() { - return retryAfter; - } - - @Override - public String toString() { - return "ResponseParameters{" + - "migrateToChatId=" + migrateToChatId + - ", retryAfter=" + retryAfter + - '}'; - } } 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 531962e8..6bae4a45 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 @@ -1,6 +1,12 @@ 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; import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; @@ -17,6 +23,12 @@ import org.telegram.telegrambots.meta.api.objects.polls.PollAnswer; * * @apiNote Only one of the optional parameters can be present in any given update. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Update implements BotApiObject { private static final String UPDATEID_FIELD = "update_id"; private static final String MESSAGE_FIELD = "message"; @@ -62,59 +74,6 @@ public class Update implements BotApiObject { @JsonProperty(POLLANSWER_FIELD) private PollAnswer pollAnswer; - - public Update() { - super(); - } - - public Integer getUpdateId() { - return updateId; - } - - public Message getMessage() { - return message; - } - - public InlineQuery getInlineQuery() { - return inlineQuery; - } - - public ChosenInlineQuery getChosenInlineQuery() { - return chosenInlineQuery; - } - - public CallbackQuery getCallbackQuery() { - return callbackQuery; - } - - public Message getEditedMessage() { - return editedMessage; - } - - public Message getChannelPost() { - return channelPost; - } - - public Message getEditedChannelPost() { - return editedChannelPost; - } - - public ShippingQuery getShippingQuery() { - return shippingQuery; - } - - public PreCheckoutQuery getPreCheckoutQuery() { - return preCheckoutQuery; - } - - public Poll getPoll() { - return poll; - } - - public PollAnswer getPollAnswer() { - return pollAnswer; - } - public boolean hasMessage() { return message != null; } @@ -158,22 +117,4 @@ public class Update implements BotApiObject { public boolean hasPollAnswer() { return pollAnswer != null; } - - @Override - public String toString() { - return "Update{" + - "updateId=" + updateId + - ", message=" + message + - ", inlineQuery=" + inlineQuery + - ", chosenInlineQuery=" + chosenInlineQuery + - ", callbackQuery=" + callbackQuery + - ", editedMessage=" + editedMessage + - ", channelPost=" + channelPost + - ", editedChannelPost=" + editedChannelPost + - ", shippingQuery=" + shippingQuery + - ", preCheckoutQuery=" + preCheckoutQuery + - ", poll=" + poll + - ", pollAnswer=" + pollAnswer + - '}'; - } } 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 32501eae..28c18079 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 @@ -2,10 +2,13 @@ package org.telegram.telegrambots.meta.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +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.interfaces.BotApiObject; /** @@ -13,7 +16,10 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 3.0 * This object represents a Telegram user or bot. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/UserProfilePhotos.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/UserProfilePhotos.java index 7c88e70a..8b88895f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/UserProfilePhotos.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/UserProfilePhotos.java @@ -2,6 +2,12 @@ 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; import java.util.List; @@ -9,9 +15,14 @@ import java.util.List; /** * @author Ruben Bermudez * @version 1.0 - * @brief This object represent a user's profile pictures. - * @date 22 of June of 2015 + * This object represent a user's profile pictures. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class UserProfilePhotos implements BotApiObject { private static final String TOTALCOUNT_FIELD = "total_count"; @@ -21,24 +32,4 @@ public class UserProfilePhotos implements BotApiObject { private Integer totalCount; ///< Total number of profile pictures the target user has @JsonProperty(PHOTOS_FIELD) private List> photos; ///< Requested profile pictures (in up to 4 sizes each) - - public UserProfilePhotos() { - super(); - } - - public Integer getTotalCount() { - return totalCount; - } - - public List> getPhotos() { - return photos; - } - - @Override - public String toString() { - return "UserProfilePhotos{" + - "totalCount=" + totalCount + - ", photos=" + photos + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Venue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Venue.java index fcc0cb1c..4c5eb831 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Venue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Venue.java @@ -2,6 +2,12 @@ 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; /** @@ -9,12 +15,20 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 1.0 * This object represents a venue. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Venue implements BotApiObject { private static final String LOCATION_FIELD = "location"; private static final String TITLE_FIELD = "title"; private static final String ADDRESS_FIELD = "address"; private static final String FOURSQUAREID_FIELD = "foursquare_id"; private static final String FOURSQUARETYPE_FIELD = "foursquare_type"; + private static final String GOOGLEPLACEID_FIELD = "google_place_id"; + private static final String GOOGLEPLACETYPE_FIELD = "google_place_type"; @JsonProperty(LOCATION_FIELD) private Location location; ///< Venue location @@ -26,39 +40,8 @@ public class Venue implements BotApiObject { private String foursquareId; ///< Optional. Foursquare identifier of the venue @JsonProperty(FOURSQUARETYPE_FIELD) private String foursquareType; ///< Optional. Foursquare type of the venue. - - public Venue() { - super(); - } - - public Location getLocation() { - return location; - } - - public String getTitle() { - return title; - } - - public String getAddress() { - return address; - } - - public String getFoursquareId() { - return foursquareId; - } - - public String getFoursquareType() { - return foursquareType; - } - - @Override - public String toString() { - return "Venue{" + - "location=" + location + - ", title='" + title + '\'' + - ", address='" + address + '\'' + - ", foursquareId='" + foursquareId + '\'' + - ", foursquareType='" + foursquareType + '\'' + - '}'; - } + @JsonProperty(GOOGLEPLACEID_FIELD) + private String googlePlaceId; ///< Optional. Google Places identifier of the venue + @JsonProperty(GOOGLEPLACETYPE_FIELD) + private String googlePlaceType; ///< Optional. Google Places type of the venue. (See supported types.) } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Video.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Video.java index 78467f0d..7114fc12 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Video.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Video.java @@ -1,14 +1,25 @@ 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 1.0 - * @brief This object represents a video file. - * @date 20 of June of 2015 + * This object represents a video file. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Video implements BotApiObject { private static final String FILEID_FIELD = "file_id"; @@ -19,6 +30,7 @@ public class Video implements BotApiObject { private static final String THUMB_FIELD = "thumb"; private static final String MIMETYPE_FIELD = "mime_type"; private static final String FILESIZE_FIELD = "file_size"; + private static final String FILENAME_FIELD = "file_name"; @JsonProperty(FILEID_FIELD) private String fileId; ///< Identifier for this file, which can be used to download or reuse the file @@ -40,54 +52,6 @@ public class Video implements BotApiObject { private String mimeType; ///< Optional. Mime type of a file as defined by sender @JsonProperty(FILESIZE_FIELD) private Integer fileSize; ///< Optional. File size - - public Video() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - public Integer getDuration() { - return duration; - } - - public PhotoSize getThumb() { - return thumb; - } - - public String getMimeType() { - return mimeType; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Video{" + - "fileId='" + fileId + '\'' + - ", width=" + width + - ", height=" + height + - ", duration=" + duration + - ", thumb=" + thumb + - ", mimeType='" + mimeType + '\'' + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } + @JsonProperty(FILENAME_FIELD) + private String fileName; ///< Optional. Original filename as defined by sender } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/VideoNote.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/VideoNote.java index 53698020..e23c4b84 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/VideoNote.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/VideoNote.java @@ -1,6 +1,12 @@ 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * * This object represents a video message (available in Telegram apps as of v.4.0). */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class VideoNote implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -33,44 +45,4 @@ public class VideoNote implements BotApiObject { private PhotoSize thumb; ///< Optional. Video thumbnail @JsonProperty(FILESIZE_FIELD) private Integer fileSize; ///< Optional. File size - - public VideoNote() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getLength() { - return length; - } - - public Integer getDuration() { - return duration; - } - - public PhotoSize getThumb() { - return thumb; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "VideoNote{" + - "fileId='" + fileId + '\'' + - ", length=" + length + - ", duration=" + duration + - ", thumb=" + thumb + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Voice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Voice.java index 4025d8ef..b0ad5231 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Voice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/Voice.java @@ -1,14 +1,25 @@ 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 1.0 - * @brief This object represents a voice note - * @date 16 of July of 2015 + * This object represents a voice note */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Voice implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -30,39 +41,4 @@ public class Voice implements BotApiObject { private String mimeType; ///< Optional. MIME type of the file as defined by sender @JsonProperty(FILESIZE_FIELD) private Integer fileSize; ///< Optional. File size - - public Voice() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getDuration() { - return duration; - } - - public String getMimeType() { - return mimeType; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Voice{" + - "fileId='" + fileId + '\'' + - ", duration=" + duration + - ", mimeType='" + mimeType + '\'' + - ", fileSize=" + fileSize + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/WebhookInfo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/WebhookInfo.java index ba573b9b..ea580761 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/WebhookInfo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/WebhookInfo.java @@ -1,7 +1,12 @@ 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; import java.util.List; @@ -9,9 +14,14 @@ import java.util.List; /** * @author Ruben Bermudez * @version 2.4 - * @brief Contains information about the current status of a webhook. - * @date 12 of August of 2016 + * Contains information about the current status of a webhook. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class WebhookInfo implements BotApiObject { private static final String URL_FIELD = "url"; @@ -21,6 +31,7 @@ public class WebhookInfo implements BotApiObject { private static final String ALLOWEDUPDATES_FIELD = "allowed_updates"; private static final String LASTERRORDATE_FIELD = "last_error_date"; private static final String LASTERRORMESSAGE_FIELD = "last_error_message"; + private static final String IPADDRESS_FIELD = "ip_address"; @JsonProperty(URL_FIELD) private String url; ///< Webhook URL, may be empty if webhook is not set up @@ -36,36 +47,6 @@ public class WebhookInfo implements BotApiObject { private Integer maxConnections; ///< Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery @JsonProperty(ALLOWEDUPDATES_FIELD) private List allowedUpdates; ///< Optional. A list of update types the bot is subscribed to. Defaults to all update types - - public WebhookInfo() { - super(); - } - - public String getUrl() { - return url; - } - - public boolean isHasCustomCertificate() { - return hasCustomCertificate; - } - - public int getPendingUpdatesCount() { - return pendingUpdatesCount; - } - - public int getLastErrorDate() { - return lastErrorDate; - } - - public String getLastErrorMessage() { - return lastErrorMessage; - } - - public Integer getMaxConnections() { - return maxConnections; - } - - public List getAllowedUpdates() { - return allowedUpdates; - } + @JsonProperty(IPADDRESS_FIELD) + private String ipAddress; ///< Optional. Currently used webhook IP address } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java index e3b4dfbb..3143589b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/commands/BotCommand.java @@ -3,9 +3,12 @@ package org.telegram.telegrambots.meta.api.objects.commands; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -15,7 +18,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * @version 4.7 * This object represents a bot command. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @NoArgsConstructor @AllArgsConstructor @Builder diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java index 6fd19f03..bf05871f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Animation.java @@ -18,10 +18,13 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -30,7 +33,10 @@ import org.telegram.telegrambots.meta.api.objects.PhotoSize; * @version 2.4 * This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java index 0aec927c..329c2554 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/CallbackGame.java @@ -17,8 +17,11 @@ package org.telegram.telegrambots.meta.api.objects.games; -import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; /** @@ -26,7 +29,10 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * @version 2.4 * A placeholder, currently holds no information. Use BotFather to set up your game. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @NoArgsConstructor public class CallbackGame implements BotApiObject { } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java index 8ddbfd3e..f6e05d4f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/Game.java @@ -18,10 +18,13 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.PhotoSize; @@ -34,7 +37,10 @@ import java.util.List; * This object represents a game. * @apiNote Use BotFather to create and edit games, their short names will act as unique identifiers. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java index 86bf27a8..401c99d0 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/games/GameHighScore.java @@ -19,9 +19,12 @@ package org.telegram.telegrambots.meta.api.objects.games; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.User; @@ -30,7 +33,10 @@ import org.telegram.telegrambots.meta.api.objects.User; * @version 1.0 * This object represents one row of a game high scores table */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @NoArgsConstructor @AllArgsConstructor public class GameHighScore implements BotApiObject { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java index 09d11e69..54a2d168 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/ChosenInlineQuery.java @@ -1,13 +1,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; - import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -18,7 +20,10 @@ import org.telegram.telegrambots.meta.api.objects.User; * Represents a result of an inline query that was chosen by the user and sent to their chat * partner. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java index 4049e4f9..8ef0bb7e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/InlineQuery.java @@ -1,13 +1,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery; import com.fasterxml.jackson.annotation.JsonProperty; - import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.objects.Location; import org.telegram.telegrambots.meta.api.objects.User; @@ -18,7 +20,10 @@ import org.telegram.telegrambots.meta.api.objects.User; * This object represents an incoming inline query. When the user sends an empty query, your * bot could return some default or trending results. */ -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java index 2cdc30a4..d4cf28e3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputContactMessageContent.java @@ -4,10 +4,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.exceptions.TelegramApiValidationException; /** @@ -18,7 +21,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * ignore them. */ @JsonDeserialize -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java index 66656f0c..957f7062 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputLocationMessageContent.java @@ -4,10 +4,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.exceptions.TelegramApiValidationException; /** @@ -18,7 +21,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * ignore them. */ @JsonDeserialize -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @@ -28,15 +34,38 @@ public class InputLocationMessageContent implements InputMessageContent { private static final String LATITUDE_FIELD = "latitude"; private static final String LONGITUDE_FIELD = "longitude"; private static final String LIVEPERIOD_FIELD = "live_period"; + private static final String HORIZONTALACCURACY_FIELD = "horizontal_accuracy"; + private static final String HEADING_FIELD = "heading"; + private static final String APPROACHINGNOTIFICATIONDISTANCE_FIELD = "approaching_notification_distance"; @JsonProperty(LATITUDE_FIELD) @NonNull - private Float latitude; ///< Latitude of the location in degrees + private Double latitude; ///< Latitude of the location in degrees @JsonProperty(LONGITUDE_FIELD) @NonNull - private Float longitude; ///< Longitude of the location in degrees + private Double longitude; ///< Longitude of the location in degrees @JsonProperty(LIVEPERIOD_FIELD) private Integer livePeriod; ///< Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. + /** + * Optional. + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + @JsonProperty(HORIZONTALACCURACY_FIELD) + private Double horizontalAccuracy; + /** + * Optional. + * For live locations, a direction in which the user is moving, in degrees. + * Must be between 1 and 360 if specified. + */ + @JsonProperty(HEADING_FIELD) + private Integer heading; + /** + * Optional. + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. + * Must be between 1 and 100000 if specified. + */ + @JsonProperty(APPROACHINGNOTIFICATIONDISTANCE_FIELD) + private Integer approachingNotificationDistance; @Override public void validate() throws TelegramApiValidationException { @@ -49,5 +78,14 @@ public class InputLocationMessageContent implements InputMessageContent { if (livePeriod != null && (livePeriod < 60 || livePeriod > 86400)) { throw new TelegramApiValidationException("Live period parameter must be between 60 and 86400", this); } + if (horizontalAccuracy != null && (horizontalAccuracy < 0 || horizontalAccuracy > 1500)) { + throw new TelegramApiValidationException("Horizontal Accuracy parameter must be between 0 and 1500", this); + } + if (heading != null && (heading < 1 || heading > 360)) { + throw new TelegramApiValidationException("Heading Accuracy parameter must be between 0 and 1500", this); + } + if (approachingNotificationDistance != null && (approachingNotificationDistance < 1 || approachingNotificationDistance > 100000)) { + throw new TelegramApiValidationException("Approaching notification distance parameter must be between 0 and 1500", this); + } } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java index 3c86b2c7..13dd6101 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputTextMessageContent.java @@ -4,19 +4,28 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents the content of a text message to be sent as the result of an inline query. */ @JsonDeserialize -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @@ -26,6 +35,7 @@ public class InputTextMessageContent implements InputMessageContent { private static final String MESSAGETEXT_FIELD = "message_text"; private static final String PARSEMODE_FIELD = "parse_mode"; private static final String DISABLEWEBPAGEPREVIEW_FIELD = "disable_web_page_preview"; + private static final String ENTITIES_FIELD = "entities"; @JsonProperty(MESSAGETEXT_FIELD) @NonNull @@ -34,11 +44,16 @@ public class InputTextMessageContent implements InputMessageContent { private String parseMode; ///< Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. @JsonProperty(DISABLEWEBPAGEPREVIEW_FIELD) private Boolean disableWebPagePreview; ///< Optional. Disables link previews for links in the sent message + @JsonProperty(ENTITIES_FIELD) + private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { if (messageText == null || messageText.isEmpty()) { throw new TelegramApiValidationException("MessageText parameter can't be empty", this); } + if (parseMode != null && (entities != null && !entities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java index 58d6a312..5ecad742 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/inputmessagecontent/InputVenueMessageContent.java @@ -1,14 +1,16 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +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.exceptions.TelegramApiValidationException; /** @@ -19,7 +21,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * ignore them. */ @JsonDeserialize -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @@ -32,6 +37,8 @@ public class InputVenueMessageContent implements InputMessageContent { private static final String ADDRESS_FIELD = "address"; private static final String FOURSQUAREID_FIELD = "foursquare_id"; private static final String FOURSQUARETYPE_FIELD = "foursquare_type"; + private static final String GOOGLEPLACEID_FIELD = "google_place_id"; + private static final String GOOGLEPLACETYPE_FIELD = "google_place_type"; @JsonProperty(LATITUDE_FIELD) @NonNull @@ -49,6 +56,10 @@ public class InputVenueMessageContent implements InputMessageContent { private String foursquareId; ///< Optional. Foursquare identifier of the venue, if known @JsonProperty(FOURSQUARETYPE_FIELD) private String foursquareType; ///< Optional. Foursquare type of the venue, if known. + @JsonProperty(GOOGLEPLACEID_FIELD) + private String googlePlaceId; ///< Optional. Google Places identifier of the venue + @JsonProperty(GOOGLEPLACETYPE_FIELD) + private String googlePlaceType; ///< Optional. Google Places type of the venue. (See supported types.) @Override public void validate() throws TelegramApiValidationException { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultArticle.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultArticle.java index d7eba9e2..2a862217 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultArticle.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultArticle.java @@ -1,8 +1,16 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -13,6 +21,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * Represents a link to an article or web page. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultArticle implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -30,10 +46,13 @@ public class InlineQueryResultArticle implements InlineQueryResult { @JsonProperty(TYPE_FIELD) private final String type = "article"; ///< Type of the result, must be “article” @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Title of the result @JsonProperty(INPUTMESSAGECONTENT_FIELD) + @NonNull private InputMessageContent inputMessageContent; ///< Content of the message to be sent @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @@ -50,104 +69,6 @@ public class InlineQueryResultArticle implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height - public InlineQueryResultArticle() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultArticle setId(String id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultArticle setTitle(String title) { - this.title = title; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultArticle setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultArticle setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getUrl() { - return url; - } - - public InlineQueryResultArticle setUrl(String url) { - this.url = url; - return this; - } - - public Boolean getHideUrl() { - return hideUrl; - } - - public InlineQueryResultArticle setHideUrl(Boolean hideUrl) { - this.hideUrl = hideUrl; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultArticle setDescription(String description) { - this.description = description; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultArticle setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public Integer getThumbWidth() { - return thumbWidth; - } - - public InlineQueryResultArticle setThumbWidth(Integer thumbWidth) { - this.thumbWidth = thumbWidth; - return this; - } - - public Integer getThumbHeight() { - return thumbHeight; - } - - public InlineQueryResultArticle setThumbHeight(Integer thumbHeight) { - this.thumbHeight = thumbHeight; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -164,21 +85,4 @@ public class InlineQueryResultArticle implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultArticle{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", title='" + title + '\'' + - ", inputMessageContent='" + inputMessageContent + '\'' + - ", replyMarkup='" + replyMarkup + '\'' + - ", url='" + url + '\'' + - ", hideUrl=" + hideUrl + - ", description='" + description + '\'' + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbWidth=" + thumbWidth + - ", thumbHeight=" + thumbHeight + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultAudio.java index d20157e8..84e50485 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultAudio.java @@ -3,20 +3,41 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to an mp3 audio file. By default, this audio file will be sent by the * user. Alternatively, you can use input_message_content to send a message with the specified * content instead of the audio. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultAudio implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -29,12 +50,15 @@ public class InlineQueryResultAudio implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "audio"; ///< Type of the result, must be "audio" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result @JsonProperty(AUDIOURL_FIELD) + @NonNull private String audioUrl; ///< A valid URL for the audio file @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @@ -49,96 +73,10 @@ public class InlineQueryResultAudio implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultAudio() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultAudio setId(String id) { - this.id = id; - return this; - } - - public String getAudioUrl() { - return audioUrl; - } - - public InlineQueryResultAudio setAudioUrl(String audioUrl) { - this.audioUrl = audioUrl; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultAudio setTitle(String title) { - this.title = title; - return this; - } - - public String getPerformer() { - return performer; - } - - public InlineQueryResultAudio setPerformer(String performer) { - this.performer = performer; - return this; - } - - public Integer getAudioDuration() { - return audioDuration; - } - - public InlineQueryResultAudio setAudioDuration(Integer audioDuration) { - this.audioDuration = audioDuration; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultAudio setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultAudio setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultAudio setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultAudio setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -148,6 +86,9 @@ public class InlineQueryResultAudio implements InlineQueryResult { if (audioUrl == null || audioUrl.isEmpty()) { throw new TelegramApiValidationException("AudioUrl parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -155,20 +96,4 @@ public class InlineQueryResultAudio implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultAudio{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", audioUrl='" + audioUrl + '\'' + - ", title='" + title + '\'' + - ", performer='" + performer + '\'' + - ", audioDuration=" + audioDuration + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultContact.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultContact.java index 49b0a38c..ab3fd78e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultContact.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultContact.java @@ -2,6 +2,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -12,10 +21,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * Represents a contact with a phone number. By default, this contact will be sent by the * user. Alternatively, you can use input_message_content to send a message with the specified * content instead of the contact. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultContact implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -33,13 +50,16 @@ public class InlineQueryResultContact implements InlineQueryResult { @JsonProperty(TYPE_FIELD) private final String type = "contact"; ///< Type of the result, must be "contact" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHONE_NUMBER_FIELD) + @NonNull private String phoneNumber; ///< Contact's phone number @JsonProperty(FIRST_NAME_FIELD) + @NonNull private String firstName; ///< Contact's first name @JsonProperty(LAST_NAME_FIELD) - private String lastName; ///< Contact's last name + private String lastName; ///< Optional. Contact's last name @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(INPUTMESSAGECONTENT_FIELD) @@ -53,104 +73,6 @@ public class InlineQueryResultContact implements InlineQueryResult { @JsonProperty(VCARD_FIELD) private String vCard; ///< Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes - public InlineQueryResultContact() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultContact setId(String id) { - this.id = id; - return this; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public InlineQueryResultContact setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public String getFirstName() { - return firstName; - } - - public InlineQueryResultContact setFirstName(String firstName) { - this.firstName = firstName; - return this; - } - - public String getLastName() { - return lastName; - } - - public InlineQueryResultContact setLastName(String lastName) { - this.lastName = lastName; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultContact setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultContact setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultContact setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public Integer getThumbWidth() { - return thumbWidth; - } - - public InlineQueryResultContact setThumbWidth(Integer thumbWidth) { - this.thumbWidth = thumbWidth; - return this; - } - - public Integer getThumbHeight() { - return thumbHeight; - } - - public InlineQueryResultContact setThumbHeight(Integer thumbHeight) { - this.thumbHeight = thumbHeight; - return this; - } - - public String getvCard() { - return vCard; - } - - public InlineQueryResultContact setvCard(String vCard) { - this.vCard = vCard; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -169,21 +91,4 @@ public class InlineQueryResultContact implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultContact{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", phoneNumber='" + phoneNumber + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", replyMarkup=" + replyMarkup + - ", inputMessageContent=" + inputMessageContent + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbWidth=" + thumbWidth + - ", thumbHeight=" + thumbHeight + - ", vCard='" + vCard + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultDocument.java index 61174a4d..bbe8bb8d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultDocument.java @@ -3,21 +3,42 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to a file. By default, this file will be sent by the user with an * optional caption. Alternatively, you can use input_message_content to send a message with the * specified content instead of the file. - * @note Currently, only .PDF and .ZIP files can be sent using this method. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote Currently, only .PDF and .ZIP files can be sent using this method. + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultDocument implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -33,16 +54,21 @@ public class InlineQueryResultDocument implements InlineQueryResult { private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "document"; ///< Type of the result, must be "document" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) - private String title; ///< Optional. Title for the result + @NonNull + private String title; ///< Title for the result @JsonProperty(DOCUMENTURL_FIELD) + @NonNull private String documentUrl; ///< A valid URL for the file @JsonProperty(MIMETYPE_FIELD) + @NonNull private String mimeType; ///< Mime type of the content of the file, either “application/pdf” or “application/zip” @JsonProperty(DESCRIPTION_FIELD) private String description; ///< Optional. Short description of the result @@ -59,123 +85,10 @@ public class InlineQueryResultDocument implements InlineQueryResult { @JsonProperty(THUMBHEIGHT_FIELD) private Integer thumbHeight; ///< Optional. Thumbnail height @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultDocument() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultDocument setId(String id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultDocument setTitle(String title) { - this.title = title; - return this; - } - - public String getDocumentUrl() { - return documentUrl; - } - - public InlineQueryResultDocument setDocumentUrl(String documentUrl) { - this.documentUrl = documentUrl; - return this; - } - - public String getMimeType() { - return mimeType; - } - - public InlineQueryResultDocument setMimeType(String mimeType) { - this.mimeType = mimeType; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultDocument setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultDocument setCaption(String caption) { - this.caption = caption; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultDocument setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultDocument setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultDocument setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public Integer getThumbWidth() { - return thumbWidth; - } - - public InlineQueryResultDocument setThumbWidth(Integer thumbWidth) { - this.thumbWidth = thumbWidth; - return this; - } - - public Integer getThumbHeight() { - return thumbHeight; - } - - public InlineQueryResultDocument setThumbHeight(Integer thumbHeight) { - this.thumbHeight = thumbHeight; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultDocument setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -191,6 +104,9 @@ public class InlineQueryResultDocument implements InlineQueryResult { if (title == null || title.isEmpty()) { throw new TelegramApiValidationException("Title parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -198,23 +114,4 @@ public class InlineQueryResultDocument implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultDocument{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", title='" + title + '\'' + - ", documentUrl='" + documentUrl + '\'' + - ", mimeType='" + mimeType + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", replyMarkup=" + replyMarkup + - ", inputMessageContent=" + inputMessageContent + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbWidth=" + thumbWidth + - ", thumbHeight=" + thumbHeight + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGame.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGame.java index e2b0cca0..597eed96 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGame.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGame.java @@ -20,6 +20,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -32,6 +41,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * @apiNote This will only work in Telegram versions released after 1 October, 2016. Older clients will ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultGame implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -42,46 +59,14 @@ public class InlineQueryResultGame implements InlineQueryResult { @JsonProperty(TYPE_FIELD) private final String type = "game"; ///< Type of the result, must be "game" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GAMESHORTNAME_FIELD) + @NonNull private String gameShortName; ///< Short name of the game @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message - public InlineQueryResultGame() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultGame setId(String id) { - this.id = id; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultGame setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getGameShortName() { - return gameShortName; - } - - public void setGameShortName(String gameShortName) { - this.gameShortName = gameShortName; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -94,14 +79,4 @@ public class InlineQueryResultGame implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultGame{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", gameShortName='" + gameShortName + '\'' + - ", replyMarkup=" + replyMarkup + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGif.java index 3a037830..21e349a5 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultGif.java @@ -3,6 +3,17 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -19,6 +30,14 @@ import java.util.List; * message with the specified content instead of the animation. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultGif implements InlineQueryResult { private static final List VALIDTHUMBTYPES = Collections.unmodifiableList(Arrays.asList("image/jpeg", "image/gif", "video/mp4")); @@ -35,12 +54,15 @@ public class InlineQueryResultGif implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String GIF_DURATION_FIELD = "gif_duration"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "gif"; ///< Type of the result, must be "gif" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GIFURL_FIELD) + @NonNull private String gifUrl; ///< A valid URL for the GIF file. File size must not exceed 1MB @JsonProperty(GIFWIDTH_FIELD) private Integer gifWidth; ///< Optional. Width of the GIF @@ -61,123 +83,10 @@ public class InlineQueryResultGif implements InlineQueryResult { @JsonProperty(GIF_DURATION_FIELD) private Integer gifDuration; ///< Optional. Duration of the GIF @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultGif() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultGif setId(String id) { - this.id = id; - return this; - } - - public String getGifUrl() { - return gifUrl; - } - - public InlineQueryResultGif setGifUrl(String gifUrl) { - this.gifUrl = gifUrl; - return this; - } - - public Integer getGifWidth() { - return gifWidth; - } - - public InlineQueryResultGif setGifWidth(Integer gifWidth) { - this.gifWidth = gifWidth; - return this; - } - - public Integer getGifHeight() { - return gifHeight; - } - - public InlineQueryResultGif setGifHeight(Integer gifHeight) { - this.gifHeight = gifHeight; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultGif setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public String getThumbUrlType() { - return thumbUrlType; - } - - public InlineQueryResultGif setThumbUrlType(String thumbUrlType) { - this.thumbUrlType = thumbUrlType; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultGif setTitle(String title) { - this.title = title; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultGif setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultGif setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultGif setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Integer getGifDuration() { - return gifDuration; - } - - public InlineQueryResultGif setGifDuration(Integer gifDuration) { - this.gifDuration = gifDuration; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultGif setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -190,6 +99,9 @@ public class InlineQueryResultGif implements InlineQueryResult { if (thumbUrlType != null && !VALIDTHUMBTYPES.contains(thumbUrlType)) { throw new TelegramApiValidationException("ThumbUrlType parameter must be one of “image/jpeg”, “image/gif”, or “video/mp4”", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -197,23 +109,4 @@ public class InlineQueryResultGif implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultGif{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", gifUrl='" + gifUrl + '\'' + - ", gifWidth=" + gifWidth + - ", gifHeight=" + gifHeight + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbUrlType='" + thumbUrlType + '\'' + - ", title='" + title + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", gifDuration=" + gifDuration + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultLocation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultLocation.java index 3018acb5..8f81b90c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultLocation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultLocation.java @@ -3,6 +3,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -13,10 +22,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * Represents a location on a map. By default, the location will be sent by the user. * Alternatively, you can use input_message_content to send a message with the specified content * instead of the location. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultLocation implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -30,16 +47,23 @@ public class InlineQueryResultLocation implements InlineQueryResult { private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; private static final String LIVEPERIOD_FIELD = "live_period"; + private static final String HORIZONTALACCURACY_FIELD = "horizontal_accuracy"; + private static final String HEADING_FIELD = "heading"; + private static final String APPROACHINGNOTIFICATIONDISTANCE_FIELD = "approaching_notification_distance"; @JsonProperty(TYPE_FIELD) private final String type = "location"; ///< Type of the result, must be "location" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) - private String title; ///< Optional. Location title + @NonNull + private String title; ///< Location title @JsonProperty(LATITUDE_FIELD) + @NonNull private Float latitude; ///< Location latitude in degrees @JsonProperty(LONGITUDE_FIELD) + @NonNull private Float longitude; ///< Location longitude in degrees @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @@ -53,104 +77,26 @@ public class InlineQueryResultLocation implements InlineQueryResult { private Integer thumbHeight; ///< Optional. Thumbnail height @JsonProperty(LIVEPERIOD_FIELD) private Integer livePeriod; ///< Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. - - public InlineQueryResultLocation() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultLocation setId(String id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultLocation setTitle(String title) { - this.title = title; - return this; - } - - public Float getLatitude() { - return latitude; - } - - public InlineQueryResultLocation setLatitude(Float latitude) { - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public InlineQueryResultLocation setLongitude(Float longitude) { - this.longitude = longitude; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultLocation setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultLocation setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultLocation setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public Integer getThumbWidth() { - return thumbWidth; - } - - public InlineQueryResultLocation setThumbWidth(Integer thumbWidth) { - this.thumbWidth = thumbWidth; - return this; - } - - public Integer getThumbHeight() { - return thumbHeight; - } - - public InlineQueryResultLocation setThumbHeight(Integer thumbHeight) { - this.thumbHeight = thumbHeight; - return this; - } - - public Integer getLivePeriod() { - return livePeriod; - } - - public InlineQueryResultLocation setLivePeriod(Integer livePeriod) { - this.livePeriod = livePeriod; - return this; - } + /** + * Optional. + * The radius of uncertainty for the location, measured in meters; 0-1500 + */ + @JsonProperty(HORIZONTALACCURACY_FIELD) + private Double horizontalAccuracy; + /** + * Optional. + * For live locations, a direction in which the user is moving, in degrees. + * Must be between 1 and 360 if specified. + */ + @JsonProperty(HEADING_FIELD) + private Integer heading; + /** + * Optional. + * For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. + * Must be between 1 and 100000 if specified. + */ + @JsonProperty(APPROACHINGNOTIFICATIONDISTANCE_FIELD) + private Integer approachingNotificationDistance; @Override public void validate() throws TelegramApiValidationException { @@ -169,6 +115,15 @@ public class InlineQueryResultLocation implements InlineQueryResult { if (livePeriod != null && (livePeriod < 60 || livePeriod > 86400)) { throw new TelegramApiValidationException("Live period parameter must be between 60 and 86400", this); } + if (horizontalAccuracy != null && (horizontalAccuracy < 0 || horizontalAccuracy > 1500)) { + throw new TelegramApiValidationException("Horizontal Accuracy parameter must be between 0 and 1500", this); + } + if (heading != null && (heading < 1 || heading > 360)) { + throw new TelegramApiValidationException("Heading Accuracy parameter must be between 0 and 1500", this); + } + if (approachingNotificationDistance != null && (approachingNotificationDistance < 1 || approachingNotificationDistance > 100000)) { + throw new TelegramApiValidationException("Approaching notification distance parameter must be between 0 and 1500", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -176,21 +131,4 @@ public class InlineQueryResultLocation implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultLocation{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", title='" + title + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", replyMarkup=" + replyMarkup + - ", inputMessageContent=" + inputMessageContent + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbWidth=" + thumbWidth + - ", thumbHeight=" + thumbHeight + - ", livePeriod=" + livePeriod + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java index 4c114778..585be270 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultMpeg4Gif.java @@ -3,10 +3,23 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -15,6 +28,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * use input_message_content to send a message with the specified content instead of the animation. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultMpeg4Gif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -29,12 +50,15 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String MPEG4_DURATION_FIELD = "mpeg4_duration"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(MPEG4URL_FIELD) + @NonNull private String mpeg4Url; ///< A valid URL for the MP4 file. File size must not exceed 1MB @JsonProperty(MPEG4WIDTH_FIELD) private Integer mpeg4Width; ///< Optional. Video width @@ -53,114 +77,10 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { @JsonProperty(MPEG4_DURATION_FIELD) private Integer mpeg4Duration; ///< Optional. Video duration @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultMpeg4Gif() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultMpeg4Gif setId(String id) { - this.id = id; - return this; - } - - public String getMpeg4Url() { - return mpeg4Url; - } - - public InlineQueryResultMpeg4Gif setMpeg4Url(String mpeg4Url) { - this.mpeg4Url = mpeg4Url; - return this; - } - - public Integer getMpeg4Width() { - return mpeg4Width; - } - - public InlineQueryResultMpeg4Gif setMpeg4Width(Integer mpeg4Width) { - this.mpeg4Width = mpeg4Width; - return this; - } - - public Integer getMpeg4Height() { - return mpeg4Height; - } - - public InlineQueryResultMpeg4Gif setMpeg4Height(Integer mpeg4Height) { - this.mpeg4Height = mpeg4Height; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultMpeg4Gif setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultMpeg4Gif setTitle(String title) { - this.title = title; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultMpeg4Gif setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultMpeg4Gif setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultMpeg4Gif setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public Integer getMpeg4Duration() { - return mpeg4Duration; - } - - public InlineQueryResultMpeg4Gif setMpeg4Duration(Integer mpeg4Duration) { - this.mpeg4Duration = mpeg4Duration; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultMpeg4Gif setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -170,6 +90,9 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { if (mpeg4Url == null || mpeg4Url.isEmpty()) { throw new TelegramApiValidationException("Mpeg4Url parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -177,22 +100,4 @@ public class InlineQueryResultMpeg4Gif implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultMpeg4Gif{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", mpeg4Url='" + mpeg4Url + '\'' + - ", mpeg4Width=" + mpeg4Width + - ", mpeg4Height=" + mpeg4Height + - ", thumbUrl='" + thumbUrl + '\'' + - ", title='" + title + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", mpeg4Duration=" + mpeg4Duration + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java index 81827796..6477c768 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultPhoto.java @@ -1,18 +1,24 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -21,7 +27,10 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * specified content instead of the photo. */ @JsonDeserialize -@Data +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString @RequiredArgsConstructor @NoArgsConstructor @AllArgsConstructor @@ -40,6 +49,7 @@ public class InlineQueryResultPhoto implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "photo"; ///< Type of the result, must be “photo” @@ -69,6 +79,9 @@ public class InlineQueryResultPhoto implements InlineQueryResult { private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -78,6 +91,9 @@ public class InlineQueryResultPhoto implements InlineQueryResult { if (photoUrl == null || photoUrl.isEmpty()) { throw new TelegramApiValidationException("PhotoUrl parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVenue.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVenue.java index a28861bc..f9dc8827 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVenue.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVenue.java @@ -3,6 +3,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -12,10 +21,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * @version 1.0 * Represents a venue. By default, the venue will be sent by the user. Alternatively, you can * use input_message_content to send a message with the specified content instead of the venue. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultVenue implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -31,19 +48,25 @@ public class InlineQueryResultVenue implements InlineQueryResult { private static final String THUMBWIDTH_FIELD = "thumb_width"; private static final String THUMBHEIGHT_FIELD = "thumb_height"; private static final String FOURSQUARETYPE_FIELD = "foursquare_type"; - + private static final String GOOGLEPLACEID_FIELD = "google_place_id"; + private static final String GOOGLEPLACETYPE_FIELD = "google_place_type"; @JsonProperty(TYPE_FIELD) private final String type = "venue"; ///< Type of the result, must be "venue" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) - private String title; ///< Optional. Location title + @NonNull + private String title; ///< Location title @JsonProperty(LATITUDE_FIELD) + @NonNull private Float latitude; ///< Venue latitude in degrees @JsonProperty(LONGITUDE_FIELD) + @NonNull private Float longitude; ///< Venue longitude in degrees @JsonProperty(ADDRESS_FIELD) + @NonNull private String address; ///< Address of the venue @JsonProperty(FOURSQUAREID_FIELD) private String foursquareId; ///< Optional. Foursquare identifier of the venue if known @@ -59,122 +82,10 @@ public class InlineQueryResultVenue implements InlineQueryResult { private Integer thumbHeight; ///< Optional. Thumbnail height @JsonProperty(FOURSQUARETYPE_FIELD) private String foursquareType; ///< Optional. Foursquare type of the venue, if known. - - public InlineQueryResultVenue() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultVenue setId(String id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultVenue setTitle(String title) { - this.title = title; - return this; - } - - public Float getLatitude() { - return latitude; - } - - public InlineQueryResultVenue setLatitude(Float latitude) { - this.latitude = latitude; - return this; - } - - public Float getLongitude() { - return longitude; - } - - public InlineQueryResultVenue setLongitude(Float longitude) { - this.longitude = longitude; - return this; - } - - public String getAddress() { - return address; - } - - public InlineQueryResultVenue setAddress(String address) { - this.address = address; - return this; - } - - public String getFoursquareId() { - return foursquareId; - } - - public InlineQueryResultVenue setFoursquareId(String foursquareId) { - this.foursquareId = foursquareId; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultVenue setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultVenue setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultVenue setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public Integer getThumbWidth() { - return thumbWidth; - } - - public InlineQueryResultVenue setThumbWidth(Integer thumbWidth) { - this.thumbWidth = thumbWidth; - return this; - } - - public Integer getThumbHeight() { - return thumbHeight; - } - - public InlineQueryResultVenue setThumbHeight(Integer thumbHeight) { - this.thumbHeight = thumbHeight; - return this; - } - - public String getFoursquareType() { - return foursquareType; - } - - public InlineQueryResultVenue setFoursquareType(String foursquareType) { - this.foursquareType = foursquareType; - return this; - } + @JsonProperty(GOOGLEPLACEID_FIELD) + private String googlePlaceId; ///< Optional. Google Places identifier of the venue + @JsonProperty(GOOGLEPLACETYPE_FIELD) + private String googlePlaceType; ///< Optional. Google Places type of the venue. (See supported types.) @Override public void validate() throws TelegramApiValidationException { @@ -201,23 +112,4 @@ public class InlineQueryResultVenue implements InlineQueryResult { } } - - @Override - public String toString() { - return "InlineQueryResultVenue{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", title='" + title + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", address='" + address + '\'' + - ", foursquareId='" + foursquareId + '\'' + - ", replyMarkup=" + replyMarkup + - ", inputMessageContent=" + inputMessageContent + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbWidth=" + thumbWidth + - ", thumbHeight=" + thumbHeight + - ", foursquareType='" + foursquareType + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVideo.java index 7c96863e..c39086c1 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVideo.java @@ -3,10 +3,23 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -15,6 +28,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * instead of the video. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultVideo implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -30,14 +51,18 @@ public class InlineQueryResultVideo implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "video"; ///< Type of the result, must be "video" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result @JsonProperty(MIMETYPE_FIELD) + @NonNull private String mimeType; ///< Mime type of the content of video url, i.e. “text/html” or “video/mp4” @JsonProperty(VIDEOURL_FIELD) + @NonNull private String videoUrl; ///< A valid URL for the embedded video player or video file @JsonProperty(VIDEOWIDTH_FIELD) private Integer videoWidth; ///< Optional. Video width @@ -58,132 +83,10 @@ public class InlineQueryResultVideo implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultVideo() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultVideo setId(String id) { - this.id = id; - return this; - } - - public String getMimeType() { - return mimeType; - } - - public InlineQueryResultVideo setMimeType(String mimeType) { - this.mimeType = mimeType; - return this; - } - - public String getVideoUrl() { - return videoUrl; - } - - public InlineQueryResultVideo setVideoUrl(String videoUrl) { - this.videoUrl = videoUrl; - return this; - } - - public Integer getVideoWidth() { - return videoWidth; - } - - public InlineQueryResultVideo setVideoWidth(Integer videoWidth) { - this.videoWidth = videoWidth; - return this; - } - - public Integer getVideoHeight() { - return videoHeight; - } - - public InlineQueryResultVideo setVideoHeight(Integer videoHeight) { - this.videoHeight = videoHeight; - return this; - } - - public Integer getVideoDuration() { - return videoDuration; - } - - public InlineQueryResultVideo setVideoDuration(Integer videoDuration) { - this.videoDuration = videoDuration; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultVideo setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultVideo setTitle(String title) { - this.title = title; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultVideo setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultVideo setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultVideo setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultVideo setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultVideo setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -193,6 +96,9 @@ public class InlineQueryResultVideo implements InlineQueryResult { if (videoUrl == null || videoUrl.isEmpty()) { throw new TelegramApiValidationException("VideoUrl parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -200,24 +106,4 @@ public class InlineQueryResultVideo implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultVideo{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", mimeType='" + mimeType + '\'' + - ", videoUrl='" + videoUrl + '\'' + - ", videoWidth=" + videoWidth + - ", videoHeight=" + videoHeight + - ", videoDuration=" + videoDuration + - ", thumbUrl='" + thumbUrl + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVoice.java index e0a98f04..c080e696 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/InlineQueryResultVoice.java @@ -3,20 +3,41 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to a voice recording in an .ogg container encoded with OPUS. By default, * this voice recording will be sent by the user. Alternatively, you can use input_message_content * to send a message with the specified content instead of the the voice message. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultVoice implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -27,14 +48,18 @@ public class InlineQueryResultVoice implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "voice"; ///< Type of the result, must be "voice" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(VOICEURL_FIELD) + @NonNull private String voiceUrl; ///< A valid URL for the voice recording @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Recording title @JsonProperty(VOICE_DURATION_FIELD) private Integer voiceDuration; ///< Optional. Recording duration in seconds @@ -45,78 +70,10 @@ public class InlineQueryResultVoice implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Voice caption (may also be used when resending documents by file_id), 0-200 characters @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultVoice() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultVoice setId(String id) { - this.id = id; - return this; - } - - public String getVoiceUrl() { - return voiceUrl; - } - - public InlineQueryResultVoice setVoiceUrl(String voiceUrl) { - this.voiceUrl = voiceUrl; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultVoice setTitle(String title) { - this.title = title; - return this; - } - - public Integer getVoiceDuration() { - return voiceDuration; - } - - public InlineQueryResultVoice setVoiceDuration(Integer voiceDuration) { - this.voiceDuration = voiceDuration; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultVoice setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultVoice setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultVoice setCaption(String caption) { - this.caption = caption; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -126,6 +83,9 @@ public class InlineQueryResultVoice implements InlineQueryResult { if (voiceUrl == null || voiceUrl.isEmpty()) { throw new TelegramApiValidationException("VoiceUrl parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -133,19 +93,4 @@ public class InlineQueryResultVoice implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultVoice{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", voiceUrl='" + voiceUrl + '\'' + - ", title='" + title + '\'' + - ", voiceDuration=" + voiceDuration + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedAudio.java index c46d3801..85bc8cfb 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedAudio.java @@ -2,21 +2,42 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to an mp3 audio file stored on the Telegram servers. By default, this * audio file will be sent by the user. Alternatively, you can use input_message_content to send a * message with the specified content instead of the audio. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedAudio implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -26,12 +47,15 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "audio"; ///< Type of the result, must be "audio" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result @JsonProperty(AUDIO_FILE_ID_FIELD) + @NonNull private String audioFileId; ///< A valid file identifier for the audio file @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the audio @@ -40,69 +64,10 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Audio caption (may also be used when resending documents by file_id), 0-200 characters @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedAudio() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedAudio setId(String id) { - this.id = id; - return this; - } - - public String getAudioFileId() { - return audioFileId; - } - - public InlineQueryResultCachedAudio setAudioFileId(String audioFileId) { - this.audioFileId = audioFileId; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedAudio setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedAudio setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedAudio setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedAudio setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -112,6 +77,9 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { if (audioFileId == null || audioFileId.isEmpty()) { throw new TelegramApiValidationException("AudioFileId parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -119,17 +87,4 @@ public class InlineQueryResultCachedAudio implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedAudio{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", audioFileId='" + audioFileId + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedDocument.java index b0bdb46a..a461c13d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedDocument.java @@ -3,22 +3,43 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to a file stored on the Telegram servers. By default, this file will be * sent by the user with an optional caption. Alternatively, you can use input_message_content to * send a message with the specified content instead of the file. - * @note Currently, only pdf-files and zip archives can be sent using this method. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote Currently, only pdf-files and zip archives can be sent using this method. + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedDocument implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -30,14 +51,17 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "document"; ///< Type of the result, must be "document" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @JsonProperty(DOCUMENT_FILE_ID_FIELD) + @NonNull private String documentFileId; ///< A valid file identifier for the file @JsonProperty(DESCRIPTION_FIELD) private String description; ///< Optional. Short description of the result @@ -48,87 +72,10 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the file @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedDocument() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedDocument setId(String id) { - this.id = id; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedDocument setTitle(String title) { - this.title = title; - return this; - } - - public String getDocumentFileId() { - return documentFileId; - } - - public InlineQueryResultCachedDocument setDocumentFileId(String documentFileId) { - this.documentFileId = documentFileId; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultCachedDocument setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedDocument setCaption(String caption) { - this.caption = caption; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedDocument setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedDocument setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedDocument setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -141,6 +88,9 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { if (title == null || title.isEmpty()) { throw new TelegramApiValidationException("Title parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -148,19 +98,4 @@ public class InlineQueryResultCachedDocument implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedDocument{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", title='" + title + '\'' + - ", documentFileId='" + documentFileId + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", replyMarkup=" + replyMarkup + - ", inputMessageContent=" + inputMessageContent + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedGif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedGif.java index bee3d835..508ba30e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedGif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedGif.java @@ -3,6 +3,17 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; @@ -20,6 +31,14 @@ import java.util.List; * input_message_content to send a message with specified content instead of the animation. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedGif implements InlineQueryResult { private static final List VALIDTHUMBTYPES = Collections.unmodifiableList(Arrays.asList("image/jpeg", "image/gif", "video/mp4")); @@ -33,12 +52,15 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "gif"; ///< Type of the result, must be "gif" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(GIF_FILE_ID_FIELD) + @NonNull private String gifFileId; ///< A valid file identifier for the GIF file @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @@ -49,100 +71,14 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + 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. @JsonProperty(THUMBURL_FIELD) private String thumbUrl; ///< Optional. URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result @JsonProperty(THUMBMIMETYPE_FIELD) private String thumbUrlType; - - public InlineQueryResultCachedGif() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedGif setId(String id) { - this.id = id; - return this; - } - - public String getGifFileId() { - return gifFileId; - } - - public InlineQueryResultCachedGif setGifFileId(String gifFileId) { - this.gifFileId = gifFileId; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedGif setTitle(String title) { - this.title = title; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedGif setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedGif setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedGif setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedGif setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } - - public String getThumbUrl() { - return thumbUrl; - } - - public InlineQueryResultCachedGif setThumbUrl(String thumbUrl) { - this.thumbUrl = thumbUrl; - return this; - } - - public String getThumbUrlType() { - return thumbUrlType; - } - - public InlineQueryResultCachedGif setThumbUrlType(String thumbUrlType) { - this.thumbUrlType = thumbUrlType; - return this; - } + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -155,6 +91,9 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { if (thumbUrlType != null && !VALIDTHUMBTYPES.contains(thumbUrlType)) { throw new TelegramApiValidationException("ThumbUrlType parameter must be one of “image/jpeg”, “image/gif”, or “video/mp4”", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -162,20 +101,4 @@ public class InlineQueryResultCachedGif implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedGif{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", gifFileId='" + gifFileId + '\'' + - ", title='" + title + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - ", thumbUrl='" + thumbUrl + '\'' + - ", thumbUrlType='" + thumbUrlType + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedMpeg4Gif.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedMpeg4Gif.java index 7022ad42..1d00f30b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedMpeg4Gif.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedMpeg4Gif.java @@ -3,11 +3,24 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -16,6 +29,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * use input_message_content to send a message with the specified content instead of the animation. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -26,12 +47,15 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "mpeg4_gif"; ///< Type of the result, must be "mpeg4_gif" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(MPEG4_FILE_ID_FIELD) + @NonNull private String mpeg4FileId; ///< A valid file identifier for the MP4 file @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @@ -42,78 +66,10 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedMpeg4Gif() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedMpeg4Gif setId(String id) { - this.id = id; - return this; - } - - public String getMpeg4FileId() { - return mpeg4FileId; - } - - public InlineQueryResultCachedMpeg4Gif setMpeg4FileId(String mpeg4FileId) { - this.mpeg4FileId = mpeg4FileId; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedMpeg4Gif setTitle(String title) { - this.title = title; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedMpeg4Gif setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedMpeg4Gif setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedMpeg4Gif setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedMpeg4Gif setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -126,22 +82,11 @@ public class InlineQueryResultCachedMpeg4Gif implements InlineQueryResult { if (inputMessageContent != null) { inputMessageContent.validate(); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (replyMarkup != null) { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedMpeg4Gif{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", mpeg4FileId='" + mpeg4FileId + '\'' + - ", title='" + title + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedPhoto.java index 77b26d41..452f29c3 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedPhoto.java @@ -3,11 +3,24 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -16,6 +29,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * send a message with the specified content instead of the photo. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedPhoto implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -26,12 +47,15 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "photo"; ///< Type of the result, must be “photo” @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(PHOTOFILEID_FIELD) + @NonNull private String photoFileId; ///< A valid file identifier of the photo @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @@ -44,87 +68,10 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedPhoto() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedPhoto setId(String id) { - this.id = id; - return this; - } - - public String getPhotoFileId() { - return photoFileId; - } - - public InlineQueryResultCachedPhoto setPhotoFileId(String photoFileId) { - this.photoFileId = photoFileId; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedPhoto setTitle(String title) { - this.title = title; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultCachedPhoto setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedPhoto setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedPhoto setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedPhoto setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedPhoto setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -134,6 +81,9 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { if (photoFileId == null || photoFileId.isEmpty()) { throw new TelegramApiValidationException("PhotoFileId parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -141,19 +91,4 @@ public class InlineQueryResultCachedPhoto implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedPhoto{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", photoFileId='" + photoFileId + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedSticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedSticker.java index 840815fc..50949114 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedSticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedSticker.java @@ -3,6 +3,15 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; @@ -14,10 +23,18 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * Represents a link to a sticker stored on the Telegram servers. By default, this sticker * will be sent by the user. Alternatively, you can use input_message_content to send a message with * the specified content instead of the sticker. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedSticker implements InlineQueryResult { private static final String TYPE_FIELD = "type"; @@ -29,58 +46,16 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { @JsonProperty(TYPE_FIELD) private final String type = "sticker"; ///< Type of the result, must be "sticker" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(STICKER_FILE_ID_FIELD) + @NonNull private String stickerFileId; ///< A valid file identifier of the sticker @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the sticker @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message - public InlineQueryResultCachedSticker() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedSticker setId(String id) { - this.id = id; - return this; - } - - public String getStickerFileId() { - return stickerFileId; - } - - public InlineQueryResultCachedSticker setStickerFileId(String stickerFileId) { - this.stickerFileId = stickerFileId; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedSticker setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedSticker setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -96,15 +71,4 @@ public class InlineQueryResultCachedSticker implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedSticker{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", sticker_file_id='" + stickerFileId + '\'' + - ", inputMessageContent='" + inputMessageContent + '\'' + - ", replyMarkup='" + replyMarkup + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVideo.java index eb611533..9ff70b89 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVideo.java @@ -3,11 +3,24 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 @@ -16,6 +29,14 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * input_message_content to send a message with the specified content instead of the video. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedVideo implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -26,12 +47,15 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { private static final String INPUTMESSAGECONTENT_FIELD = "input_message_content"; private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "video"; ///< Type of the result, must be "video" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result @JsonProperty(VIDEO_FILE_ID_FIELD) + @NonNull private String videoFileId; ///< A valid file identifier for the video file @JsonProperty(TITLE_FIELD) private String title; ///< Optional. Title for the result @@ -44,87 +68,10 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { @JsonProperty(REPLY_MARKUP_FIELD) private InlineKeyboardMarkup replyMarkup; ///< Optional. Inline keyboard attached to the message @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedVideo() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedVideo setId(String id) { - this.id = id; - return this; - } - - public String getVideoFileId() { - return videoFileId; - } - - public InlineQueryResultCachedVideo setVideoFileId(String videoFileId) { - this.videoFileId = videoFileId; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedVideo setTitle(String title) { - this.title = title; - return this; - } - - public String getDescription() { - return description; - } - - public InlineQueryResultCachedVideo setDescription(String description) { - this.description = description; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedVideo setCaption(String caption) { - this.caption = caption; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedVideo setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedVideo setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedVideo setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + 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. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -134,6 +81,9 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { if (videoFileId == null || videoFileId.isEmpty()) { throw new TelegramApiValidationException("VideoFileId parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -141,19 +91,4 @@ public class InlineQueryResultCachedVideo implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedVideo{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", videoFileId='" + videoFileId + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", caption='" + caption + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVoice.java index 6a54c8ff..e59cdd5d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/inlinequery/result/cached/InlineQueryResultCachedVoice.java @@ -3,21 +3,42 @@ package org.telegram.telegrambots.meta.api.objects.inlinequery.result.cached; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.util.List; + /** * @author Ruben Bermudez * @version 1.0 * Represents a link to a voice message stored on the Telegram servers. By default, this * voice message will be sent by the user. Alternatively, you can use input_message_content to send * a message with the specified content instead of the voice message. - * @note This will only work in Telegram versions released after 9 April, 2016. Older clients will + * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * ignore them. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineQueryResultCachedVoice implements InlineQueryResult { private static final String TYPE_FIELD = "type"; private static final String ID_FIELD = "id"; @@ -27,14 +48,18 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { private static final String REPLY_MARKUP_FIELD = "reply_markup"; private static final String CAPTION_FIELD = "caption"; private static final String PARSEMODE_FIELD = "parse_mode"; + private static final String CAPTION_ENTITIES_FIELD = "caption_entities"; @JsonProperty(TYPE_FIELD) private final String type = "voice"; ///< Type of the result, must be "voice" @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Unique identifier of this result, 1-64 bytes @JsonProperty(VOICE_FILE_ID_FIELD) + @NonNull private String voiceFileId; ///< A valid file identifier for the voice message @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Recording title @JsonProperty(INPUTMESSAGECONTENT_FIELD) private InputMessageContent inputMessageContent; ///< Optional. Content of the message to be sent instead of the voice recording @@ -43,78 +68,10 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Voice caption (may also be used when resending documents by file_id), 0-200 characters @JsonProperty(PARSEMODE_FIELD) - private String parseMode; ///< Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - - public InlineQueryResultCachedVoice() { - super(); - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } - - public InlineQueryResultCachedVoice setId(String id) { - this.id = id; - return this; - } - - public String getVoiceFileId() { - return voiceFileId; - } - - public InlineQueryResultCachedVoice setVoiceFileId(String voiceFileId) { - this.voiceFileId = voiceFileId; - return this; - } - - public String getTitle() { - return title; - } - - public InlineQueryResultCachedVoice setTitle(String title) { - this.title = title; - return this; - } - - public InputMessageContent getInputMessageContent() { - return inputMessageContent; - } - - public InlineQueryResultCachedVoice setInputMessageContent(InputMessageContent inputMessageContent) { - this.inputMessageContent = inputMessageContent; - return this; - } - - public InlineKeyboardMarkup getReplyMarkup() { - return replyMarkup; - } - - public InlineQueryResultCachedVoice setReplyMarkup(InlineKeyboardMarkup replyMarkup) { - this.replyMarkup = replyMarkup; - return this; - } - - public String getCaption() { - return caption; - } - - public InlineQueryResultCachedVoice setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InlineQueryResultCachedVoice setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; - } + private String parseMode; ///< Optinal. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + @JsonProperty(CAPTION_ENTITIES_FIELD) + @Singular + private List captionEntities; ///< Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode @Override public void validate() throws TelegramApiValidationException { @@ -124,6 +81,9 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { if (voiceFileId == null || voiceFileId.isEmpty()) { throw new TelegramApiValidationException("VoiceFileId parameter can't be empty", this); } + if (parseMode != null && (captionEntities != null && !captionEntities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } if (inputMessageContent != null) { inputMessageContent.validate(); } @@ -131,18 +91,4 @@ public class InlineQueryResultCachedVoice implements InlineQueryResult { replyMarkup.validate(); } } - - @Override - public String toString() { - return "InlineQueryResultCachedVoice{" + - "type='" + type + '\'' + - ", id='" + id + '\'' + - ", voiceFileId='" + voiceFileId + '\'' + - ", title='" + title + '\'' + - ", inputMessageContent=" + inputMessageContent + - ", replyMarkup=" + replyMarkup + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java index 45855293..078cb7ac 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMedia.java @@ -4,27 +4,46 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.media.serialization.InputMediaDeserializer; import org.telegram.telegrambots.meta.api.objects.media.serialization.InputMediaSerializer; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.File; import java.io.InputStream; +import java.util.List; /** * @author Ruben Bermudez * @version 3.5 */ -@SuppressWarnings({"unchecked"}) +@SuppressWarnings({"unused"}) @JsonSerialize(using = InputMediaSerializer.class) @JsonDeserialize(using = InputMediaDeserializer.class) -public abstract class InputMedia implements Validable, BotApiObject { +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@RequiredArgsConstructor +@NoArgsConstructor +@AllArgsConstructor +public abstract class InputMedia implements Validable, BotApiObject { public static final String TYPE_FIELD = "type"; public static final String MEDIA_FIELD = "media"; public static final String CAPTION_FIELD = "caption"; public static final String PARSEMODE_FIELD = "parse_mode"; + public static final String ENTITIES_FIELD = "entities"; /** * File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), @@ -32,11 +51,15 @@ public abstract class InputMedia implements Validable, BotApiObject { * to upload a new one using multipart/form-data under name. */ @JsonProperty(MEDIA_FIELD) + @NonNull private String media; @JsonProperty(CAPTION_FIELD) private String caption; ///< Optional. Caption of the media to be sent, 0-200 characters @JsonProperty(PARSEMODE_FIELD) 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. + @JsonProperty(ENTITIES_FIELD) + @Singular + private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode @JsonIgnore private boolean isNewMedia; ///< True to upload a new media, false to use a fileId or URL @JsonIgnore @@ -46,31 +69,6 @@ public abstract class InputMedia implements Validable, BotApiObject { @JsonIgnore private InputStream newMediaStream; ///< New media stream - public InputMedia() { - super(); - } - - public InputMedia(String media, String caption) { - this.media = media; - this.caption = caption; - } - - public String getMedia() { - return media; - } - - public File getMediaFile() { - return newMediaFile; - } - - public InputStream getNewMediaStream() { - return newMediaStream; - } - - public String getMediaName() { - return mediaName; - } - @JsonIgnore public boolean isNewMedia() { return isNewMedia; @@ -79,56 +77,32 @@ public abstract class InputMedia implements Validable, BotApiObject { /** * Use this setter to send an existing file (using file_id) or an url. * @param media File_id or URL of the file to send - * @return This object */ - public T setMedia(String media) { + public void setMedia(String media) { this.media = media; this.isNewMedia = false; - return (T) this; } /** * Use this setter to send new file. * @param mediaFile File to send - * @return This object */ - public T setMedia(File mediaFile, String fileName) { + public void setMedia(File mediaFile, String fileName) { this.newMediaFile = mediaFile; this.isNewMedia = true; this.mediaName = fileName; this.media = "attach://" + fileName; - return (T) this; } /** * Use this setter to send new file as stream. * @param mediaStream File to send - * @return This object */ - public T setMedia(InputStream mediaStream, String fileName) { + public void setMedia(InputStream mediaStream, String fileName) { this.newMediaStream = mediaStream; this.isNewMedia = true; this.mediaName = fileName; this.media = "attach://" + fileName; - return (T) this; - } - - public String getCaption() { - return caption; - } - - public InputMedia setCaption(String caption) { - this.caption = caption; - return this; - } - - public String getParseMode() { - return parseMode; - } - - public InputMedia setParseMode(String parseMode) { - this.parseMode = parseMode; - return this; } @Override @@ -143,21 +117,11 @@ public abstract class InputMedia implements Validable, BotApiObject { } else if (media == null || media.isEmpty()) { throw new TelegramApiValidationException("Media can't be empty", this); } + if (parseMode != null && (entities != null && !entities.isEmpty()) ) { + throw new TelegramApiValidationException("Parse mode can't be enabled if Entities are provided", this); + } } @JsonProperty(TYPE_FIELD) public abstract String getType(); - - @Override - public String toString() { - return "InputMedia{" + - "media='" + media + '\'' + - ", caption='" + caption + '\'' + - ", parseMode='" + parseMode + '\'' + - ", isNewMedia=" + isNewMedia + - ", mediaName='" + mediaName + '\'' + - ", newMediaFile=" + newMediaFile + - ", newMediaStream=" + newMediaStream + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAnimation.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAnimation.java index e059a516..0e1e0fef 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAnimation.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAnimation.java @@ -2,9 +2,20 @@ package org.telegram.telegrambots.meta.api.objects.media; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.InputFile; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.io.File; +import java.io.InputStream; +import java.util.List; + /** * @author Ruben Bermudez * @version 4.0.0 @@ -13,7 +24,11 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @SuppressWarnings("unused") @JsonDeserialize -public class InputMediaAnimation extends InputMedia { +@EqualsAndHashCode(callSuper = true) +@Getter +@Setter +@ToString +public class InputMediaAnimation extends InputMedia { private static final String TYPE = "animation"; public static final String WIDTH_FIELD = "width"; @@ -40,44 +55,17 @@ public class InputMediaAnimation extends InputMedia { super(); } - public InputMediaAnimation(String media, String caption) { - super(media, caption); + public InputMediaAnimation(@NonNull String media) { + super(media); } - public Integer getWidth() { - return width; - } - - public InputMediaAnimation setWidth(Integer width) { + @Builder + public InputMediaAnimation(@NonNull String media, String caption, String parseMode, List entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream, Integer width, Integer height, Integer duration, InputFile thumb) { + super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); this.width = width; - return this; - } - - public Integer getHeight() { - return height; - } - - public InputMediaAnimation setHeight(Integer height) { this.height = height; - return this; - } - - public Integer getDuration() { - return duration; - } - - public InputMediaAnimation setDuration(Integer duration) { this.duration = duration; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public InputMediaAnimation setThumb(InputFile thumb) { this.thumb = thumb; - return this; } @Override @@ -89,14 +77,4 @@ public class InputMediaAnimation extends InputMedia { public void validate() throws TelegramApiValidationException { super.validate(); } - - @Override - public String toString() { - return "InputMediaAnimation{" + - "width=" + width + - ", height=" + height + - ", duration=" + duration + - ", thumb=" + thumb + - "} " + super.toString(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAudio.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAudio.java index a338d77c..813bd247 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAudio.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaAudio.java @@ -2,9 +2,20 @@ package org.telegram.telegrambots.meta.api.objects.media; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.InputFile; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.io.File; +import java.io.InputStream; +import java.util.List; + /** * @author Ruben Bermudez * @version 4.0.0 @@ -13,7 +24,11 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @SuppressWarnings({"unused"}) @JsonDeserialize -public class InputMediaAudio extends InputMedia { +@EqualsAndHashCode(callSuper = true) +@Getter +@Setter +@ToString +public class InputMediaAudio extends InputMedia { private static final String TYPE = "audio"; public static final String DURATION_FIELD = "duration"; @@ -36,49 +51,21 @@ public class InputMediaAudio extends InputMedia { */ private InputFile thumb; - public InputMediaAudio() { super(); } - public InputMediaAudio(String media, String caption) { - super(media, caption); + public InputMediaAudio(@NonNull String media) { + super(media); } - public Integer getDuration() { - return duration; - } - - public InputMediaAudio setDuration(Integer duration) { + @Builder + public InputMediaAudio(@NonNull String media, String caption, String parseMode, List entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream, Integer duration, String performer, String title, InputFile thumb) { + super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); this.duration = duration; - return this; - } - - public String getPerformer() { - return performer; - } - - public InputMediaAudio setPerformer(String performer) { this.performer = performer; - return this; - } - - public String getTitle() { - return title; - } - - public InputMediaAudio setTitle(String title) { this.title = title; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public InputMediaAudio setThumb(InputFile thumb) { this.thumb = thumb; - return this; } @Override @@ -90,14 +77,4 @@ public class InputMediaAudio extends InputMedia { public void validate() throws TelegramApiValidationException { super.validate(); } - - @Override - public String toString() { - return "InputMediaAudio{" + - "duration=" + duration + - ", performer=" + performer + - ", title=" + title + - ", thumb=" + thumb + - "} " + super.toString(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaDocument.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaDocument.java index edc33165..de4f4240 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaDocument.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaDocument.java @@ -1,9 +1,21 @@ package org.telegram.telegrambots.meta.api.objects.media; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.InputFile; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.io.File; +import java.io.InputStream; +import java.util.List; + /** * @author Ruben Bermudez * @version 4.0.0 @@ -12,9 +24,15 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @SuppressWarnings("unused") @JsonDeserialize -public class InputMediaDocument extends InputMedia { +@EqualsAndHashCode(callSuper = true) +@Getter +@Setter +@ToString +public class InputMediaDocument extends InputMedia { private static final String TYPE = "document"; + public static final String THUMB_FIELD = "thumb"; + public static final String DISABLECONTENTTYPEDETECTION_FIELD = "disable_content_type_detection"; /** * Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. @@ -24,22 +42,27 @@ public class InputMediaDocument extends InputMedia { * if the thumbnail was uploaded using multipart/form-data under . */ private InputFile thumb; + /** + * Optional. + * Disables automatic server-side content type detection for files uploaded using multipart/form-data. + * Always true, if the document is sent as part of an album. + */ + @JsonProperty(DISABLECONTENTTYPEDETECTION_FIELD) + private Boolean disableContentTypeDetection; public InputMediaDocument() { super(); } - public InputMediaDocument(String media, String caption) { - super(media, caption); + public InputMediaDocument(@NonNull String media) { + super(media); } - public InputFile getThumb() { - return thumb; - } - - public InputMediaDocument setThumb(InputFile thumb) { + @Builder + public InputMediaDocument(@NonNull String media, String caption, String parseMode, List entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream, InputFile thumb, Boolean disableContentTypeDetection) { + super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); this.thumb = thumb; - return this; + this.disableContentTypeDetection = disableContentTypeDetection; } @Override @@ -51,11 +74,4 @@ public class InputMediaDocument extends InputMedia { public void validate() throws TelegramApiValidationException { super.validate(); } - - @Override - public String toString() { - return "InputMediaDocument{" + - "thumb=" + thumb + - "} " + super.toString(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaPhoto.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaPhoto.java index d0b47cbe..b94bce1d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaPhoto.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaPhoto.java @@ -1,8 +1,19 @@ package org.telegram.telegrambots.meta.api.objects.media; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.io.File; +import java.io.InputStream; +import java.util.List; + /** * @author Ruben Bermudez * @version 3.5 @@ -11,15 +22,24 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @SuppressWarnings("unused") @JsonDeserialize -public class InputMediaPhoto extends InputMedia { +@EqualsAndHashCode(callSuper = true) +@Getter +@Setter +@ToString +public class InputMediaPhoto extends InputMedia { private static final String TYPE = "photo"; public InputMediaPhoto() { super(); } - public InputMediaPhoto(String media, String caption) { - super(media, caption); + public InputMediaPhoto(@NonNull String media) { + super(media); + } + + @Builder + public InputMediaPhoto(@NonNull String media, String caption, String parseMode, List entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream) { + super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); } @Override @@ -31,9 +51,4 @@ public class InputMediaPhoto extends InputMedia { public void validate() throws TelegramApiValidationException { super.validate(); } - - @Override - public String toString() { - return "InputMediaPhoto{} " + super.toString(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaVideo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaVideo.java index 932ec6a8..4b35730d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaVideo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/InputMediaVideo.java @@ -2,9 +2,20 @@ package org.telegram.telegrambots.meta.api.objects.media; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.InputFile; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; +import java.io.File; +import java.io.InputStream; +import java.util.List; + /** * @author Ruben Bermudez * @version 3.5 @@ -13,7 +24,11 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; */ @SuppressWarnings({"unused"}) @JsonDeserialize -public class InputMediaVideo extends InputMedia { +@EqualsAndHashCode(callSuper = true) +@Getter +@Setter +@ToString +public class InputMediaVideo extends InputMedia { private static final String TYPE = "video"; public static final String WIDTH_FIELD = "width"; @@ -41,56 +56,20 @@ public class InputMediaVideo extends InputMedia { private InputFile thumb; public InputMediaVideo() { - super(); } - public InputMediaVideo(String media, String caption) { - super(media, caption); + public InputMediaVideo(@NonNull String media) { + super(media); } - public Integer getWidth() { - return width; - } - - public InputMediaVideo setWidth(Integer width) { + @Builder + public InputMediaVideo(@NonNull String media, String caption, String parseMode, List entities, boolean isNewMedia, String mediaName, File newMediaFile, InputStream newMediaStream, Integer width, Integer height, Integer duration, Boolean supportsStreaming, InputFile thumb) { + super(media, caption, parseMode, entities, isNewMedia, mediaName, newMediaFile, newMediaStream); this.width = width; - return this; - } - - public Integer getHeight() { - return height; - } - - public InputMediaVideo setHeight(Integer height) { this.height = height; - return this; - } - - public Integer getDuration() { - return duration; - } - - public InputMediaVideo setDuration(Integer duration) { this.duration = duration; - return this; - } - - public Boolean getSupportsStreaming() { - return supportsStreaming; - } - - public InputMediaVideo setSupportsStreaming(Boolean supportsStreaming) { this.supportsStreaming = supportsStreaming; - return this; - } - - public InputFile getThumb() { - return thumb; - } - - public InputMediaVideo setThumb(InputFile thumb) { this.thumb = thumb; - return this; } @Override @@ -102,14 +81,4 @@ public class InputMediaVideo extends InputMedia { public void validate() throws TelegramApiValidationException { super.validate(); } - - @Override - public String toString() { - return "InputMediaVideo{" + - "width=" + width + - ", height=" + height + - ", duration=" + duration + - ", supportsStreaming=" + supportsStreaming + - "} " + super.toString(); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/serialization/InputMediaSerializer.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/serialization/InputMediaSerializer.java index 6830b521..565cbd5b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/serialization/InputMediaSerializer.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/media/serialization/InputMediaSerializer.java @@ -4,7 +4,12 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; -import org.telegram.telegrambots.meta.api.objects.media.*; +import org.telegram.telegrambots.meta.api.objects.MessageEntity; +import org.telegram.telegrambots.meta.api.objects.media.InputMedia; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaAnimation; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaAudio; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaDocument; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaVideo; import java.io.IOException; @@ -26,6 +31,13 @@ public class InputMediaSerializer extends JsonSerializer { if (value.getParseMode() != null) { gen.writeStringField(InputMedia.PARSEMODE_FIELD, value.getParseMode()); } + if (value.getEntities() != null) { + gen.writeArrayFieldStart(InputMedia.ENTITIES_FIELD); + for (MessageEntity entity : value.getEntities()) { + gen.writeObject(entity); + } + gen.writeEndArray(); + } if (value instanceof InputMediaAudio) { InputMediaAudio audio = (InputMediaAudio) value; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedCredentials.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedCredentials.java index e82a388f..e78c04f8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedCredentials.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedCredentials.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.passport; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * Contains data required for decrypting and authenticating EncryptedPassportElement. * See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class EncryptedCredentials implements BotApiObject { private static final String DATA_FIELD = "data"; private static final String HASH_FIELD = "hash"; @@ -24,34 +36,4 @@ public class EncryptedCredentials implements BotApiObject { private String hash; ///< Base64-encoded data hash for data authentication @JsonProperty(SECRET_FIELD) private String secret; ///< Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption - - public EncryptedCredentials() { - } - - public EncryptedCredentials(String data, String hash, String secret) { - this.data = data; - this.hash = hash; - this.secret = secret; - } - - public String getData() { - return data; - } - - public String getHash() { - return hash; - } - - public String getSecret() { - return secret; - } - - @Override - public String toString() { - return "EncryptedCredentials{" + - "data='" + data + '\'' + - ", hash='" + hash + '\'' + - ", secret='" + secret + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedPassportElement.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedPassportElement.java index 25bcab65..52a4231a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedPassportElement.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/EncryptedPassportElement.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.passport; 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 java.util.ArrayList; @@ -12,6 +18,12 @@ import java.util.List; * Contains information about documents or other Telegram Passport data shared with the bot by the user. */ @SuppressWarnings("unused") +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class EncryptedPassportElement implements BotApiObject { private static final String TYPE_FIELD = "type"; private static final String DATA_FIELD = "data"; @@ -84,79 +96,4 @@ public class EncryptedPassportElement implements BotApiObject { */ @JsonProperty(HASH_FIELD) private String hash; - - public EncryptedPassportElement(String type, String data, String phoneNumber, String email, List files, - PassportFile frontSide, PassportFile reverseSide, PassportFile selfie) { - this.type = type; - this.data = data; - this.phoneNumber = phoneNumber; - this.email = email; - this.files = files; - this.frontSide = frontSide; - this.reverseSide = reverseSide; - this.selfie = selfie; - } - - public EncryptedPassportElement() { - } - - public String getType() { - return type; - } - - public String getData() { - return data; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public String getEmail() { - return email; - } - - public List getFiles() { - return files; - } - - public PassportFile getFrontSide() { - return frontSide; - } - - public PassportFile getReverseSide() { - return reverseSide; - } - - public PassportFile getSelfie() { - return selfie; - } - - public String getHash() { - return hash; - } - - public boolean hasTranslations() { - return translations != null && !translations.isEmpty(); - } - - public ArrayList getTranslations() { - return translations; - } - - @Override - public String toString() { - return "EncryptedPassportElement{" + - "type='" + type + '\'' + - ", data='" + data + '\'' + - ", phoneNumber='" + phoneNumber + '\'' + - ", email='" + email + '\'' + - ", files=" + files + - ", frontSide=" + frontSide + - ", reverseSide=" + reverseSide + - ", selfie=" + selfie + - ", translations=" + translations + - ", hash='" + hash + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportData.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportData.java index 95cd1973..5ff10868 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportData.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportData.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.passport; 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 java.util.List; @@ -10,6 +16,12 @@ import java.util.List; * @version 4.0.0 * Contains information about Telegram Passport data shared with the bot by the user. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PassportData implements BotApiObject { private static final String DATA_FIELD = "data"; private static final String CREDENTIALS_FIELD = "credentials"; @@ -18,28 +30,4 @@ public class PassportData implements BotApiObject { private List data; ///< Array with information about documents and other Telegram Passport data that was shared with the bot @JsonProperty(CREDENTIALS_FIELD) private EncryptedCredentials credentials; ///< Array with information about documents and other Telegram Passport data shared with the bot. - - public PassportData() { - } - - public PassportData(List data, EncryptedCredentials credentials) { - this.data = data; - this.credentials = credentials; - } - - public List getData() { - return data; - } - - public EncryptedCredentials getCredentials() { - return credentials; - } - - @Override - public String toString() { - return "PassportData{" + - "data=" + data + - ", credentials=" + credentials + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportFile.java index 73a2f6fe..8bbc427a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/PassportFile.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.passport; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * This object represents a file uploaded to Telegram Passport. * Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PassportFile implements BotApiObject { private static final String FILEID_FIELD = "file_id"; private static final String FILEUNIQUEID_FIELD = "file_unique_id"; @@ -27,39 +39,4 @@ public class PassportFile implements BotApiObject { private Integer fileSize; ///< File size @JsonProperty(FILEDATE_FIELD) private Integer fileDate; ///< Unix time when the file was uploaded - - public PassportFile() { - } - - public PassportFile(String fileId, Integer fileSize, Integer fileDate) { - this.fileId = fileId; - this.fileSize = fileSize; - this.fileDate = fileDate; - } - - public String getFileId() { - return fileId; - } - - public Integer getFileSize() { - return fileSize; - } - - public Integer getFileDate() { - return fileDate; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "PassportFile{" + - "fileId='" + fileId + '\'' + - ", fileSize=" + fileSize + - ", fileDate=" + fileDate + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorDataField.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorDataField.java index c4e3b1da..d2c562d9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorDataField.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorDataField.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the field's value changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorDataField implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -22,72 +35,25 @@ public class PassportElementErrorDataField implements PassportElementError { private static final String MESSAGE_FIELD = "message"; @JsonProperty(SOURCE_FIELD) + @NonNull private final String source = "data"; ///< Error source, must be data /** * Type of the Telegram Passport data with the error, one of “personal_details”, “passport”, “driver_license”, * “identity_card”, “internal_passport”, “address” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FIELDNAME_FIELD) + @NonNull private String fieldName; ///< Name of the data field with the error @JsonProperty(DATAHASH_FIELD) + @NonNull private String dataHash; ///< Base64-encoded data hash @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorDataField() { - super(); - } - - public PassportElementErrorDataField(String type, String fieldName, String dataHash, String message) { - super(); - this.type = checkNotNull(type); - this.fieldName = checkNotNull(fieldName); - this.dataHash = checkNotNull(dataHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorDataField setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFieldName() { - return fieldName; - } - - public PassportElementErrorDataField setFieldName(String fieldName) { - this.fieldName = checkNotNull(fieldName); - return this; - } - - public String getDataHash() { - return dataHash; - } - - public PassportElementErrorDataField setDataHash(String dataHash) { - this.dataHash = checkNotNull(dataHash); - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorDataField setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fieldName == null || fieldName.isEmpty()) { @@ -103,15 +69,4 @@ public class PassportElementErrorDataField implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorDataField{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fieldName='" + fieldName + '\'' + - ", dataHash='" + dataHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFile.java index a5e4f407..b914afe9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFile.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorFile implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -27,54 +40,15 @@ public class PassportElementErrorFile implements PassportElementError { * “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASH_FIELD) + @NonNull private String fileHash; ///< Base64-encoded file hash @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorFile() { - super(); - } - - public PassportElementErrorFile(String type, String fileHash, String message) { - super(); - this.type = checkNotNull(type); - this.fileHash = checkNotNull(fileHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorFile setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFileHash() { - return fileHash; - } - - public PassportElementErrorFile setFileHash(String fileHash) { - this.fileHash = fileHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorFile setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHash == null || fileHash.isEmpty()) { @@ -87,14 +61,4 @@ public class PassportElementErrorFile implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorFile{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHash='" + fileHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFiles.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFiles.java index bc1a8742..cacb04c5 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFiles.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFiles.java @@ -2,13 +2,19 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.ArrayList; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -17,6 +23,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file list changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorFiles implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -30,63 +43,16 @@ public class PassportElementErrorFiles implements PassportElementError { * “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASHES_FIELD) + @Singular + @NonNull private List fileHashes; ///< List of base64-encoded file hashes @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorFiles() { - super(); - } - - public PassportElementErrorFiles(String type, List fileHashes, String message) { - super(); - this.type = checkNotNull(type); - this.fileHashes = checkNotNull(fileHashes); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorFiles setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public List getFileHashes() { - return fileHashes; - } - - public PassportElementErrorFiles setFileHashes(List fileHashes) { - this.fileHashes = checkNotNull(fileHashes); - return this; - } - - public PassportElementErrorFiles addFileHash(String fileHash) { - fileHash = checkNotNull(fileHash); - if (fileHashes == null) { - fileHashes = new ArrayList<>(); - } - fileHashes.add(fileHash); - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorFiles setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHashes == null || fileHashes.isEmpty()) { @@ -99,14 +65,4 @@ public class PassportElementErrorFiles implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorFile{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHashes='" + fileHashes + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFrontSide.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFrontSide.java index 798aec4d..4ff2dd54 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFrontSide.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorFrontSide.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file with the document’s front side changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorFrontSide implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -27,54 +40,15 @@ public class PassportElementErrorFrontSide implements PassportElementError { * “driver_license”, “identity_card”, “internal_passport” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASH_FIELD) + @NonNull private String fileHash; ///< Base64-encoded file with document's front side hash @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorFrontSide() { - super(); - } - - public PassportElementErrorFrontSide(String type, String fileHash, String message) { - super(); - this.type = checkNotNull(type); - this.fileHash = checkNotNull(fileHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorFrontSide setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFileHash() { - return fileHash; - } - - public PassportElementErrorFrontSide setFileHash(String fileHash) { - this.fileHash = fileHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorFrontSide setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHash == null || fileHash.isEmpty()) { @@ -87,14 +61,4 @@ public class PassportElementErrorFrontSide implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorFrontSide{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHash='" + fileHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorReverseSide.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorReverseSide.java index c56168a4..16775565 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorReverseSide.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorReverseSide.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file with the document’s reverse side changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorReverseSide implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -26,54 +39,15 @@ public class PassportElementErrorReverseSide implements PassportElementError { * Type of the Telegram Passport data with the error, one of “driver_license”, “identity_card” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASH_FIELD) + @NonNull private String fileHash; ///< Base64-encoded hash of file with document's reverse side @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorReverseSide() { - super(); - } - - public PassportElementErrorReverseSide(String type, String fileHash, String message) { - super(); - this.type = checkNotNull(type); - this.fileHash = checkNotNull(fileHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorReverseSide setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFileHash() { - return fileHash; - } - - public PassportElementErrorReverseSide setFileHash(String fileHash) { - this.fileHash = fileHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorReverseSide setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHash == null || fileHash.isEmpty()) { @@ -86,14 +60,4 @@ public class PassportElementErrorReverseSide implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorReverseSide{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHash='" + fileHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorSelfie.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorSelfie.java index 9a8c0035..413c922e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorSelfie.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorSelfie.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.0.0 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file with the selfie changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorSelfie implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -27,54 +40,15 @@ public class PassportElementErrorSelfie implements PassportElementError { * “driver_license”, “identity_card”, “internal_passport” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASH_FIELD) + @NonNull private String fileHash; ///< Base64-encoded hash of file with selfie @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorSelfie() { - super(); - } - - public PassportElementErrorSelfie(String type, String fileHash, String message) { - super(); - this.type = checkNotNull(type); - this.fileHash = checkNotNull(fileHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorSelfie setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFileHash() { - return fileHash; - } - - public PassportElementErrorSelfie setFileHash(String fileHash) { - this.fileHash = fileHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorSelfie setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHash == null || fileHash.isEmpty()) { @@ -87,14 +61,4 @@ public class PassportElementErrorSelfie implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorSelfie{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHash='" + fileHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFile.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFile.java index 061d9ed2..60da8efc 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFile.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFile.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.1 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when the file changes. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorTranslationFile implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -28,54 +41,15 @@ public class PassportElementErrorTranslationFile implements PassportElementError * “passport_registration”, “temporary_registration” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASH_FIELD) + @NonNull private String fileHash; ///< Base64-encoded file hash @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorTranslationFile() { - super(); - } - - public PassportElementErrorTranslationFile(String type, String fileHash, String message) { - super(); - this.type = checkNotNull(type); - this.fileHash = checkNotNull(fileHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorTranslationFile setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getFileHash() { - return fileHash; - } - - public PassportElementErrorTranslationFile setFileHash(String fileHash) { - this.fileHash = fileHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorTranslationFile setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHash == null || fileHash.isEmpty()) { @@ -88,14 +62,4 @@ public class PassportElementErrorTranslationFile implements PassportElementError throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorTranslationFile{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHash='" + fileHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java index a6d37296..f2be141f 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java @@ -2,13 +2,19 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.ArrayList; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.1 @@ -17,6 +23,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when a file with the document translation change. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorTranslationFiles implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -31,63 +44,16 @@ public class PassportElementErrorTranslationFiles implements PassportElementErro * “passport_registration”, “temporary_registration” */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(FILEHASHES_FIELD) + @NonNull + @Singular private List fileHashes; ///< List of base64-encoded file hashes @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorTranslationFiles() { - super(); - } - - public PassportElementErrorTranslationFiles(String type, List fileHashes, String message) { - super(); - this.type = checkNotNull(type); - this.fileHashes = checkNotNull(fileHashes); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorTranslationFiles setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public List getFileHashes() { - return fileHashes; - } - - public PassportElementErrorTranslationFiles setFileHashes(List fileHashes) { - this.fileHashes = checkNotNull(fileHashes); - return this; - } - - public PassportElementErrorTranslationFiles addFileHash(String fileHash) { - fileHash = checkNotNull(fileHash); - if (fileHashes == null) { - fileHashes = new ArrayList<>(); - } - fileHashes.add(fileHash); - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorTranslationFiles setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (fileHashes == null || fileHashes.isEmpty()) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorUnspecified.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorUnspecified.java index 42b30233..77357707 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorUnspecified.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorUnspecified.java @@ -2,10 +2,16 @@ package org.telegram.telegrambots.meta.api.objects.passport.dataerror; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 4.1 @@ -14,6 +20,13 @@ import static com.google.common.base.Preconditions.checkNotNull; * The error is considered resolved when new data is added. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class PassportElementErrorUnspecified implements PassportElementError { private static final String SOURCE_FIELD = "source"; private static final String TYPE_FIELD = "type"; @@ -26,54 +39,15 @@ public class PassportElementErrorUnspecified implements PassportElementError { * Type of element of the user's Telegram Passport which has the issue */ @JsonProperty(TYPE_FIELD) + @NonNull private String type; @JsonProperty(ELEMENTHASH_FIELD) + @NonNull private String elementHash; ///< Base64-encoded element hash @JsonProperty(MESSAGE_FIELD) + @NonNull private String message; ///< Error message - public PassportElementErrorUnspecified() { - super(); - } - - public PassportElementErrorUnspecified(String type, String elementHash, String message) { - super(); - this.type = checkNotNull(type); - this.elementHash = checkNotNull(elementHash); - this.message = checkNotNull(message); - } - - public String getType() { - return type; - } - - public PassportElementErrorUnspecified setType(String type) { - this.type = checkNotNull(type); - return this; - } - - public String getSource() { - return source; - } - - public String getElementHash() { - return elementHash; - } - - public PassportElementErrorUnspecified setElementHash(String elementHash) { - this.elementHash = elementHash; - return this; - } - - public String getMessage() { - return message; - } - - public PassportElementErrorUnspecified setMessage(String message) { - this.message = checkNotNull(message); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (elementHash == null || elementHash.isEmpty()) { @@ -86,14 +60,4 @@ public class PassportElementErrorUnspecified implements PassportElementError { throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorFile{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", elementHash='" + elementHash + '\'' + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/Invoice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/Invoice.java index 43ab5fc4..488f8b87 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/Invoice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/Invoice.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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.PhotoSize; @@ -10,6 +16,12 @@ import org.telegram.telegrambots.meta.api.objects.PhotoSize; * * This object contains basic information about an invoice. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Invoice implements BotApiObject { private static final String TITLE_FIELD = "title"; private static final String DESCRIPTION_FIELD = "description"; @@ -26,52 +38,12 @@ public class Invoice implements BotApiObject { private String startParameter; ///< Unique bot deep-linking parameter for generation of this invoice @JsonProperty(CURRENCY_FIELD) private String currency; ///< Three-letter ISO 4217 currency code - @JsonProperty(TOTAL_AMOUNT_FIELD) /** * Total price in the smallest units of the currency (integer, not float/double). * For example, for a price of US$ 1.45 pass amount = 145. */ + @JsonProperty(TOTAL_AMOUNT_FIELD) private Integer totalAmount; ///< Goods total price in minimal quantity of the currency @JsonProperty(PHOTO_FIELD) private PhotoSize photo; ///< Optional. Goods photo - - public Invoice() { - super(); - } - - public String getTitle() { - return title; - } - - public String getDescription() { - return description; - } - - public String getStartParameter() { - return startParameter; - } - - public String getCurrency() { - return currency; - } - - public Integer getTotalAmount() { - return totalAmount; - } - - public PhotoSize getPhoto() { - return photo; - } - - @Override - public String toString() { - return "Invoice{" + - "title='" + title + '\'' + - ", description='" + description + '\'' + - ", startParameter='" + startParameter + '\'' + - ", currency='" + currency + '\'' + - ", totalAmount=" + totalAmount + - ", photo=" + photo + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java index 9ddcd105..a193d5b8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/LabeledPrice.java @@ -1,17 +1,27 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * This object represents a portion of goods price. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class LabeledPrice implements Validable, BotApiObject { private static final String LABEL_FIELD = "label"; private static final String AMOUNT_FIELD = "amount"; @@ -25,40 +35,6 @@ public class LabeledPrice implements Validable, BotApiObject { @JsonProperty(AMOUNT_FIELD) private Integer amount; - /** - * Builds an empty LabeledPrice - */ - public LabeledPrice() { - super(); - } - - /** - * Builds a LabeledPrice with mandatory parameters - * @param label Portion label - * @param amount Currency amount in minimal quantity of the currency - */ - public LabeledPrice(String label, Integer amount) { - super(); - this.label = checkNotNull(label); - this.amount = checkNotNull(amount); - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = checkNotNull(label); - } - - public Integer getAmount() { - return amount; - } - - public void setAmount(Integer amount) { - this.amount = checkNotNull(amount); - } - @Override public void validate() throws TelegramApiValidationException { if (label == null || label.isEmpty()) { @@ -68,12 +44,4 @@ public class LabeledPrice implements Validable, BotApiObject { throw new TelegramApiValidationException("Amount parameter can't be empty", this); } } - - @Override - public String toString() { - return "LabeledPrice{" + - "label='" + label + '\'' + - ", amount=" + amount + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/OrderInfo.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/OrderInfo.java index 7bfbef5a..f453fde4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/OrderInfo.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/OrderInfo.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * * This object represents information about an order. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class OrderInfo implements BotApiObject { private static final String NAME_FIELD = "name"; private static final String PHONE_NUMBER_FIELD = "phone_number"; @@ -23,34 +35,4 @@ public class OrderInfo implements BotApiObject { private String email; ///< Optional. User email @JsonProperty(SHIPPING_ADDRESS_FIELD) private ShippingAddress shippingAddress; ///< Optional. First line for the address - - public OrderInfo() { - super(); - } - - public String getName() { - return name; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public String getEmail() { - return email; - } - - public ShippingAddress getShippingAddress() { - return shippingAddress; - } - - @Override - public String toString() { - return "OrderInfo{" + - "name='" + name + '\'' + - ", phoneNumber='" + phoneNumber + '\'' + - ", email='" + email + '\'' + - ", shippingAddress=" + shippingAddress + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/PreCheckoutQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/PreCheckoutQuery.java index 839c95e9..1322aff9 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/PreCheckoutQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/PreCheckoutQuery.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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; @@ -10,6 +16,12 @@ import org.telegram.telegrambots.meta.api.objects.User; * * This object contains information about incoming pre-checkout query. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PreCheckoutQuery implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FROM_FIELD = "from"; @@ -25,11 +37,11 @@ public class PreCheckoutQuery implements BotApiObject { private User from; ///< User who sent the query @JsonProperty(CURRENCY_FIELD) private String currency; ///< Three-letter ISO 4217 currency code - @JsonProperty(TOTAL_AMOUNT_FIELD) /** * Total price in the smallest units of the currency (integer, not float/double). * For example, for a price of US$ 1.45 pass amount = 145. */ + @JsonProperty(TOTAL_AMOUNT_FIELD) private Integer totalAmount; @JsonProperty(INVOICE_PAYLOAD_FIELD) private String invoicePayload; ///< Bot specified invoice payload @@ -37,49 +49,4 @@ public class PreCheckoutQuery implements BotApiObject { private String shippingOptionId; ///< Optional. Identifier of a chosen by user shipping option @JsonProperty(ORDER_INFO_FIELD) private OrderInfo orderInfo; ///< Optional. Order info provided by the user - - public PreCheckoutQuery() { - super(); - } - - public String getId() { - return id; - } - - public User getFrom() { - return from; - } - - public String getCurrency() { - return currency; - } - - public Integer getTotalAmount() { - return totalAmount; - } - - public String getInvoicePayload() { - return invoicePayload; - } - - public String getShippingOptionId() { - return shippingOptionId; - } - - public OrderInfo getOrderInfo() { - return orderInfo; - } - - @Override - public String toString() { - return "PreCheckoutQuery{" + - "id='" + id + '\'' + - ", from=" + from + - ", currency='" + currency + '\'' + - ", totalAmount=" + totalAmount + - ", invoicePayload='" + invoicePayload + '\'' + - ", shippingOptionId='" + shippingOptionId + '\'' + - ", orderInfo=" + orderInfo + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingAddress.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingAddress.java index 085d7325..e829685a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingAddress.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingAddress.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * * 2-letter ISO 3166-1 alpha-2 country code */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class ShippingAddress implements BotApiObject { private static final String COUNTRY_CODE_FIELD = "country_code"; private static final String STATE_FIELD = "state"; @@ -29,44 +41,4 @@ public class ShippingAddress implements BotApiObject { private String streetLine2; ///< Second line for the address @JsonProperty(POST_CODE_FIELD) private String postCode; ///< Address post code - - public ShippingAddress() { - super(); - } - - public String getCountryCode() { - return countryCode; - } - - public String getState() { - return state; - } - - public String getCity() { - return city; - } - - public String getStreetLine1() { - return streetLine1; - } - - public String getStreetLine2() { - return streetLine2; - } - - public String getPostCode() { - return postCode; - } - - @Override - public String toString() { - return "ShippingAddress{" + - "countryCode='" + countryCode + '\'' + - ", state='" + state + '\'' + - ", city='" + city + '\'' + - ", streetLine1='" + streetLine1 + '\'' + - ", streetLine2='" + streetLine2 + '\'' + - ", postCode='" + postCode + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java index ea883ff2..1e3a16e8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingOption.java @@ -1,78 +1,50 @@ package org.telegram.telegrambots.meta.api.objects.payments; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 * * This object represents one shipping option. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class ShippingOption implements Validable, BotApiObject { private static final String ID_FIELD = "id"; private static final String TITLE_FIELD = "title"; private static final String PRICES_FIELD = "prices"; @JsonProperty(ID_FIELD) + @NonNull private String id; ///< Shipping option identifier @JsonProperty(TITLE_FIELD) + @NonNull private String title; ///< Option title @JsonProperty(PRICES_FIELD) + @NonNull + @Singular private List prices; ///< List of price portions - /** - * Creates an empty shipping option - */ - public ShippingOption() { - super(); - } - - /** - * Creates a shipping option with mandatory fields - * @param id Shipping option identifier - * @param title Option title - * @param prices List of price portions - */ - public ShippingOption(String id, String title, List prices) { - this.id = checkNotNull(id); - this.title = checkNotNull(title); - this.prices = checkNotNull(prices); - } - - public String getId() { - return id; - } - - public ShippingOption setId(String id) { - this.id = checkNotNull(id); - return this; - } - - public String getTitle() { - return title; - } - - public ShippingOption setTitle(String title) { - this.title = checkNotNull(title); - return this; - } - - public List getPrices() { - return prices; - } - - public ShippingOption setPrices(List prices) { - this.prices = checkNotNull(prices); - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (id == null || id.isEmpty()) { @@ -88,13 +60,4 @@ public class ShippingOption implements Validable, BotApiObject { price.validate(); } } - - @Override - public String toString() { - return "ShippingOption{" + - "id='" + id + '\'' + - ", title='" + title + '\'' + - ", prices=" + prices + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingQuery.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingQuery.java index c636089a..4b5335ba 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingQuery.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/ShippingQuery.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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; @@ -10,6 +16,12 @@ import org.telegram.telegrambots.meta.api.objects.User; * * This object contains information about incoming shipping query. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class ShippingQuery implements BotApiObject { private static final String ID_FIELD = "id"; private static final String FROM_FIELD = "from"; @@ -24,34 +36,4 @@ public class ShippingQuery implements BotApiObject { private String invoicePayload; ///< Bot specified invoice payload @JsonProperty(SHIPPING_ADDRESS_FIELD) private ShippingAddress shippingAddress; ///< User specified shipping address - - public ShippingQuery() { - super(); - } - - public String getId() { - return id; - } - - public User getFrom() { - return from; - } - - public String getInvoicePayload() { - return invoicePayload; - } - - public ShippingAddress getShippingAddress() { - return shippingAddress; - } - - @Override - public String toString() { - return "ShippingQuery{" + - "id='" + id + '\'' + - ", from=" + from + - ", invoicePayload='" + invoicePayload + '\'' + - ", shippingAddress=" + shippingAddress + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/SuccessfulPayment.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/SuccessfulPayment.java index 2d4ddbc0..07f63553 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/SuccessfulPayment.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/payments/SuccessfulPayment.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.payments; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * * This object contains basic information about a successful payment. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class SuccessfulPayment implements BotApiObject { private static final String CURRENCY_FIELD = "currency"; private static final String TOTAL_AMOUNT_FIELD = "total_amount"; @@ -20,11 +32,11 @@ public class SuccessfulPayment implements BotApiObject { @JsonProperty(CURRENCY_FIELD) private String currency; ///< Three-letter ISO 4217 currency code - @JsonProperty(TOTAL_AMOUNT_FIELD) /** * Total price in the smallest units of the currency (integer, not float/double). * For example, for a price of US$ 1.45 pass amount = 145. */ + @JsonProperty(TOTAL_AMOUNT_FIELD) private Integer totalAmount; @JsonProperty(INVOICE_PAYLOAD_FIELD) private String invoicePayload; ///< Bot specified invoice payload @@ -36,49 +48,4 @@ public class SuccessfulPayment implements BotApiObject { private String telegramPaymentChargeId; ///< Telegram payment identifier @JsonProperty(PROVIDER_PAYMENT_CHARGE_ID_FIELD) private String providerPaymentChargeId; ///< Provider payment identifier - - public SuccessfulPayment() { - super(); - } - - public String getCurrency() { - return currency; - } - - public Integer getTotalAmount() { - return totalAmount; - } - - public String getInvoicePayload() { - return invoicePayload; - } - - public String getShippingOptionId() { - return shippingOptionId; - } - - public OrderInfo getOrderInfo() { - return orderInfo; - } - - public String getTelegramPaymentChargeId() { - return telegramPaymentChargeId; - } - - public String getProviderPaymentChargeId() { - return providerPaymentChargeId; - } - - @Override - public String toString() { - return "SuccessfulPayment{" + - "currency='" + currency + '\'' + - ", totalAmount=" + totalAmount + - ", invoicePayload='" + invoicePayload + '\'' + - ", shippingOptionId='" + shippingOptionId + '\'' + - ", orderInfo=" + orderInfo + - ", telegramPaymentChargeId='" + telegramPaymentChargeId + '\'' + - ", providerPaymentChargeId='" + providerPaymentChargeId + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/Poll.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/Poll.java index f4c62de0..acacc845 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/Poll.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/Poll.java @@ -1,11 +1,16 @@ package org.telegram.telegrambots.meta.api.objects.polls; 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.MessageEntity; import java.util.List; -import java.util.Objects; /** * @author Ruben Bermudez @@ -13,6 +18,12 @@ import java.util.Objects; * * This object contains information about a poll. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Poll implements BotApiObject { private static final String ID_FIELD = "id"; private static final String QUESTION_FIELD = "question"; @@ -60,139 +71,4 @@ public class Poll implements BotApiObject { private String explanation; ///< Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters @JsonProperty(EXPLANATIONENTITIES_FIELD) private List explanationEntities; ///< Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the explanation - - public Poll() { - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getQuestion() { - return question; - } - - public void setQuestion(String question) { - this.question = question; - } - - public List getOptions() { - return options; - } - - public void setOptions(List options) { - this.options = options; - } - - public Boolean getClosed() { - return isClosed; - } - - public void setClosed(Boolean closed) { - isClosed = closed; - } - - public Integer getTotalVoterCount() { - return totalVoterCount; - } - - public void setTotalVoterCount(Integer totalVoterCount) { - this.totalVoterCount = totalVoterCount; - } - - public Boolean getAnonymous() { - return isAnonymous; - } - - public void setAnonymous(Boolean anonymous) { - isAnonymous = anonymous; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Boolean getAllowMultipleAnswers() { - return allowMultipleAnswers; - } - - public void setAllowMultipleAnswers(Boolean allowMultipleAnswers) { - this.allowMultipleAnswers = allowMultipleAnswers; - } - - public Integer getCorrectOptionId() { - return correctOptionId; - } - - public void setCorrectOptionId(Integer correctOptionId) { - this.correctOptionId = correctOptionId; - } - - public Integer getOpenPeriod() { - return openPeriod; - } - - public Integer getCloseDate() { - return closeDate; - } - - public String getExplanation() { - return explanation; - } - - public List getExplanationEntities() { - return explanationEntities; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Poll)) return false; - Poll poll = (Poll) o; - return Objects.equals(id, poll.id) && - Objects.equals(question, poll.question) && - Objects.equals(options, poll.options) && - Objects.equals(totalVoterCount, poll.totalVoterCount) && - Objects.equals(isClosed, poll.isClosed) && - Objects.equals(isAnonymous, poll.isAnonymous) && - Objects.equals(type, poll.type) && - Objects.equals(allowMultipleAnswers, poll.allowMultipleAnswers) && - Objects.equals(correctOptionId, poll.correctOptionId) && - Objects.equals(openPeriod, poll.openPeriod) && - Objects.equals(closeDate, poll.closeDate) && - Objects.equals(explanation, poll.explanation) && - Objects.equals(explanationEntities, poll.explanationEntities); - } - - @Override - public int hashCode() { - return Objects.hash(id, question, options, totalVoterCount, isClosed, isAnonymous, type, allowMultipleAnswers, correctOptionId, openPeriod, closeDate, explanation, explanationEntities); - } - - @Override - public String toString() { - return "Poll{" + - "id='" + id + '\'' + - ", question='" + question + '\'' + - ", options=" + options + - ", totalVoterCount=" + totalVoterCount + - ", isClosed=" + isClosed + - ", isAnonymous=" + isAnonymous + - ", type='" + type + '\'' + - ", allowMultipleAnswers=" + allowMultipleAnswers + - ", correctOptionId=" + correctOptionId + - ", openPeriod=" + openPeriod + - ", closeDate=" + closeDate + - ", explanation='" + explanation + '\'' + - ", explanationEntities=" + explanationEntities + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollAnswer.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollAnswer.java index 15093821..ee5edd0a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollAnswer.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollAnswer.java @@ -1,11 +1,16 @@ package org.telegram.telegrambots.meta.api.objects.polls; 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; -import java.util.Objects; /** * @author Ruben Bermudez @@ -13,6 +18,12 @@ import java.util.Objects; * * This object represents an answer of a user in a non-anonymous poll. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PollAnswer implements BotApiObject { private static final String POLLID_FIELD = "poll_id"; private static final String USER_FIELD = "user"; @@ -24,55 +35,4 @@ public class PollAnswer implements BotApiObject { private User user; ///< The user, who changed the answer to the poll @JsonProperty(OPTIONIDS_FIELD) private List optionIds; ///< 0-based identifiers of answer options, chosen by the user. May be empty if the user retracted their vote. - - public PollAnswer() { - } - - public String getPollId() { - return pollId; - } - - public void setPollId(String pollId) { - this.pollId = pollId; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public List getOptionIds() { - return optionIds; - } - - public void setOptionIds(List optionIds) { - this.optionIds = optionIds; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PollAnswer)) return false; - PollAnswer that = (PollAnswer) o; - return Objects.equals(pollId, that.pollId) && - Objects.equals(user, that.user) && - Objects.equals(optionIds, that.optionIds); - } - - @Override - public int hashCode() { - return Objects.hash(pollId, user, optionIds); - } - - @Override - public String toString() { - return "PollAnswer{" + - "pollId='" + pollId + '\'' + - ", user=" + user + - ", optionIds=" + optionIds + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollOption.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollOption.java index 85cef066..c92d6096 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollOption.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/polls/PollOption.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.polls; 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; /** @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; * * This object contains information about one answer option in a poll. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class PollOption implements BotApiObject { private static final String TEXT_FIELD = "text"; private static final String VOTERCOUNT_FIELD = "voter_count"; @@ -17,31 +29,4 @@ public class PollOption implements BotApiObject { private String text; ///< Option text, 1-100 characters @JsonProperty(VOTERCOUNT_FIELD) private Integer voterCount; ///< Number of users that voted for this option - - public PollOption() { - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - - public Integer getVoterCount() { - return voterCount; - } - - public void setVoterCount(Integer voterCount) { - this.voterCount = voterCount; - } - - @Override - public String toString() { - return "PollOption{" + - "text='" + text + '\'' + - ", voterCount=" + voterCount + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ForceReplyKeyboard.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ForceReplyKeyboard.java index 3afc3a4e..fe0c6d56 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ForceReplyKeyboard.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ForceReplyKeyboard.java @@ -1,12 +1,18 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import java.util.Objects; - /** * @author Ruben Bermudez * @version 1.0 @@ -16,6 +22,14 @@ import java.util.Objects; * sacrifice privacy mode. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class ForceReplyKeyboard implements ReplyKeyboard { private static final String FORCEREPLY_FIELD = "force_reply"; private static final String SELECTIVE_FIELD = "selective"; @@ -25,8 +39,11 @@ public class ForceReplyKeyboard implements ReplyKeyboard { * ’Reply' */ @JsonProperty(FORCEREPLY_FIELD) + @NonNull private Boolean forceReply; /** + * Optional. + * * Use this parameter if you want to force reply from specific users only. Targets: 1) users * that are @mentioned in the text of the Message object; 2) if the bot's message is a reply * (has reply_to_message_id), sender of the original message. @@ -34,55 +51,10 @@ public class ForceReplyKeyboard implements ReplyKeyboard { @JsonProperty(SELECTIVE_FIELD) private Boolean selective; - public ForceReplyKeyboard() { - super(); - this.forceReply = true; - } - - public Boolean getForceReply() { - return forceReply; - } - - public Boolean getSelective() { - return selective; - } - - public ForceReplyKeyboard setSelective(Boolean selective) { - this.selective = selective; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (forceReply == null) { throw new TelegramApiValidationException("ForceReply parameter can't not be null", this); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof ForceReplyKeyboard)) { - return false; - } - ForceReplyKeyboard forceReplyKeyboard = (ForceReplyKeyboard) o; - return Objects.equals(forceReply, forceReplyKeyboard.forceReply) - && Objects.equals(selective, forceReplyKeyboard.selective) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - forceReply, - selective); - } - - @Override - public String toString() { - return "ForceReplyKeyboard{" + - "forceReply=" + forceReply + - ", selective=" + selective + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/InlineKeyboardMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/InlineKeyboardMarkup.java index 0b042c4a..2ed56cd4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/InlineKeyboardMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/InlineKeyboardMarkup.java @@ -1,14 +1,20 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * @author Ruben Bermudez @@ -17,32 +23,22 @@ import java.util.Objects; * belongs to. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class InlineKeyboardMarkup implements ReplyKeyboard { private static final String KEYBOARD_FIELD = "inline_keyboard"; @JsonProperty(KEYBOARD_FIELD) + @NonNull + @Singular(value = "keyboardRow") private List> keyboard; ///< Array of button rows, each represented by an Array of Strings - public InlineKeyboardMarkup() { - super(); - keyboard = new ArrayList<>(); - } - - public InlineKeyboardMarkup(List> keyboard) { - super(); - this.keyboard = keyboard; - } - - public List> getKeyboard() { - return keyboard; - } - - public InlineKeyboardMarkup setKeyboard(List> keyboard) { - this.keyboard = keyboard; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (keyboard == null) { @@ -54,26 +50,4 @@ public class InlineKeyboardMarkup implements ReplyKeyboard { } } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof InlineKeyboardMarkup)) { - return false; - } - InlineKeyboardMarkup inlineKeyboardMarkup = (InlineKeyboardMarkup) o; - return Objects.equals(keyboard, inlineKeyboardMarkup.keyboard); - } - - @Override - public int hashCode() { - return Objects.hash(keyboard); - } - - @Override - public String toString() { - return "InlineKeyboardMarkup{" + - "inline_keyboard=" + keyboard + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardMarkup.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardMarkup.java index c225d235..5f7a871e 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardMarkup.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardMarkup.java @@ -1,14 +1,21 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.Singular; +import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.ArrayList; import java.util.List; -import java.util.Objects; /** * @author Ruben Bermudez @@ -16,6 +23,14 @@ import java.util.Objects; * This object represents a custom keyboard with reply options. */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class ReplyKeyboardMarkup implements ReplyKeyboard { private static final String KEYBOARD_FIELD = "keyboard"; @@ -24,6 +39,9 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { private static final String SELECTIVE_FIELD = "selective"; @JsonProperty(KEYBOARD_FIELD) + @NonNull + @Singular(value = "keyboardRow") + @Setter private List keyboard; ///< Array of button rows, each represented by an Array of Strings @JsonProperty(RESIZEKEYBOARD_FIELD) private Boolean resizeKeyboard; ///< Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false. @@ -38,52 +56,6 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { @JsonProperty(SELECTIVE_FIELD) private Boolean selective; - public ReplyKeyboardMarkup() { - super(); - keyboard = new ArrayList<>(); - } - - public ReplyKeyboardMarkup(List keyboard) { - super(); - this.keyboard = keyboard; - } - - public List getKeyboard() { - return keyboard; - } - - public ReplyKeyboardMarkup setKeyboard(List keyboard) { - this.keyboard = keyboard; - return this; - } - - public Boolean getResizeKeyboard() { - return resizeKeyboard; - } - - public ReplyKeyboardMarkup setResizeKeyboard(Boolean resizeKeyboard) { - this.resizeKeyboard = resizeKeyboard; - return this; - } - - public Boolean getOneTimeKeyboard() { - return oneTimeKeyboard; - } - - public ReplyKeyboardMarkup setOneTimeKeyboard(Boolean oneTimeKeyboard) { - this.oneTimeKeyboard = oneTimeKeyboard; - return this; - } - - public Boolean getSelective() { - return selective; - } - - public ReplyKeyboardMarkup setSelective(Boolean selective) { - this.selective = selective; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (keyboard == null) { @@ -93,37 +65,4 @@ public class ReplyKeyboardMarkup implements ReplyKeyboard { keyboardButtons.validate(); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof ReplyKeyboardMarkup)) { - return false; - } - ReplyKeyboardMarkup replyKeyboardMarkup = (ReplyKeyboardMarkup) o; - return Objects.equals(keyboard, replyKeyboardMarkup.keyboard) - && Objects.equals(oneTimeKeyboard, replyKeyboardMarkup.oneTimeKeyboard) - && Objects.equals(resizeKeyboard, replyKeyboardMarkup.resizeKeyboard) - && Objects.equals(selective, replyKeyboardMarkup.selective) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - keyboard, - oneTimeKeyboard, - resizeKeyboard, - selective); - } - - @Override - public String toString() { - return "ReplyKeyboardMarkup{" + - "keyboard=" + keyboard + - ", resizeKeyboard=" + resizeKeyboard + - ", oneTimeKeyboard=" + oneTimeKeyboard + - ", selective=" + selective + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardRemove.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardRemove.java index 8133517f..ac2f4748 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardRemove.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/ReplyKeyboardRemove.java @@ -1,12 +1,18 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard; import com.fasterxml.jackson.annotation.JsonProperty; - import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +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.exceptions.TelegramApiValidationException; -import java.util.Objects; - /** * @author Ruben Bermudez * @version 1.0 @@ -16,11 +22,20 @@ import java.util.Objects; * hidden immediately after the user presses a button (@see ReplyKeyboardMarkup). */ @JsonDeserialize +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class ReplyKeyboardRemove implements ReplyKeyboard { private static final String REMOVEKEYBOARD_FIELD = "remove_keyboard"; private static final String SELECTIVE_FIELD = "selective"; @JsonProperty(REMOVEKEYBOARD_FIELD) + @NonNull private Boolean removeKeyboard; ///< Requests clients to remove the custom keyboard /** * Optional. Use this parameter if you want to show the keyboard to specific users only. @@ -30,55 +45,10 @@ public class ReplyKeyboardRemove implements ReplyKeyboard { @JsonProperty(SELECTIVE_FIELD) private Boolean selective; - public ReplyKeyboardRemove() { - super(); - this.removeKeyboard = true; - } - - public Boolean getRemoveKeyboard() { - return removeKeyboard; - } - - public Boolean getSelective() { - return selective; - } - - public ReplyKeyboardRemove setSelective(Boolean selective) { - this.selective = selective; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (removeKeyboard == null) { throw new TelegramApiValidationException("RemoveKeyboard parameter can't be null", this); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof ReplyKeyboardRemove)) { - return false; - } - ReplyKeyboardRemove replyKeyboardRemove = (ReplyKeyboardRemove) o; - return Objects.equals(removeKeyboard, replyKeyboardRemove.removeKeyboard) - && Objects.equals(selective, replyKeyboardRemove.selective) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - removeKeyboard, - selective); - } - - @Override - public String toString() { - return "ReplyKeyboardRemove{" + - "removeKeyboard=" + removeKeyboard + - ", selective=" + selective + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java index 20017a11..5bee7fb6 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/InlineKeyboardButton.java @@ -1,16 +1,21 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; import com.fasterxml.jackson.annotation.JsonProperty; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.api.objects.LoginUrl; import org.telegram.telegrambots.meta.api.objects.games.CallbackGame; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * @author Ruben Bermudez * @version 1.0 @@ -19,6 +24,14 @@ import static com.google.common.base.Preconditions.checkNotNull; * @apiNote This will only work in Telegram versions released after 9 April, 2016. Older clients will * display unsupported message. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class InlineKeyboardButton implements Validable, BotApiObject { private static final String TEXT_FIELD = "text"; @@ -31,6 +44,7 @@ public class InlineKeyboardButton implements Validable, BotApiObject { private static final String LOGIN_URL_FIELD = "login_url"; @JsonProperty(TEXT_FIELD) + @NonNull private String text; ///< Label text on the button @JsonProperty(URL_FIELD) private String url; ///< Optional. HTTP or tg:// url to be opened when button is pressed @@ -78,86 +92,6 @@ public class InlineKeyboardButton implements Validable, BotApiObject { @JsonProperty(LOGIN_URL_FIELD) private LoginUrl loginUrl; - public InlineKeyboardButton() { - super(); - } - - public InlineKeyboardButton(String text) { - this.text = checkNotNull(text); - } - - public String getText() { - return text; - } - - public InlineKeyboardButton setText(String text) { - this.text = text; - return this; - } - - public String getUrl() { - return url; - } - - public InlineKeyboardButton setUrl(String url) { - this.url = url; - return this; - } - - public String getCallbackData() { - return callbackData; - } - - public InlineKeyboardButton setCallbackData(String callbackData) { - this.callbackData = callbackData; - return this; - } - - public String getSwitchInlineQuery() { - return switchInlineQuery; - } - - public InlineKeyboardButton setSwitchInlineQuery(String switchInlineQuery) { - this.switchInlineQuery = switchInlineQuery; - return this; - } - - public CallbackGame getCallbackGame() { - return callbackGame; - } - - public InlineKeyboardButton setCallbackGame(CallbackGame callbackGame) { - this.callbackGame = callbackGame; - return this; - } - - public String getSwitchInlineQueryCurrentChat() { - return switchInlineQueryCurrentChat; - } - - public InlineKeyboardButton setSwitchInlineQueryCurrentChat(String switchInlineQueryCurrentChat) { - this.switchInlineQueryCurrentChat = switchInlineQueryCurrentChat; - return this; - } - - public Boolean getPay() { - return pay; - } - - public InlineKeyboardButton setPay(Boolean pay) { - this.pay = pay; - return this; - } - - public LoginUrl getLoginUrl() { - return loginUrl; - } - - public InlineKeyboardButton setLoginUrl(LoginUrl loginUrl) { - this.loginUrl = loginUrl; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (text == null || text.isEmpty()) { @@ -167,49 +101,4 @@ public class InlineKeyboardButton implements Validable, BotApiObject { loginUrl.validate(); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof InlineKeyboardButton)) { - return false; - } - InlineKeyboardButton inlineKeyboardButton = (InlineKeyboardButton) o; - return Objects.equals(callbackData, inlineKeyboardButton.callbackData) - && Objects.equals(callbackGame, inlineKeyboardButton.callbackGame) - && Objects.equals(pay, inlineKeyboardButton.pay) - && Objects.equals(switchInlineQuery, inlineKeyboardButton.switchInlineQuery) - && Objects.equals(switchInlineQueryCurrentChat, inlineKeyboardButton.switchInlineQueryCurrentChat) - && Objects.equals(text, inlineKeyboardButton.text) - && Objects.equals(url, inlineKeyboardButton.url) - && Objects.equals(loginUrl, inlineKeyboardButton.loginUrl) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - callbackData, - callbackGame, - pay, - switchInlineQuery, - switchInlineQueryCurrentChat, - text, - url, - loginUrl); - } - - @Override - public String toString() { - return "InlineKeyboardButton{" + - "text='" + text + '\'' + - ", url='" + url + '\'' + - ", callbackData='" + callbackData + '\'' + - ", callbackGame=" + callbackGame + - ", switchInlineQuery='" + switchInlineQuery + '\'' + - ", switchInlineQueryCurrentChat='" + switchInlineQueryCurrentChat + '\'' + - ", pay=" + pay + - ", loginUrl=" + loginUrl + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java index dbf087e7..fb0adcfd 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButton.java @@ -1,12 +1,19 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; import com.fasterxml.jackson.annotation.JsonProperty; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.Objects; - /** * @author Ruben Bermudez * @version 1.0 @@ -19,6 +26,14 @@ import java.util.Objects; * @apiNote request_poll option will only work in Telegram versions released after 1X January, 2020. * Older clients will receive unsupported message. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@RequiredArgsConstructor +@AllArgsConstructor +@Builder public class KeyboardButton implements Validable, BotApiObject { private static final String TEXT_FIELD = "text"; @@ -30,6 +45,7 @@ public class KeyboardButton implements Validable, BotApiObject { * If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed */ @JsonProperty(TEXT_FIELD) + @NonNull private String text; /** * Optional. @@ -53,51 +69,6 @@ public class KeyboardButton implements Validable, BotApiObject { @JsonProperty(REQUEST_POLL_FIELD) private KeyboardButtonPollType requestPoll; - public KeyboardButton() { - super(); - } - - public KeyboardButton(String text) { - super(); - this.text = text; - } - - public String getText() { - return text; - } - - public KeyboardButton setText(String text) { - this.text = text; - return this; - } - - public Boolean getRequestContact() { - return requestContact; - } - - public KeyboardButton setRequestContact(Boolean requestContact) { - this.requestContact = requestContact; - return this; - } - - public Boolean getRequestLocation() { - return requestLocation; - } - - public KeyboardButton setRequestLocation(Boolean requestLocation) { - this.requestLocation = requestLocation; - return this; - } - - public KeyboardButtonPollType getRequestPoll() { - return requestPoll; - } - - public KeyboardButton setRequestPoll(KeyboardButtonPollType requestPoll) { - this.requestPoll = requestPoll; - return this; - } - @Override public void validate() throws TelegramApiValidationException { if (text == null || text.isEmpty()) { @@ -113,37 +84,4 @@ public class KeyboardButton implements Validable, BotApiObject { throw new TelegramApiValidationException("Cant request location and poll at the same time", this); } } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof KeyboardButton)) { - return false; - } - KeyboardButton keyboardButton = (KeyboardButton) o; - return Objects.equals(requestContact, keyboardButton.requestContact) - && Objects.equals(requestLocation, keyboardButton.requestLocation) - && Objects.equals(requestPoll, keyboardButton.requestPoll) - && Objects.equals(text, keyboardButton.text) - ; - } - - @Override - public int hashCode() { - return Objects.hash( - requestContact, - requestLocation, - requestPoll, - text); - } - - @Override - public String toString() { - return "KeyboardButton{" + - "text=" + text + - ", requestContact=" + requestContact + - ", requestLocation=" + requestLocation + - ", requestPoll=" + requestPoll + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButtonPollType.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButtonPollType.java index 5135e23e..65be7f2d 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButtonPollType.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardButtonPollType.java @@ -1,18 +1,30 @@ package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +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.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; -import java.util.Objects; - /** * @author Ruben Bermudez * @version 4.7 * * This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class KeyboardButtonPollType implements BotApiObject, Validable { private static final String TYPE_FIELD = "type"; @@ -26,45 +38,7 @@ public class KeyboardButtonPollType implements BotApiObject, Validable { @JsonProperty(TYPE_FIELD) private String type; - public KeyboardButtonPollType() { - } - - public KeyboardButtonPollType(String type) { - this.type = type; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - @Override public void validate() throws TelegramApiValidationException { - if (type == null || type.isEmpty()) { - throw new TelegramApiValidationException("Type parameter can't be empty", this); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof KeyboardButtonPollType)) return false; - KeyboardButtonPollType that = (KeyboardButtonPollType) o; - return Objects.equals(type, that.type); - } - - @Override - public int hashCode() { - return Objects.hash(type); - } - - @Override - public String toString() { - return "KeyboardButtonPollType{" + - "type='" + type + '\'' + - '}'; } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardRow.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardRow.java index b1b76ecb..b0e1b772 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardRow.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/replykeyboard/buttons/KeyboardRow.java @@ -9,8 +9,7 @@ import java.util.List; /** * @author Ruben Bermudez * @version 1.0 - * @brief Row for ReplyKeyBoardMarkup - * @date 10 of April of 2016 + * Row for ReplyKeyBoardMarkup */ public class KeyboardRow extends ArrayList implements Validable { public boolean add(String text) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java index b69d9cba..3a922ebc 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/MaskPosition.java @@ -2,6 +2,14 @@ package org.telegram.telegrambots.meta.api.objects.stickers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; +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.interfaces.BotApiObject; import org.telegram.telegrambots.meta.api.interfaces.Validable; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -12,6 +20,13 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; * This object describes the position on faces where a mask should be placed by default. */ @JsonTypeInfo(use=JsonTypeInfo.Id.NONE) +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor +@Builder public class MaskPosition implements Validable, BotApiObject { private static final String POINT_FIELD = "point"; private static final String XSHIFT_FIELD = "x_shift"; @@ -19,60 +34,18 @@ public class MaskPosition implements Validable, BotApiObject { private static final String SCALE_FIELD = "scale"; @JsonProperty(POINT_FIELD) + @NonNull private String point; ///< The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”. @JsonProperty(XSHIFT_FIELD) + @NonNull private Float xShift; ///< Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. @JsonProperty(YSHIFT_FIELD) + @NonNull private Float yShift; ///< Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. @JsonProperty(SCALE_FIELD) + @NonNull private Float scale; ///< Mask scaling coefficient. For example, 2.0 means double size. - public MaskPosition() { - super(); - } - - public String getPoint() { - return point; - } - - public Float getxShift() { - return xShift; - } - - public Float getyShift() { - return yShift; - } - - public Float getScale() { - return scale; - } - - public void setPoint(String point) { - this.point = point; - } - - public void setxShift(Float xShift) { - this.xShift = xShift; - } - - public void setyShift(Float yShift) { - this.yShift = yShift; - } - - public void setScale(Float scale) { - this.scale = scale; - } - - @Override - public String toString() { - return "MaskPosition{" + - "point='" + point + '\'' + - ", xShift=" + xShift + - ", yShift=" + yShift + - ", scale=" + scale + - '}'; - } - @Override public void validate() throws TelegramApiValidationException { if (point == null || point.isEmpty()) { diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/Sticker.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/Sticker.java index f0e21f1c..2dc8b003 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/Sticker.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/Sticker.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.stickers; 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.PhotoSize; @@ -9,6 +15,12 @@ import org.telegram.telegrambots.meta.api.objects.PhotoSize; * @version 1.0 * This object represents a sticker. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class Sticker implements BotApiObject { private static final String FILEID_FIELD = "file_id"; @@ -46,64 +58,4 @@ public class Sticker implements BotApiObject { private MaskPosition maskPosition; ///< Optional. For mask stickers, the position where the mask should be placed @JsonProperty(ISANIMATED_FIELD) private Boolean isAnimated; ///< True, if the sticker is animated - - public Sticker() { - super(); - } - - public String getFileId() { - return fileId; - } - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - public PhotoSize getThumb() { - return thumb; - } - - public Integer getFileSize() { - return fileSize; - } - - public String getEmoji() { - return emoji; - } - - public String getSetName() { - return setName; - } - - public MaskPosition getMaskPosition() { - return maskPosition; - } - - public Boolean getAnimated() { - return isAnimated; - } - - public String getFileUniqueId() { - return fileUniqueId; - } - - @Override - public String toString() { - return "Sticker{" + - "fileId='" + fileId + '\'' + - ", width=" + width + - ", height=" + height + - ", thumb=" + thumb + - ", fileSize=" + fileSize + - ", emoji='" + emoji + '\'' + - ", setName='" + setName + '\'' + - ", maskPosition=" + maskPosition + - ", isAnimated=" + isAnimated + - ", fileUniqueId=" + fileUniqueId + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/StickerSet.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/StickerSet.java index e9b34571..2f227f0b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/StickerSet.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/stickers/StickerSet.java @@ -1,6 +1,12 @@ package org.telegram.telegrambots.meta.api.objects.stickers; 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.PhotoSize; @@ -11,6 +17,12 @@ import java.util.List; * @version 1.0 * This object represents a sticker set. */ +@EqualsAndHashCode(callSuper = false) +@Getter +@Setter +@ToString +@NoArgsConstructor +@AllArgsConstructor public class StickerSet implements BotApiObject { private static final String NAME_FIELD = "name"; private static final String TITLE_FIELD = "title"; @@ -20,55 +32,15 @@ public class StickerSet implements BotApiObject { private static final String THUMB_FIELD = "thumb"; @JsonProperty(NAME_FIELD) - private String name; + private String name; ///< Sticker set name @JsonProperty(TITLE_FIELD) - private String title; + private String title; ///< Sticker set title @JsonProperty(CONTAINSMASKS_FIELD) - private Boolean containsMasks; + private Boolean containsMasks; ///< True, if the sticker set contains animated stickers @JsonProperty(STICKERS_FIELD) - private List stickers; + private List stickers; ///< True, if the sticker set contains masks @JsonProperty(ISANIMATED_FIELD) - private Boolean isAnimated; + private Boolean isAnimated; ///< List of all set stickers @JsonProperty(THUMB_FIELD) private PhotoSize thumb; ///< Optional. Sticker set thumbnail in the .WEBP or .TGS format - - public StickerSet() { - super(); - } - - public String getName() { - return name; - } - - public String getTitle() { - return title; - } - - public Boolean getContainsMasks() { - return containsMasks; - } - - public List getStickers() { - return stickers; - } - - public Boolean getAnimated() { - return isAnimated; - } - - public PhotoSize getThumb() { - return thumb; - } - - @Override - public String toString() { - return "StickerSet{" + - "name='" + name + '\'' + - ", title='" + title + '\'' + - ", containsMasks=" + containsMasks + - ", stickers=" + stickers + - ", isAnimated=" + isAnimated + - ", thumb=" + thumb + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java index dd41bd94..204bb1fa 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java @@ -162,7 +162,7 @@ public abstract class AbsSender { /** * Edit media in a message * @param editMessageMedia Information of the new media - * @return If the edited message was sent by the bot, the edited Message is returned, otherwise True is returned + * @return If the edited message is not an inline message, the edited Message is returned, otherwise True is returned * @throws TelegramApiException If there is any error editing the media */ public abstract Serializable execute(EditMessageMedia editMessageMedia) throws TelegramApiException; 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 696a7268..123099b4 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 @@ -1,14 +1,15 @@ package org.telegram.telegrambots.meta.generics; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; /** * @author Ruben Bermudez * @version 1.0 - * @brief Callback to handle updates. - * @date 20 of June of 2015 + * Callback to handle updates. */ public interface WebhookBot extends TelegramBot { /** @@ -19,11 +20,9 @@ public interface WebhookBot extends TelegramBot { /** * Execute setWebhook method to set up the url of the webhook - * @param url Url for the webhook - * @param publicCertificatePath Path to the public key certificate of the webhook * @throws TelegramApiRequestException In case of error executing the request */ - void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException; + void setWebhook(SetWebhook setWebhook) throws TelegramApiException; /** * Gets in the url for the webhook diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/api/methods/send/SendMessageTest.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/api/methods/send/SendMessageTest.java index f6dc3a7f..0b03b425 100644 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/api/methods/send/SendMessageTest.java +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/api/methods/send/SendMessageTest.java @@ -9,17 +9,28 @@ class SendMessageTest { @Test void comparison() { - SendMessage sm1 = new SendMessage().setChatId(1L).setText("Hello World"); - SendMessage sm2 = new SendMessage().setChatId(1L).setText("Hello World"); - SendMessage noMessage = new SendMessage().setChatId(1L); - SendMessage disabledNotification = new SendMessage().setChatId(1L).setText("Hello World").disableNotification(); + SendMessage sm1 = SendMessage + .builder() + .chatId("1") + .text("Hello World") + .build(); + SendMessage sm2 = SendMessage + .builder() + .chatId("1") + .text("Hello World") + .build(); + SendMessage disabledNotification = SendMessage + .builder() + .chatId("1") + .text("Hello World") + .disableNotification(true) + .build(); + sm1.equals(sm2); assertEquals(sm1, sm2); - assertNotEquals(sm1, noMessage); assertNotEquals(sm1, disabledNotification); assertEquals(sm1.hashCode(), sm2.hashCode()); - assertNotEquals(sm1.hashCode(), noMessage.hashCode()); assertNotEquals(sm1.hashCode(), disabledNotification.hashCode()); } 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 9f9a3c6f..41b14334 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,9 +1,11 @@ package org.telegram.telegrambots.meta.test; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.Audio; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; @@ -39,6 +41,116 @@ class TestDeserialization { mapper = new ObjectMapper(); } + @Test + void TestListUpdates() throws Exception { + String updateText = "{\"ok\":true,\"result\":[{\"update_id\":79995144,\n" + + "\"message\":{\"message_id\":90,\"from\":{\"id\":1234567,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"en\"},\"chat\":{\"id\":1234567,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154223,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":79995145,\n" + + "\"message\":{\"message_id\":91,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154306,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":79995146,\n" + + "\"message\":{\"message_id\":92,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154313,\"text\":\"/test\",\"entities\":[{\"offset\":0,\"length\":5,\"type\":\"bot_command\"}]}},{\"update_id\":79995147,\n" + + "\"message\":{\"message_id\":93,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154318,\"text\":\"@aaaa\"}},{\"update_id\":79995148,\n" + + "\"message\":{\"message_id\":94,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154326,\"game\":{\"title\":\"Brick Stacker\",\"description\":\"Play the game to see how many bricks you can stack, and contribute to the tower!\",\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":12663,\"width\":320,\"height\":180},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":35050,\"width\":640,\"height\":360}],\"animation\":{\"file_name\":\"video.mp4\",\"mime_type\":\"video/mp4\",\"duration\":6,\"width\":320,\"height\":180,\"thumb\":{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":6209,\"width\":320,\"height\":180},\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":411406}},\"reply_markup\":{\"inline_keyboard\":[[{\"text\":\"Play Brick Stacker!\",\"callback_game\":{}}]]},\"via_bot\":{\"id\":280713127,\"is_bot\":true,\"first_name\":\"Gamee\",\"username\":\"gamee\"}}},{\"update_id\":79995149,\n" + + "\"message\":{\"message_id\":95,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154339,\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":8291,\"width\":320,\"height\":180},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":25998,\"width\":800,\"height\":450},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":38407,\"width\":1200,\"height\":675}],\"via_bot\":{\"id\":114528005,\"is_bot\":true,\"first_name\":\"Yandex Image Search\",\"username\":\"pic\"}}},{\"update_id\":79995150,\n" + + "\"message\":{\"message_id\":96,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154347,\"location\":{\"latitude\":34.76437,\"longitude\":0.001983}}},{\"update_id\":79995151,\n" + + "\"message\":{\"message_id\":97,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154360,\"video_note\":{\"duration\":3,\"length\":240,\"thumb\":{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":6852,\"width\":240,\"height\":240},\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":100544}}},{\"update_id\":79995152,\n" + + "\"message\":{\"message_id\":98,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154363,\"voice\":{\"duration\":1,\"mime_type\":\"audio/ogg\",\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":5198}}},{\"update_id\":79995153,\n" + + "\"message\":{\"message_id\":99,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154371,\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":14395,\"width\":180,\"height\":320},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":52852,\"width\":450,\"height\":800},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":84493,\"width\":720,\"height\":1280}]}},{\"update_id\":79995154,\n" + + "\"message\":{\"message_id\":6,\"from\":{\"id\":1234567,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"en\"},\"chat\":{\"id\":-110011556359722345678,\"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); + + 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); + } + } + + @Test + void TestListUpdates2() throws Exception { + String updateText = "{\"ok\":true,\"result\":[{\"update_id\":259894298,\n" + + "\"message\":{\"message_id\":101,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\"},\"chat\":{\"id\":12345678,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"type\":\"private\"},\"date\":1604171814,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":259894299,\n" + + "\"message\":{\"message_id\":102,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"language_code\":\"en\"},\"chat\":{\"id\":12345678,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"type\":\"private\"},\"date\":1604188661,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":259894300,\n" + + "\"message\":{\"message_id\":103,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"language_code\":\"en\"},\"chat\":{\"id\":12345678,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"type\":\"private\"},\"date\":1604188669,\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":18933,\"width\":180,\"height\":320},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":80310,\"width\":450,\"height\":800},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":114661,\"width\":720,\"height\":1280}]}},{\"update_id\":259894301,\n" + + "\"message\":{\"message_id\":104,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"language_code\":\"en\"},\"chat\":{\"id\":12345678,\"first_name\":\"FistName\",\"last_name\":\"LastName\",\"username\":\"username\",\"type\":\"private\"},\"date\":1604188673,\"voice\":{\"duration\":1,\"mime_type\":\"audio/ogg\",\"file_id\":\"FILEID\",\"file_unique_id\":\"AgADFQADqRjwTA\",\"file_size\":8386}}},{\"update_id\":259894302,\n" + + "\"message\":{\"message_id\":105,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"Username\"},\"chat\":{\"id\":12345678,\"first_name\":\"FirstName\",\"username\":\"Username\",\"type\":\"private\"},\"date\":1604226451,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":259894303,\n" + + "\"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); + + 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); + } + } + + @Test + void TestListUpdates3() throws Exception { + String updateText = "{\"ok\":true,\"result\":[{\"update_id\":259894302,\n" + + "\"message\":{\"message_id\":105,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"Username\"},\"chat\":{\"id\":12345678,\"first_name\":\"FirstName\",\"username\":\"Username\",\"type\":\"private\"},\"date\":1604226451,\"text\":\"/start\",\"entities\":[{\"offset\":0,\"length\":6,\"type\":\"bot_command\"}]}},{\"update_id\":259894303,\n" + + "\"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}}},{\"update_id\":259894304,\n" + + "\"message\":{\"message_id\":107,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"group\",\"all_members_are_administrators\":true},\"date\":1604281682,\"new_chat_members\":[{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing Telegram Bots\",\"username\":\"TestingRanBot\"}]}},{\"update_id\":259894305,\n" + + "\"message\":{\"message_id\":108,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"group\",\"all_members_are_administrators\":true},\"date\":1604281713,\"left_chat_member\":{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing Telegram Bots\",\"username\":\"TestingRanBot\"}}},{\"update_id\":259894306,\n" + + "\"message\":{\"message_id\":109,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"group\",\"all_members_are_administrators\":true},\"date\":1604281720,\"new_chat_members\":[{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing Telegram Bots\",\"username\":\"TestingRanBot\"}]}},{\"update_id\":259894307,\n" + + "\"message\":{\"message_id\":110,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"FirstName\",\"username\":\"FirstName\",\"language_code\":\"en\"},\"chat\":{\"id\":-10011869112345,\"title\":\"My new test group\",\"type\":\"group\",\"all_members_are_administrators\":false},\"date\":1604281763,\"migrate_to_chat_id\":-10011869112345}},{\"update_id\":259894308,\n" + + "\"message\":{\"message_id\":1,\"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\":1604281763,\"migrate_from_chat_id\":-10011869112345}},{\"update_id\":259894309,\n" + + "\"message\":{\"message_id\":2,\"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\":1604281985,\"sticker\":{\"width\":512,\"height\":512,\"emoji\":\"\\ud83e\\udd2c\",\"set_name\":\"ShadowKitty\",\"is_animated\":true,\"thumb\":{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":7546,\"width\":128,\"height\":128},\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":13187}}},{\"update_id\":259894310,\n" + + "\"message\":{\"message_id\":3,\"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\":1604281993,\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"AQADL3I6J10AAzbcAQAB\",\"file_size\":15207,\"width\":148,\"height\":320},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":64579,\"width\":369,\"height\":800},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":93424,\"width\":591,\"height\":1280}]}},{\"update_id\":259894311,\n" + + "\"message\":{\"message_id\":4,\"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\":1604282015,\"poll\":{\"id\":\"5834976086823272454\",\"question\":\"My test poll\",\"options\":[{\"text\":\"No option\",\"voter_count\":0},{\"text\":\"Yes option\",\"voter_count\":0}],\"total_voter_count\":0,\"is_closed\":false,\"is_anonymous\":true,\"type\":\"quiz\",\"allows_multiple_answers\":false}}},{\"update_id\":259894312,\n" + + "\"message\":{\"message_id\":5,\"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\":1604282029,\"contact\":{\"phone_number\":\"618490765\",\"first_name\":\"FirstName\",\"last_name\":\"LASNAME\",\"vcard\":\"BEGIN:VCARD \\nVERSION:3.0\"}}},{\"update_id\":259894313,\n" + + "\"message\":{\"message_id\":6,\"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\":1604282057,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822}}},{\"update_id\":259894314,\n" + + "\"message\":{\"message_id\":7,\"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\":1604282070,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800}}},{\"update_id\":259894315,\n" + + "\"edited_message\":{\"message_id\":7,\"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\":1604282070,\"edit_date\":1604282070,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894316,\n" + + "\"edited_message\":{\"message_id\":7,\"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\":1604282070,\"edit_date\":1604282074,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":28800,\"heading\":102,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894317,\n" + + "\"edited_message\":{\"message_id\":7,\"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\":1604282070,\"edit_date\":1604282077,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822}}},{\"update_id\":259894318,\n" + + "\"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,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800}}},{\"update_id\":259894319,\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\":1604282102,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":111,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894320,\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\":1604282106,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":105,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894321,\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\":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" + + "\"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\":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\":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" + + "\"message\":{\"message_id\":11,\"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\":1604282147,\"text\":\"Hello\"}},{\"update_id\":259894336,\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\":1604282148,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":98,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894337,\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\":1604282152,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":111,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894338,\n" + + "\"edited_message\":{\"message_id\":11,\"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\":1604282147,\"edit_date\":1604282153,\"text\":\"Hello, modified\"}},{\"update_id\":259894339,\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\":1604282156,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":112,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894340,\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\":1604282160,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":111,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894341,\n" + + "\"message\":{\"message_id\":12,\"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\":1604282163,\"reply_to_message\":{\"message_id\":11,\"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\":1604282147,\"edit_date\":1604282153,\"text\":\"Hello, modified\"},\"text\":\"And the answer\"}},{\"update_id\":259894342,\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\":1604282194,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":80,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894343,\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\":1604282198,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":63,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894344,\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\":1604282206,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":64,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894345,\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\":1604282214,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":140,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894346,\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\":1604282218,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":84,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894347,\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\":1604282230,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":85,\"horizontal_accuracy\":65.000000}}},{\"update_id\":259894348,\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\":1604282234,\"location\":{\"latitude\":0.004822,\"longitude\":-0.004822,\"live_period\":1800,\"heading\":85,\"horizontal_accuracy\":65.000000}}}]}"; + + + ArrayList response = new GetUpdates().deserializeResponse(updateText); + + 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); + } + } + @Test void TestUpdateDeserialization() throws Exception { Update update = mapper.readValue(TelegramBotsHelper.GetUpdate(), Update.class); diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestSerialization.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestSerialization.java new file mode 100644 index 00000000..e30a6b7a --- /dev/null +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestSerialization.java @@ -0,0 +1,79 @@ +package org.telegram.telegrambots.meta.test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery; +import org.telegram.telegrambots.meta.api.methods.send.SendLocation; +import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputLocationMessageContent; +import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResultArticle; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +public class TestSerialization { + private ObjectMapper mapper; + + @BeforeEach + void setUp() { + mapper = new ObjectMapper(); + } + + @Test + void testSendLocation() throws JsonProcessingException { + SendLocation location = SendLocation.builder() + .chatId("12345") + .latitude(20.758069) + .longitude(-0.005702) + .horizontalAccuracy(65.00000) + .disableNotification(true) + .replyToMessageId(1) + .livePeriod(100) + .allowSendingWithoutReply(true) + .heading(125) + .approachingNotificationDistance(100) + .build(); + + String json = mapper.writeValueAsString(location); + + assertNotNull(json); + assertEquals("{\"chat_id\":\"12345\",\"latitude\":20.758069,\"longitude\":-0.005702,\"disable_notification\":true,\"reply_to_message_id\":1,\"live_period\":100,\"allow_sending_without_reply\":true,\"horizontal_accuracy\":65.0,\"heading\":125,\"approaching_notification_distance\":100,\"method\":\"sendlocation\"}", + json); + } + + @Test + void testAnswerInlineLocation() throws JsonProcessingException { + AnswerInlineQuery inlineQuery = AnswerInlineQuery + .builder() + .inlineQueryId("12345") + .cacheTime(1) + .isPersonal(true) + .nextOffset("2") + .switchPmText("switch") + .switchPmParameter("parameter") + .result(InlineQueryResultArticle + .builder() + .id("1") + .title("Title") + .inputMessageContent(InputLocationMessageContent + .builder() + .latitude(20.758069) + .longitude(-0.005702) + .horizontalAccuracy(65.00000) + .build() + ) + .build()) + .build(); + + String json = mapper.writeValueAsString(inlineQuery); + + assertNotNull(json); + assertEquals("{\"inline_query_id\":\"12345\",\"results\":[{\"type\":\"article\",\"id\":\"1\",\"title\":\"Title\",\"input_message_content\":{\"latitude\":20.758069,\"longitude\":-0.005702,\"horizontal_accuracy\":65.0}}],\"cache_time\":1,\"is_personal\":true,\"next_offset\":\"2\",\"switch_pm_text\":\"switch\",\"switch_pm_parameter\":\"parameter\",\"method\":\"answerInlineQuery\"}", + json); + } +} diff --git a/telegrambots-spring-boot-starter/README.md b/telegrambots-spring-boot-starter/README.md index 422e3380..9644e564 100644 --- a/telegrambots-spring-boot-starter/README.md +++ b/telegrambots-spring-boot-starter/README.md @@ -18,14 +18,14 @@ Usage org.telegram telegrambots-spring-boot-starter - 4.9.2 + 5.0.0 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-spring-boot-starter:4.9.2" + compile "org.telegram:telegrambots-spring-boot-starter:5.0.0" ``` Motivation diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index aeb03f45..08f21a38 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambots-spring-boot-starter @@ -70,9 +70,9 @@ UTF-8 UTF-8 - 4.9.2 - 2.3.3.RELEASE - 3.14.0 + 5.0.0 + 2.3.5.RELEASE + 3.18.0 1.6 1.6.8 diff --git a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java new file mode 100644 index 00000000..a3a7c624 --- /dev/null +++ b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java @@ -0,0 +1,27 @@ +package org.telegram.telegrambots.starter; + +import org.telegram.telegrambots.bots.DefaultBotOptions; +import org.telegram.telegrambots.bots.TelegramWebhookBot; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; + +/** + * @author Ruben Bermudez + * @version 1.0 + */ +public abstract class SpringWebhookBot extends TelegramWebhookBot { + private SetWebhook setWebhook; + + public SpringWebhookBot(SetWebhook setWebhook) { + super(); + this.setWebhook = setWebhook; + } + + public SpringWebhookBot(DefaultBotOptions options, SetWebhook setWebhook) { + super(options); + this.setWebhook = setWebhook; + } + + public SetWebhook getSetWebhook() { + return setWebhook; + } +} 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 3c8168a6..92540ecf 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 @@ -9,7 +9,6 @@ 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; -import org.telegram.telegrambots.meta.generics.WebhookBot; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -27,11 +26,11 @@ public class TelegramBotInitializer implements InitializingBean { private final TelegramBotsApi telegramBotsApi; private final List longPollingBots; - private final List webHookBots; + private final List webHookBots; public TelegramBotInitializer(TelegramBotsApi telegramBotsApi, List longPollingBots, - List webHookBots) { + List webHookBots) { Objects.requireNonNull(telegramBotsApi); Objects.requireNonNull(longPollingBots); Objects.requireNonNull(webHookBots); @@ -47,8 +46,8 @@ public class TelegramBotInitializer implements InitializingBean { BotSession session = telegramBotsApi.registerBot(bot); handleAfterRegistrationHook(bot, session); } - for (WebhookBot bot : webHookBots) { - telegramBotsApi.registerBot(bot); + for (SpringWebhookBot bot : webHookBots) { + telegramBotsApi.registerBot(bot, bot.getSetWebhook()); } } catch (TelegramApiException e) { throw new RuntimeException(e); diff --git a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java index 6aea31d0..c47dcdbf 100644 --- a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java +++ b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java @@ -1,9 +1,5 @@ package org.telegram.telegrambots.starter; -import java.util.Collections; -import java.util.List; - - import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -11,7 +7,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.generics.LongPollingBot; -import org.telegram.telegrambots.meta.generics.WebhookBot; + +import java.util.Collections; +import java.util.List; /** * #TelegramBotsApi added to spring context as well */ @@ -29,7 +27,7 @@ public class TelegramBotStarterConfiguration { @ConditionalOnMissingBean public TelegramBotInitializer telegramBotInitializer(TelegramBotsApi telegramBotsApi, ObjectProvider> longPollingBots, - ObjectProvider> webHookBots) { + ObjectProvider> webHookBots) { return new TelegramBotInitializer(telegramBotsApi, longPollingBots.getIfAvailable(Collections::emptyList), webHookBots.getIfAvailable(Collections::emptyList)); diff --git a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java index 09cbec19..16a94b5d 100644 --- a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java +++ b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterConfiguration.java @@ -6,11 +6,15 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.generics.LongPollingBot; -import org.telegram.telegrambots.meta.generics.WebhookBot; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; class TestTelegramBotStarterConfiguration { @@ -25,7 +29,7 @@ class TestTelegramBotStarterConfiguration { assertThat(context).hasSingleBean(TelegramBotsApi.class); assertThat(context).hasSingleBean(TelegramBotInitializer.class); assertThat(context).doesNotHaveBean(LongPollingBot.class); - assertThat(context).doesNotHaveBean(WebhookBot.class); + assertThat(context).doesNotHaveBean(SpringWebhookBot.class); verifyNoMoreInteractions(context.getBean(TelegramBotsApi.class)); }); } @@ -35,7 +39,7 @@ class TestTelegramBotStarterConfiguration { this.contextRunner.withUserConfiguration(LongPollingBotConfig.class) .run((context) -> { assertThat(context).hasSingleBean(LongPollingBot.class); - assertThat(context).doesNotHaveBean(WebhookBot.class); + assertThat(context).doesNotHaveBean(SpringWebhookBot.class); TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); @@ -49,13 +53,13 @@ class TestTelegramBotStarterConfiguration { void createOnlyWebhookBot() { this.contextRunner.withUserConfiguration(WebhookBotConfig.class) .run((context) -> { - assertThat(context).hasSingleBean(WebhookBot.class); + assertThat(context).hasSingleBean(SpringWebhookBot.class); assertThat(context).doesNotHaveBean(LongPollingBot.class); TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); verify(telegramBotsApi, - times(1)).registerBot(context.getBean(WebhookBot.class)); + times(1)).registerBot(context.getBean(SpringWebhookBot.class), context.getBean(SpringWebhookBot.class).getSetWebhook()); verifyNoMoreInteractions(telegramBotsApi); }); } @@ -66,14 +70,14 @@ class TestTelegramBotStarterConfiguration { WebhookBotConfig.class) .run((context) -> { assertThat(context).hasSingleBean(LongPollingBot.class); - assertThat(context).hasSingleBean(WebhookBot.class); + assertThat(context).hasSingleBean(SpringWebhookBot.class); TelegramBotsApi telegramBotsApi = context.getBean(TelegramBotsApi.class); verify(telegramBotsApi, times(1)).registerBot(context.getBean(LongPollingBot.class)); verify(telegramBotsApi, - times(1)).registerBot(context.getBean(WebhookBot.class)); + times(1)).registerBot(context.getBean(SpringWebhookBot.class), context.getBean(SpringWebhookBot.class).getSetWebhook()); //verifyNoMoreInteractions(telegramBotsApi); }); } @@ -98,8 +102,15 @@ class TestTelegramBotStarterConfiguration { @Configuration static class WebhookBotConfig { @Bean - public WebhookBot webhookBot() { - return mock(WebhookBot.class); + public SpringWebhookBot webhookBot(SetWebhook setWebhook) { + SpringWebhookBot bot = mock(SpringWebhookBot.class); + doReturn(setWebhook).when(bot).getSetWebhook(); + return bot; + } + + @Bean + public SetWebhook setWebhook() { + return mock(SetWebhook.class); } } } diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 83779007..1cf9e4bf 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 4.9.2 + 5.0.0 telegrambots @@ -70,13 +70,13 @@ UTF-8 UTF-8 - 2.29.1 + 2.32 1.19.3 - 4.5.10 + 4.5.13 20180813 - 2.10.1 - 2.10.1 - 2.6 + 2.11.3 + 2.11.3 + 2.8.0 @@ -95,7 +95,7 @@ org.telegram telegrambots-meta - 4.9.2 + 5.0.0 com.fasterxml.jackson.core @@ -110,7 +110,7 @@ com.fasterxml.jackson.module jackson-module-jaxb-annotations - 2.10.1 + ${jackson.version} com.fasterxml.jackson.core @@ -146,6 +146,12 @@ org.glassfish.jersey.core jersey-server ${glassfish.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + + org.json diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java index aab32d63..97b3c065 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java @@ -33,6 +33,7 @@ import org.telegram.telegrambots.meta.api.objects.File; import org.telegram.telegrambots.meta.api.objects.InputFile; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.media.InputMedia; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaAnimation; import org.telegram.telegrambots.meta.api.objects.media.InputMediaAudio; import org.telegram.telegrambots.meta.api.objects.media.InputMediaDocument; import org.telegram.telegrambots.meta.api.objects.media.InputMediaVideo; @@ -185,6 +186,13 @@ public abstract class DefaultAbsSender extends AbsSender { builder.addTextBody(SendDocument.DISABLENOTIFICATION_FIELD, sendDocument.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendDocument.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendDocument.ALLOWSENDINGWITHOUTREPLY_FIELD, sendDocument.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendDocument.getCaptionEntities() != null) { + builder.addTextBody(SendDocument.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendDocument.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendDocument.getThumb() != null) { addInputFile(builder, sendDocument.getThumb(), SendDocument.THUMB_FIELD, false); builder.addTextBody(SendDocument.THUMB_FIELD, sendDocument.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE); @@ -229,6 +237,12 @@ public abstract class DefaultAbsSender extends AbsSender { if (sendPhoto.getDisableNotification() != null) { builder.addTextBody(SendPhoto.DISABLENOTIFICATION_FIELD, sendPhoto.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendPhoto.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendPhoto.ALLOWSENDINGWITHOUTREPLY_FIELD, sendPhoto.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendPhoto.getCaptionEntities() != null) { + builder.addTextBody(SendPhoto.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendPhoto.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -284,6 +298,12 @@ public abstract class DefaultAbsSender extends AbsSender { addInputFile(builder, sendVideo.getThumb(), SendVideo.THUMB_FIELD, false); builder.addTextBody(SendVideo.THUMB_FIELD, sendVideo.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendVideo.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendVideo.ALLOWSENDINGWITHOUTREPLY_FIELD, sendVideo.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendVideo.getCaptionEntities() != null) { + builder.addTextBody(SendVideo.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendVideo.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -328,6 +348,9 @@ public abstract class DefaultAbsSender extends AbsSender { addInputFile(builder, sendVideoNote.getThumb(), SendVideoNote.THUMB_FIELD, false); builder.addTextBody(SendVideoNote.THUMB_FIELD, sendVideoNote.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendVideoNote.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendVideoNote.ALLOWSENDINGWITHOUTREPLY_FIELD, sendVideoNote.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -362,6 +385,9 @@ public abstract class DefaultAbsSender extends AbsSender { if (sendSticker.getDisableNotification() != null) { builder.addTextBody(SendSticker.DISABLENOTIFICATION_FIELD, sendSticker.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendSticker.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendSticker.ALLOWSENDINGWITHOUTREPLY_FIELD, sendSticker.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -418,6 +444,12 @@ public abstract class DefaultAbsSender extends AbsSender { addInputFile(builder, sendAudio.getThumb(), SendAudio.THUMB_FIELD, false); builder.addTextBody(SendAudio.THUMB_FIELD, sendAudio.getThumb().getAttachName(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendAudio.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendAudio.ALLOWSENDINGWITHOUTREPLY_FIELD, sendAudio.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendAudio.getCaptionEntities() != null) { + builder.addTextBody(SendAudio.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendAudio.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -467,6 +499,12 @@ public abstract class DefaultAbsSender extends AbsSender { builder.addTextBody(SendVoice.PARSEMODE_FIELD, sendVoice.getParseMode(), TEXT_PLAIN_CONTENT_TYPE); } } + if (sendVoice.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendVoice.ALLOWSENDINGWITHOUTREPLY_FIELD, sendVoice.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendVoice.getCaptionEntities() != null) { + builder.addTextBody(SendVoice.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendVoice.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -490,9 +528,12 @@ public abstract class DefaultAbsSender extends AbsSender { builder.setCharset(StandardCharsets.UTF_8); builder.addTextBody(SetChatPhoto.CHATID_FIELD, setChatPhoto.getChatId(), TEXT_PLAIN_CONTENT_TYPE); if (setChatPhoto.getPhoto() != null) { - builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, setChatPhoto.getPhoto()); - } else if (setChatPhoto.getPhotoStream() != null) { - builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, setChatPhoto.getPhotoStream(), ContentType.APPLICATION_OCTET_STREAM, setChatPhoto.getPhotoName()); + InputFile photo = setChatPhoto.getPhoto(); + if (photo.getNewMediaFile() != null) { + builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, photo.getNewMediaFile()); + } else if (photo.getNewMediaStream() != null) { + builder.addBinaryBody(SetChatPhoto.PHOTO_FIELD, photo.getNewMediaStream(), ContentType.APPLICATION_OCTET_STREAM, photo.getMediaName()); + } } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -516,7 +557,7 @@ public abstract class DefaultAbsSender extends AbsSender { builder.setLaxMode(); builder.setCharset(StandardCharsets.UTF_8); builder.addTextBody(SendMediaGroup.CHATID_FIELD, sendMediaGroup.getChatId(), TEXT_PLAIN_CONTENT_TYPE); - addInputData(builder, sendMediaGroup.getMedia(), SendMediaGroup.MEDIA_FIELD); + addInputData(builder, sendMediaGroup.getMedias(), SendMediaGroup.MEDIA_FIELD); if (sendMediaGroup.getDisableNotification() != null) { builder.addTextBody(SendMediaGroup.DISABLENOTIFICATION_FIELD, sendMediaGroup.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE); @@ -525,6 +566,9 @@ public abstract class DefaultAbsSender extends AbsSender { if (sendMediaGroup.getReplyToMessageId() != null) { builder.addTextBody(SendMediaGroup.REPLYTOMESSAGEID_FIELD, sendMediaGroup.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE); } + if (sendMediaGroup.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendMediaGroup.ALLOWSENDINGWITHOUTREPLY_FIELD, sendMediaGroup.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); @@ -717,6 +761,12 @@ public abstract class DefaultAbsSender extends AbsSender { builder.addTextBody(SendAnimation.PARSEMODE_FIELD, sendAnimation.getParseMode(), TEXT_PLAIN_CONTENT_TYPE); } } + if (sendAnimation.getAllowSendingWithoutReply() != null) { + builder.addTextBody(SendAnimation.ALLOWSENDINGWITHOUTREPLY_FIELD, sendAnimation.getAllowSendingWithoutReply().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (sendAnimation.getCaptionEntities() != null) { + builder.addTextBody(SendAnimation.CAPTION_ENTITIES_FIELD, objectMapper.writeValueAsString(sendAnimation.getCaptionEntities()), TEXT_PLAIN_CONTENT_TYPE); + } HttpEntity multipart = builder.build(); httppost.setEntity(multipart); @@ -782,8 +832,8 @@ public abstract class DefaultAbsSender extends AbsSender { private void addInputData(MultipartEntityBuilder builder, InputMedia media, String mediaField, boolean addField) throws JsonProcessingException { if (media.isNewMedia()) { - if (media.getMediaFile() != null) { - builder.addBinaryBody(media.getMediaName(), media.getMediaFile(), ContentType.APPLICATION_OCTET_STREAM, media.getMediaName()); + if (media.getNewMediaFile() != null) { + builder.addBinaryBody(media.getMediaName(), media.getNewMediaFile(), ContentType.APPLICATION_OCTET_STREAM, media.getMediaName()); } else if (media.getNewMediaStream() != null) { builder.addBinaryBody(media.getMediaName(), media.getNewMediaStream(), ContentType.APPLICATION_OCTET_STREAM, media.getMediaName()); } @@ -804,6 +854,11 @@ public abstract class DefaultAbsSender extends AbsSender { if (video.getThumb() != null) { addInputFile(builder, video.getThumb(), InputMediaVideo.THUMB_FIELD, false); } + } else if (media instanceof InputMediaAnimation) { + InputMediaAnimation animation = (InputMediaAnimation) media; + if (animation.getThumb() != null) { + addInputFile(builder, animation.getThumb(), InputMediaAnimation.THUMB_FIELD, false); + } } if (addField) { 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 05032668..4a9e702c 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -1,7 +1,8 @@ package org.telegram.telegrambots.bots; import org.telegram.telegrambots.meta.ApiContext; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.WebhookBot; import org.telegram.telegrambots.util.WebhookUtils; @@ -22,7 +23,7 @@ public abstract class TelegramWebhookBot extends DefaultAbsSender implements Web } @Override - public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { - WebhookUtils.setWebhook(this, url, publicCertificatePath); + public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { + WebhookUtils.setWebhook(this, setWebhook); } } \ No newline at end of file diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index 804181c0..4ce3b853 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -10,11 +10,10 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; -import org.telegram.telegrambots.bots.DefaultBotOptions; -import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.telegram.telegrambots.meta.ApiConstants; +import org.telegram.telegrambots.bots.DefaultBotOptions; +import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder; import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; @@ -235,10 +234,12 @@ public class DefaultBotSession implements BotSession { } private List getUpdatesFromServer() throws IOException { - GetUpdates request = new GetUpdates() - .setLimit(options.getGetUpdatesLimit()) - .setTimeout(options.getGetUpdatesTimeout()) - .setOffset(lastReceivedUpdate + 1); + GetUpdates request = GetUpdates + .builder() + .limit(options.getGetUpdatesLimit()) + .timeout(options.getGetUpdatesTimeout()) + .offset(lastReceivedUpdate + 1) + .build(); if (options.getAllowedUpdates() != null) { request.setAllowedUpdates(options.getAllowedUpdates()); 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 5210cd6c..91a15cc3 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/util/WebhookUtils.java @@ -17,6 +17,7 @@ import org.telegram.telegrambots.facilities.TelegramHttpClientBuilder; import org.telegram.telegrambots.meta.ApiConstants; import org.telegram.telegrambots.meta.api.methods.updates.DeleteWebhook; 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; @@ -27,10 +28,81 @@ import java.nio.charset.StandardCharsets; import static org.telegram.telegrambots.Constants.SOCKET_TIMEOUT; public final class WebhookUtils { + private static final ContentType TEXT_PLAIN_CONTENT_TYPE = ContentType.create("text/plain", StandardCharsets.UTF_8); + private WebhookUtils() { } + /** + * Set webhook address to receive updates + * @param bot Bot to set the webhook to + * @param setWebhook SetSebhook object with webhook information + * @throws TelegramApiRequestException If any issue executing the request + * + * @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 { + setWebhook.validate(); + + DefaultBotOptions botOptions = bot.getOptions(); + try (CloseableHttpClient httpclient = TelegramHttpClientBuilder.build(botOptions)) { + String requestUrl = bot.getBaseUrl() + SetWebhook.PATH; + + RequestConfig requestConfig = botOptions.getRequestConfig(); + if (requestConfig == null) { + requestConfig = RequestConfig.copy(RequestConfig.custom().build()) + .setSocketTimeout(SOCKET_TIMEOUT) + .setConnectTimeout(SOCKET_TIMEOUT) + .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); + } + + HttpPost httppost = new HttpPost(requestUrl); + httppost.setConfig(requestConfig); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.addTextBody(SetWebhook.URL_FIELD, setWebhook.getUrl(), TEXT_PLAIN_CONTENT_TYPE); + if (setWebhook.getMaxConnections() != null) { + builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, setWebhook.getMaxConnections().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (setWebhook.getAllowedUpdates() != null) { + builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(setWebhook.getAllowedUpdates()).toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (setWebhook.getIpAddress() != null) { + builder.addTextBody(SetWebhook.IPADDRESS_FIELD, setWebhook.getIpAddress(), TEXT_PLAIN_CONTENT_TYPE); + } + if (setWebhook.getDropPendingUpdates() != null) { + builder.addTextBody(SetWebhook.DROPPENDINGUPDATES_FIELD, setWebhook.getDropPendingUpdates().toString(), TEXT_PLAIN_CONTENT_TYPE); + } + if (setWebhook.getCertificate() != null) { + InputFile webhookFile = setWebhook.getCertificate(); + if (webhookFile.getNewMediaFile() != null) { + builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, webhookFile.getNewMediaFile(), ContentType.TEXT_PLAIN, webhookFile.getMediaName()); + } else if (webhookFile.getNewMediaStream() != null) { + builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, webhookFile.getNewMediaStream(), ContentType.TEXT_PLAIN, webhookFile.getMediaName()); + } + } + + HttpEntity multipart = builder.build(); + httppost.setEntity(multipart); + try (CloseableHttpResponse response = httpclient.execute(httppost, botOptions.getHttpContext())) { + String responseContent = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + Boolean result = setWebhook.deserializeResponse(responseContent); + if (!result) { + throw new TelegramApiRequestException("Error setting webhook:" + responseContent); + } + } + } catch (JSONException e) { + throw new TelegramApiRequestException("Error deserializing setWebhook method response", e); + } catch (IOException e) { + throw new TelegramApiRequestException("Error executing setWebook method", e); + } + } + + /** + * @deprecated Use {{@link #setWebhook(DefaultAbsSender, SetWebhook)}} instead + */ + @Deprecated public static void setWebhook(DefaultAbsSender bot, String url, String publicCertificatePath) throws TelegramApiRequestException { DefaultBotOptions botOptions = bot.getOptions(); @@ -55,6 +127,9 @@ public final class WebhookUtils { if (botOptions.getAllowedUpdates() != null) { builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getAllowedUpdates()).toString()); } + if (botOptions.getAllowedUpdates() != null) { + builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getAllowedUpdates()).toString()); + } if (publicCertificatePath != null) { File certificate = new File(publicCertificatePath); if (certificate.exists()) { 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 9ac70c3f..5034326e 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/BotApiMethodHelperFactory.java @@ -53,6 +53,7 @@ import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.Keyboard import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -64,95 +65,121 @@ public final class BotApiMethodHelperFactory { } public static BotApiMethod getSendMessage() { - return new SendMessage() - .setChatId("@test") - .setText("Hithere") - .setReplyToMessageId(12) - .setParseMode(ParseMode.HTML) - .setReplyMarkup(new ForceReplyKeyboard()); + return SendMessage + .builder() + .chatId("@test") + .text("Hithere") + .replyToMessageId(12) + .parseMode(ParseMode.HTML) + .replyMarkup(new ForceReplyKeyboard()) + .build(); } public static BotApiMethod getAnswerCallbackQuery() { - return new AnswerCallbackQuery() - .setCallbackQueryId("id") - .setText("text") - .setShowAlert(true); + return AnswerCallbackQuery + .builder() + .callbackQueryId("id") + .text("text") + .showAlert(true) + .build(); } public static BotApiMethod getAnswerInlineQuery() { - return new AnswerInlineQuery() - .setInlineQueryId("id") - .setPersonal(true) - .setResults(getInlineQueryResultArticle(), getInlineQueryResultPhoto()) - .setCacheTime(100) - .setNextOffset("3") - .setSwitchPmParameter("PmParameter") - .setSwitchPmText("pmText"); + return AnswerInlineQuery + .builder() + .inlineQueryId("id") + .isPersonal(true) + .results(Arrays.asList(getInlineQueryResultArticle(), getInlineQueryResultPhoto())) + .cacheTime(100) + .nextOffset("3") + .switchPmParameter("PmParameter") + .switchPmText("pmText") + .build(); } public static BotApiMethod getEditMessageCaption() { - return new EditMessageCaption() - .setChatId("ChatId") - .setMessageId(1) - .setCaption("Caption") - .setReplyMarkup(getInlineKeyboardMarkup()); + return EditMessageCaption + .builder() + .chatId("ChatId") + .messageId(1) + .caption("Caption") + .replyMarkup(getInlineKeyboardMarkup()) + .build(); } public static BotApiMethod getEditMessageText() { - return new EditMessageText() - .setChatId("ChatId") - .setMessageId(1) - .setText("Text") - .setParseMode(ParseMode.MARKDOWN) - .setReplyMarkup(getInlineKeyboardMarkup()); + return EditMessageText + .builder() + .chatId("ChatId") + .messageId(1) + .text("Text") + .parseMode(ParseMode.MARKDOWN) + .replyMarkup(getInlineKeyboardMarkup()) + .build(); } public static BotApiMethod getEditMessageReplyMarkup() { - return new EditMessageReplyMarkup() - .setInlineMessageId("12345") - .setReplyMarkup(getInlineKeyboardMarkup()); + return EditMessageReplyMarkup + .builder() + .inlineMessageId("12345") + .replyMarkup(getInlineKeyboardMarkup()) + .build(); } public static BotApiMethod getForwardMessage() { - return new ForwardMessage(54L, 123L, 55) - .setFromChatId("From") - .setChatId("To") - .setMessageId(15) - .disableNotification(); + return ForwardMessage + .builder() + .fromChatId("From") + .chatId("To") + .messageId(15) + .disableNotification(true) + .build(); } public static BotApiMethod getGetChat() { - return new GetChat() - .setChatId("12345"); + return GetChat + .builder() + .chatId("12345") + .build(); } public static BotApiMethod> getChatAdministrators() { - return new GetChatAdministrators() - .setChatId("12345"); + return GetChatAdministrators + .builder() + .chatId("12345") + .build(); } public static BotApiMethod getChatMember() { - return new GetChatMember() - .setChatId("12345") - .setUserId(98765); + return GetChatMember + .builder() + .chatId("12345") + .userId(98765) + .build(); } public static BotApiMethod getChatMembersCount() { - return new GetChatMembersCount() - .setChatId("12345"); + return GetChatMembersCount + .builder() + .chatId("12345") + .build(); } public static BotApiMethod getGetFile() { - return new GetFile() - .setFileId("FileId"); + return GetFile + .builder() + .fileId("FileId") + .build(); } public static BotApiMethod> getGetGameHighScores() { - return new GetGameHighScores() - .setChatId("12345") - .setMessageId(67890) - .setUserId(98765); + return GetGameHighScores + .builder() + .chatId("12345") + .messageId(67890) + .userId(98765) + .build(); } public static BotApiMethod getGetMe() { @@ -160,10 +187,12 @@ public final class BotApiMethodHelperFactory { } public static BotApiMethod getGetUserProfilePhotos() { - return new GetUserProfilePhotos() - .setUserId(98765) - .setLimit(10) - .setOffset(3); + return GetUserProfilePhotos + .builder() + .userId(98765) + .limit(10) + .offset(3) + .build(); } public static BotApiMethod getGetWebhookInfo() { @@ -171,30 +200,38 @@ public final class BotApiMethodHelperFactory { } public static BotApiMethod getKickChatMember() { - return new KickChatMember() - .setChatId("12345") - .setUserId(98765); + return KickChatMember + .builder() + .chatId("12345") + .userId(98765) + .build(); } public static BotApiMethod getLeaveChat() { - return new LeaveChat() - .setChatId("12345"); + return LeaveChat + .builder() + .chatId("12345") + .build(); } public static BotApiMethod getSendChatAction() { - return new SendChatAction() - .setChatId("12345") - .setAction(ActionType.RECORDVIDEO); + return SendChatAction + .builder() + .chatId("12345") + .action(ActionType.RECORDVIDEO.toString()) + .build(); } public static BotApiMethod getSendContact() { - return new SendContact() - .setChatId("12345") - .setFirstName("First Name") - .setLastName("Last Name") - .setPhoneNumber("123456789") - .setReplyMarkup(getKeyboardMarkup()) - .setReplyToMessageId(54); + return SendContact + .builder() + .chatId("12345") + .firstName("First Name") + .lastName("Last Name") + .phoneNumber("123456789") + .replyMarkup(getKeyboardMarkup()) + .replyToMessageId(54) + .build(); } private static ReplyKeyboard getKeyboardMarkup() { @@ -214,17 +251,19 @@ public final class BotApiMethodHelperFactory { } private static InlineQueryResult getInlineQueryResultArticle() { - return new InlineQueryResultArticle() - .setId("0") - .setTitle("Title") - .setUrl("Url") - .setHideUrl(false) - .setDescription("Description") - .setThumbUrl("ThumbUrl") - .setThumbWidth(10) - .setThumbHeight(20) - .setInputMessageContent(getInputMessageContent()) - .setReplyMarkup(getInlineKeyboardMarkup()); + return InlineQueryResultArticle + .builder() + .id("0") + .title("Title") + .url("Url") + .hideUrl(false) + .description("Description") + .thumbUrl("ThumbUrl") + .thumbWidth(10) + .thumbHeight(20) + .inputMessageContent(getInputMessageContent()) + .replyMarkup(getInlineKeyboardMarkup()) + .build(); } private static InlineQueryResult getInlineQueryResultPhoto() { @@ -253,68 +292,84 @@ public final class BotApiMethodHelperFactory { } private static InlineKeyboardMarkup getInlineKeyboardMarkup() { - InlineKeyboardButton button = new InlineKeyboardButton() - .setText("Button1") - .setCallbackData("Callback"); + InlineKeyboardButton button = InlineKeyboardButton + .builder() + .text("Button1") + .callbackData("Callback") + .build(); List row = new ArrayList<>(); row.add(button); List> keyboard = new ArrayList<>(); keyboard.add(row); - return new InlineKeyboardMarkup() - .setKeyboard(keyboard); + return InlineKeyboardMarkup + .builder() + .keyboard(keyboard) + .build(); } public static BotApiMethod getSendGame() { - return new SendGame() - .setChatId("12345") - .setGameShortName("MyGame"); + return SendGame + .builder() + .chatId("12345") + .gameShortName("MyGame") + .build(); } public static BotApiMethod getSendLocation() { - return new SendLocation() - .setChatId("12345") - .setLatitude(12.5F) - .setLongitude(21.5F) - .setReplyToMessageId(53); + return SendLocation + .builder() + .chatId("12345") + .latitude(12.5) + .longitude(21.5) + .replyToMessageId(53) + .build(); } public static BotApiMethod getSendVenue() { - return new SendVenue() - .setChatId("12345") - .setLatitude(12.5F) - .setLongitude(21.5F) - .setReplyToMessageId(53) - .setTitle("Venue Title") - .setAddress("Address") - .setFoursquareId("FourId"); + return SendVenue + .builder() + .chatId("12345") + .latitude(12.5) + .longitude(21.5) + .replyToMessageId(53) + .title("Venue Title") + .address("Address") + .foursquareId("FourId") + .build(); } public static BotApiMethod getSetGameScore() { - return new SetGameScore() - .setInlineMessageId("12345") - .setDisableEditMessage(true) - .setScore(12) - .setUserId(98765); + return SetGameScore + .builder() + .inlineMessageId("12345") + .disableEditMessage(true) + .score(12) + .userId(98765) + .build(); } public static BotApiMethod getUnbanChatMember() { - return new UnbanChatMember() - .setChatId("12345") - .setUserId(98765); + return UnbanChatMember + .builder() + .chatId("12345") + .userId(98765) + .build(); } public static BotApiMethod getSendInvoice() { List prices = new ArrayList<>(); prices.add(new LabeledPrice("LABEL", 1000)); - return new SendInvoice() - .setChatId(12345) - .setTitle("Random title") - .setDescription("Random description") - .setPayload("Random Payload") - .setProviderToken("Random provider token") - .setStartParameter("STARTPARAM") - .setCurrency("EUR") - .setPrices(prices); + return SendInvoice + .builder() + .chatId(12345) + .title("Random title") + .description("Random description") + .payload("Random Payload") + .providerToken("Random provider token") + .startParameter("STARTPARAM") + .currency("EUR") + .prices(prices) + .build(); } } diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/test/Fakes/FakeWebhook.java b/telegrambots/src/test/java/org/telegram/telegrambots/test/Fakes/FakeWebhook.java index c79fa808..65a5e8c8 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/Fakes/FakeWebhook.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/Fakes/FakeWebhook.java @@ -1,8 +1,9 @@ package org.telegram.telegrambots.test.Fakes; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.WebhookBot; /** @@ -32,7 +33,7 @@ public class FakeWebhook implements WebhookBot { } @Override - public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException { + public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { } From fb5626de7a3627ecca07721fa06d4c95ed53415d Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Tue, 3 Nov 2020 02:24:07 +0000 Subject: [PATCH 32/45] CompletableFuture support --- TelegramBots.wiki/Changelog.md | 1 + .../PassportElementErrorTranslationFiles.java | 10 - .../telegrambots/meta/bots/AbsSender.java | 102 +++++++ .../telegrambots/bots/DefaultAbsSender.java | 257 ++++++++++++++++-- 4 files changed, 340 insertions(+), 30 deletions(-) diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 1358a72a..418a5d26 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -6,6 +6,7 @@ 5. Locations now use Double instead of Float to avoid rounding. 6. When registering a Webhook Bot, a SetWebhook object must be provided. 7. When using Webhook with Spring, extends class SpringWebhookBot instead of WebhookBot +8. New Async methods returning CompletableFutures. ### 4.9.2 ### 1. Bug fixing: #792, #801, #804, #810, #812, #813, #820 and #814 diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java index f2be141f..61212a33 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/passport/dataerror/PassportElementErrorTranslationFiles.java @@ -66,14 +66,4 @@ public class PassportElementErrorTranslationFiles implements PassportElementErro throw new TelegramApiValidationException("Type parameter can't be empty", this); } } - - @Override - public String toString() { - return "PassportElementErrorTranslationFiles{" + - "source='" + source + '\'' + - ", type='" + type + '\'' + - ", fileHashes=" + fileHashes + - ", message='" + message + '\'' + - '}'; - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java index 204bb1fa..ccf9e8ae 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/bots/AbsSender.java @@ -27,6 +27,7 @@ import org.telegram.telegrambots.meta.updateshandlers.SentCallback; import java.io.Serializable; import java.util.List; +import java.util.concurrent.CompletableFuture; /** * @author Ruben Bermudez @@ -49,6 +50,13 @@ public abstract class AbsSender { sendApiMethodAsync(method, callback); } + public > CompletableFuture executeAsync(Method method) throws TelegramApiException { + if (method == null) { + throw new TelegramApiException("Parameter method can not be null"); + } + return sendApiMethodAsync(method); + } + public > T execute(Method method) throws TelegramApiException { if (method == null) { throw new TelegramApiException("Parameter method can not be null"); @@ -70,6 +78,15 @@ public abstract class AbsSender { // Send Requests Async + + public final CompletableFuture getMeAsync() { + return sendApiMethodAsync(new GetMe()); + } + + public final CompletableFuture getWebhookInfoAsync() { + return sendApiMethodAsync(new GetWebhookInfo()); + } + public final void getMeAsync(SentCallback sentCallback) throws TelegramApiException { if (sentCallback == null) { throw new TelegramApiException("Parameter sentCallback can not be null"); @@ -175,9 +192,94 @@ public abstract class AbsSender { */ public abstract Message execute(SendAnimation sendAnimation) throws TelegramApiException; + + // Specific Send Requests Async + + public abstract CompletableFuture executeAsync(SendDocument sendDocument); + + public abstract CompletableFuture executeAsync(SendPhoto sendPhoto); + + public abstract CompletableFuture executeAsync(SendVideo sendVideo); + + public abstract CompletableFuture executeAsync(SendVideoNote sendVideoNote); + + public abstract CompletableFuture executeAsync(SendSticker sendSticker); + + /** + * Sends a file using Send Audio method (https://core.telegram.org/bots/api#sendaudio) + * @param sendAudio Information to send + * @return If success, the sent Message is returned + */ + public abstract CompletableFuture executeAsync(SendAudio sendAudio); + + /** + * Sends a voice note using Send Voice method (https://core.telegram.org/bots/api#sendvoice) + * For this to work, your audio must be in an .ogg file encoded with OPUS + * @param sendVoice Information to send + * @return If success, the sent Message is returned + */ + public abstract CompletableFuture executeAsync(SendVoice sendVoice); + + /** + * Send a media group (https://core.telegram.org/bots/api#sendMediaGroup) + * @return If success, list of generated messages + */ + public abstract CompletableFuture> executeAsync(SendMediaGroup sendMediaGroup); + + /** + * Set chat profile photo (https://core.telegram.org/bots/api#setChatPhoto) + * @param setChatPhoto Information to set the photo + * @return If success, true is returned + */ + public abstract CompletableFuture executeAsync(SetChatPhoto setChatPhoto); + + /** + * Adds a new sticker to a set (https://core.telegram.org/bots/api#addStickerToSet) + * @param addStickerToSet Information of the sticker to set + * @return If success, true is returned + */ + public abstract CompletableFuture executeAsync(AddStickerToSet addStickerToSet); + + /** + * Set sticker set thumb (https://core.telegram.org/bots/api#setStickerSetThumb) + * @param setStickerSetThumb Information of the sticker to set + * @return If success, true is returned + */ + public abstract CompletableFuture executeAsync(SetStickerSetThumb setStickerSetThumb); + + /** + * Creates a new sticker set (https://core.telegram.org/bots/api#createNewStickerSet) + * @param createNewStickerSet Information of the sticker set to create + * @return If success, true is returned + */ + public abstract CompletableFuture executeAsync(CreateNewStickerSet createNewStickerSet); + + /** + * Upload a new file as sticker (https://core.telegram.org/bots/api#uploadStickerFile) + * @param uploadStickerFile Information of the file to upload as sticker + * @return If success, true is returned + */ + public abstract CompletableFuture executeAsync(UploadStickerFile uploadStickerFile); + + /** + * Edit media in a message + * @param editMessageMedia Information of the new media + * @return If the edited message is not an inline message, the edited Message is returned, otherwise True is returned + */ + public abstract CompletableFuture executeAsync(EditMessageMedia editMessageMedia); + + /** + * Send animation + * @param sendAnimation Information of the animation + * @return Sent message + */ + public abstract CompletableFuture executeAsync(SendAnimation sendAnimation); + // Simplified methods protected abstract , Callback extends SentCallback> void sendApiMethodAsync(Method method, Callback callback); + protected abstract > CompletableFuture sendApiMethodAsync(Method method); + protected abstract > T sendApiMethod(Method method) throws TelegramApiException; } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java index 97b3c065..2f72f236 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/DefaultAbsSender.java @@ -2,6 +2,7 @@ package org.telegram.telegrambots.bots; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -50,6 +51,7 @@ import java.io.Serializable; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -61,6 +63,7 @@ import static org.telegram.telegrambots.Constants.SOCKET_TIMEOUT; * Implementation of all the methods needed to interact with Telegram Servers */ @SuppressWarnings({"unused"}) +@Slf4j public abstract class DefaultAbsSender extends AbsSender { private static final ContentType TEXT_PLAIN_CONTENT_TYPE = ContentType.create("text/plain", StandardCharsets.UTF_8); @@ -92,22 +95,6 @@ public abstract class DefaultAbsSender extends AbsSender { } } - private void configureHttpContext() { - - if (options.getProxyType() != DefaultBotOptions.ProxyType.NO_PROXY) { - InetSocketAddress socksaddr = new InetSocketAddress(options.getProxyHost(), options.getProxyPort()); - options.getHttpContext().setAttribute("socketAddress", socksaddr); - } - - if (options.getProxyType() == DefaultBotOptions.ProxyType.SOCKS4) { - options.getHttpContext().setAttribute("socksVersion", 4); - } - if (options.getProxyType() == DefaultBotOptions.ProxyType.SOCKS5) { - options.getHttpContext().setAttribute("socksVersion", 5); - } - - } - /** * Returns the token of the bot to be able to perform Telegram Api Requests * @return Token of the bot @@ -118,6 +105,10 @@ public abstract class DefaultAbsSender extends AbsSender { return options; } + public String getBaseUrl() { + return options.getBaseUrl() + getBotToken() + "/"; + } + // Send Requests public final java.io.File downloadFile(String filePath) throws TelegramApiException { @@ -776,6 +767,204 @@ public abstract class DefaultAbsSender extends AbsSender { } } + // Async Methods + + @Override + public CompletableFuture executeAsync(SendDocument sendDocument) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendDocument)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendPhoto sendPhoto) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendPhoto)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendVideo sendVideo) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendVideo)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendVideoNote sendVideoNote) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendVideoNote)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendSticker sendSticker) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendSticker)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendAudio sendAudio) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendAudio)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendVoice sendVoice) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendVoice)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture> executeAsync(SendMediaGroup sendMediaGroup) { + CompletableFuture> completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendMediaGroup)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SetChatPhoto setChatPhoto) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(setChatPhoto)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(AddStickerToSet addStickerToSet) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(addStickerToSet)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SetStickerSetThumb setStickerSetThumb) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(setStickerSetThumb)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(CreateNewStickerSet createNewStickerSet) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(createNewStickerSet)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(UploadStickerFile uploadStickerFile) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(uploadStickerFile)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(EditMessageMedia editMessageMedia) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(editMessageMedia)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + @Override + public CompletableFuture executeAsync(SendAnimation sendAnimation) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + completableFuture.complete(execute(sendAnimation)); + } catch (TelegramApiException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + + // Simplified methods @Override @@ -799,6 +988,20 @@ public abstract class DefaultAbsSender extends AbsSender { }); } + @Override + protected > CompletableFuture sendApiMethodAsync(Method method) { + CompletableFuture completableFuture = new CompletableFuture<>(); + exe.submit(() -> { + try { + String responseContent = sendMethodRequest(method); + completableFuture.complete(method.deserializeResponse(responseContent)); + } catch (IOException | TelegramApiValidationException | TelegramApiRequestException e) { + completableFuture.completeExceptionally(e); + } + }); + return completableFuture; + } + @Override protected final > T sendApiMethod(Method method) throws TelegramApiException { try { @@ -809,6 +1012,24 @@ public abstract class DefaultAbsSender extends AbsSender { } } + // Private methods + + private void configureHttpContext() { + + if (options.getProxyType() != DefaultBotOptions.ProxyType.NO_PROXY) { + InetSocketAddress socksaddr = new InetSocketAddress(options.getProxyHost(), options.getProxyPort()); + options.getHttpContext().setAttribute("socketAddress", socksaddr); + } + + if (options.getProxyType() == DefaultBotOptions.ProxyType.SOCKS4) { + options.getHttpContext().setAttribute("socksVersion", 4); + } + if (options.getProxyType() == DefaultBotOptions.ProxyType.SOCKS5) { + options.getHttpContext().setAttribute("socksVersion", 5); + } + + } + private > String sendMethodRequest(Method method) throws TelegramApiValidationException, IOException { method.validate(); String url = getBaseUrl() + method.getMethod(); @@ -888,10 +1109,6 @@ public abstract class DefaultAbsSender extends AbsSender { } } - public String getBaseUrl() { - return options.getBaseUrl() + getBotToken() + "/"; - } - private void assertParamNotNull(Object param, String paramName) throws TelegramApiException { if (param == null) { throw new TelegramApiException("Parameter " + paramName + " can not be null"); From ab00b182e821e77ea0da3b3569befd1888529bed Mon Sep 17 00:00:00 2001 From: Ruben Bermudez Date: Tue, 3 Nov 2020 02:57:36 +0000 Subject: [PATCH 33/45] Remove Guice --- TelegramBots.wiki/Changelog.md | 1 + TelegramBots.wiki/abilities/Simple-Example.md | 5 +- .../TelegramLongPollingSessionBot.java | 3 +- .../TelegramLongPollingCommandBot.java | 3 +- telegrambots-meta/pom.xml | 12 -- .../telegrambots/meta/ApiContext.java | 67 ---------- .../telegrambots/meta/TelegramBotsApi.java | 115 ++++-------------- .../telegrambots/meta/generics/Webhook.java | 6 +- .../meta/test/TestDeserialization.java | 2 +- .../meta/test/TestTelegramApi.java | 36 +++--- .../telegrambots/meta/test/base/TestBase.java | 21 ---- .../TelegramBotStarterConfiguration.java | 6 +- ...stTelegramBotStarterRegistrationHooks.java | 11 +- telegrambots/pom.xml | 5 + .../telegrambots/ApiContextInitializer.java | 22 ---- .../bots/TelegramLongPollingBot.java | 3 +- .../telegrambots/bots/TelegramWebhookBot.java | 3 +- .../updatesreceivers/DefaultBotSession.java | 2 - .../updatesreceivers/DefaultWebhook.java | 20 ++- 19 files changed, 76 insertions(+), 267 deletions(-) delete mode 100644 telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/ApiContext.java delete mode 100644 telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/base/TestBase.java delete mode 100644 telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 418a5d26..70675239 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -7,6 +7,7 @@ 6. When registering a Webhook Bot, a SetWebhook object must be provided. 7. When using Webhook with Spring, extends class SpringWebhookBot instead of WebhookBot 8. New Async methods returning CompletableFutures. +9. No more Guice to define custom class ### 4.9.2 ### 1. Bug fixing: #792, #801, #804, #810, #812, #813, #820 and #814 diff --git a/TelegramBots.wiki/abilities/Simple-Example.md b/TelegramBots.wiki/abilities/Simple-Example.md index 0a4e2567..7c3b7326 100644 --- a/TelegramBots.wiki/abilities/Simple-Example.md +++ b/TelegramBots.wiki/abilities/Simple-Example.md @@ -81,11 +81,8 @@ Running the bot is just like running the regular Telegram bots. Create a Java cl ```java public class Application { public static void main(String[] args) { - // Initializes dependencies necessary for the base bot - Guice - ApiContextInitializer.init(); - // Create the TelegramBotsApi object to register your bots - TelegramBotsApi botsApi = new TelegramBotsApi(); + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); try { // Register your newly created AbilityBot diff --git a/telegrambots-chat-session-bot/src/main/java/org/telegram/telegrambots/session/TelegramLongPollingSessionBot.java b/telegrambots-chat-session-bot/src/main/java/org/telegram/telegrambots/session/TelegramLongPollingSessionBot.java index 1cceff89..2c6751bb 100644 --- a/telegrambots-chat-session-bot/src/main/java/org/telegram/telegrambots/session/TelegramLongPollingSessionBot.java +++ b/telegrambots-chat-session-bot/src/main/java/org/telegram/telegrambots/session/TelegramLongPollingSessionBot.java @@ -6,7 +6,6 @@ import org.apache.shiro.session.mgt.DefaultSessionManager; import org.apache.shiro.session.mgt.SessionContext; import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; import org.telegram.telegrambots.bots.DefaultBotOptions; -import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.bots.TelegramLongPollingBot; @@ -24,7 +23,7 @@ public abstract class TelegramLongPollingSessionBot extends TelegramLongPollingB } public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter){ - this(chatIdConverter, ApiContext.getInstance(DefaultBotOptions.class)); + this(chatIdConverter, new DefaultBotOptions()); } public TelegramLongPollingSessionBot(ChatIdConverter chatIdConverter, DefaultBotOptions defaultBotOptions){ diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java index 24aadaf0..117a7d4e 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/TelegramLongPollingCommandBot.java @@ -1,7 +1,6 @@ package org.telegram.telegrambots.extensions.bots.commandbot; -import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.bots.AbsSender; @@ -29,7 +28,7 @@ public abstract class TelegramLongPollingCommandBot extends TelegramLongPollingB * */ public TelegramLongPollingCommandBot() { - this(ApiContext.getInstance(DefaultBotOptions.class)); + this(new DefaultBotOptions()); } /** diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index 0410cf24..165f91f5 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -69,7 +69,6 @@ UTF-8 UTF-8 - 4.2.3 2.11.3 2.11.3 20180813 @@ -77,17 +76,6 @@ - - com.google.inject - guice - ${guice.version} - - - com.google.guava - guava - - - com.fasterxml.jackson.core jackson-databind diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/ApiContext.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/ApiContext.java deleted file mode 100644 index 3859fa91..00000000 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/ApiContext.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.telegram.telegrambots.meta; - -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Singleton; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Ruben Bermudez - * @version 1.0 - */ -public class ApiContext { - private static final Logger log = LoggerFactory.getLogger(ApiContext.class); - - private static final Object lock = new Object(); - private static Injector INJECTOR; - private static Map bindings = new HashMap<>(); - private static Map singletonBindings = new HashMap<>(); - - public static T getInstance(Class type) { - return getInjector().getInstance(type); - } - - public static void register(Class type, Class implementation) { - if (bindings.containsKey(type)) { - log.debug(MessageFormat.format("Class {0} already registered", type.getName())); - } - bindings.put(type, implementation); - } - - public static void registerSingleton(Class type, Class implementation) { - if (singletonBindings.containsKey(type)) { - log.debug(MessageFormat.format("Class {0} already registered", type.getName())); - } - singletonBindings.put(type, implementation); - } - - private static Injector getInjector() { - if (INJECTOR == null) { - synchronized (lock) { - if (INJECTOR == null) { - INJECTOR = Guice.createInjector(new ApiModule()); - } - } - } - return INJECTOR; - } - - @SuppressWarnings("unchecked") - private static class ApiModule extends AbstractModule { - @Override - protected void configure() { - for (Map.Entry binding : bindings.entrySet()) { - bind(binding.getKey()).to(binding.getValue()); - } - for (Map.Entry binding : singletonBindings.entrySet()) { - bind(binding.getKey()).to(binding.getValue()).in(Singleton.class); - } - } - } -} 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 bd574a87..2642d7b9 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 @@ -2,13 +2,12 @@ package org.telegram.telegrambots.meta; import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; 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; import org.telegram.telegrambots.meta.generics.Webhook; import org.telegram.telegrambots.meta.generics.WebhookBot; -import java.text.MessageFormat; +import java.lang.reflect.InvocationTargetException; /** * @author Ruben Bermudez @@ -17,110 +16,53 @@ import java.text.MessageFormat; */ 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 - private String externalUrl; ///< External url of the bots - private String pathToCertificate; ///< Path to public key certificate /** * */ - public TelegramBotsApi() { + public TelegramBotsApi(Class botSessionClass) throws TelegramApiException { + if (botSessionClass == null) { + throw new TelegramApiException("Parameter botSessionClass can not be null or empty"); + } + this.botSessionClass = botSessionClass; } /** * Creates an HTTP server to receive webhook request - * @param externalUrl External base url for the webhook - * @param internalUrl Internal base url for the webhook + * @param webhook Webhook class * - * @implSpec This option requires externally handled HTTPS support (i.e. via proxy) + * @implSpec This option may require externally handled HTTPS support (i.e. via proxy) */ - public TelegramBotsApi(String externalUrl, String internalUrl) throws TelegramApiRequestException { - if (externalUrl == null || externalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); + public TelegramBotsApi(Class botSessionClass, Webhook webhook) throws TelegramApiException { + if (botSessionClass == null) { + throw new TelegramApiException("Parameter botSessionClass can not be null or empty"); } - if (internalUrl == null || internalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); + if (webhook == null) { + throw new TelegramApiException("Parameter webhook can not be null or empty"); } - + this.botSessionClass = botSessionClass; this.useWebhook = true; - this.externalUrl = fixExternalUrl(externalUrl); - webhook = ApiContext.getInstance(Webhook.class); - webhook.setInternalUrl(internalUrl); - webhook.startServer(); - } - - /** - * Creates an HTTPS server to receive webhook request - * @param keyStore KeyStore for the server - * @param keyStorePassword Key store password for the server - * @param externalUrl External base url for the webhook - * @param internalUrl Internal base url for the webhook - */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl) throws TelegramApiRequestException { - if (externalUrl == null || externalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); - } - if (internalUrl == null || internalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); - } - if (keyStore == null || keyStore.isEmpty()) { - throw new TelegramApiRequestException("Parameter keyStore can not be null or empty"); - } - if (keyStorePassword == null || keyStorePassword.isEmpty()) { - throw new TelegramApiRequestException("Parameter keyStorePassword can not be null or empty"); - } - - this.useWebhook = true; - this.externalUrl = fixExternalUrl(externalUrl); - webhook = ApiContext.getInstance(Webhook.class); - webhook.setInternalUrl(internalUrl); - webhook.setKeyStore(keyStore, keyStorePassword); - webhook.startServer(); - } - - /** - * Creates an HTTPS server with self-signed certificate to receive webhook request - * @param keyStore KeyStore for the server - * @param keyStorePassword Key store password for the server - * @param externalUrl External base url for the webhook - * @param internalUrl Internal base url for the webhook - * @param pathToCertificate Full path until .pem public certificate keys - */ - public TelegramBotsApi(String keyStore, String keyStorePassword, String externalUrl, String internalUrl, String pathToCertificate) throws TelegramApiRequestException { - if (externalUrl == null || externalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter externalUrl can not be null or empty"); - } - if (internalUrl == null || internalUrl.isEmpty()) { - throw new TelegramApiRequestException("Parameter internalUrl can not be null or empty"); - } - if (keyStore == null || keyStore.isEmpty()) { - throw new TelegramApiRequestException("Parameter keyStore can not be null or empty"); - } - if (keyStorePassword == null || keyStorePassword.isEmpty()) { - throw new TelegramApiRequestException("Parameter keyStorePassword can not be null or empty"); - } - if (pathToCertificate == null || pathToCertificate.isEmpty()) { - throw new TelegramApiRequestException("Parameter pathToCertificate can not be null or empty"); - } - - this.useWebhook = true; - this.externalUrl = fixExternalUrl(externalUrl); - this.pathToCertificate = pathToCertificate; - webhook = ApiContext.getInstance(Webhook.class); - webhook.setInternalUrl(internalUrl); - webhook.setKeyStore(keyStore, keyStorePassword); - webhook.startServer(); + this.webhook = webhook; + this.webhook.startServer(); } /** * Register a bot. The Bot Session is started immediately, and may be disconnected by calling close. * @param bot the bot to register */ - public BotSession registerBot(LongPollingBot bot) throws TelegramApiRequestException { + public BotSession registerBot(LongPollingBot bot) throws TelegramApiException { bot.onRegister(); bot.clearWebhook(); - BotSession session = ApiContext.getInstance(BotSession.class); + BotSession session; + try { + session = botSessionClass.getConstructor().newInstance(); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { + throw new TelegramApiException(e); + } session.setToken(bot.getBotToken()); session.setOptions(bot.getOptions()); session.setCallback(bot); @@ -140,11 +82,4 @@ public class TelegramBotsApi { bot.setWebhook(setWebhook); } } - - private static String fixExternalUrl(String externalUrl) { - if (externalUrl != null && !externalUrl.endsWith("/")) { - externalUrl = externalUrl + "/"; - } - return MessageFormat.format(webhookUrlFormat, externalUrl); - } } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/Webhook.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/Webhook.java index 09e3b7e6..4b4020c8 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/Webhook.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/generics/Webhook.java @@ -1,6 +1,6 @@ package org.telegram.telegrambots.meta.generics; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; /** * @author Ruben Bermudez @@ -8,8 +8,8 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; * Webhook interface */ public interface Webhook { - void startServer() throws TelegramApiRequestException; + void startServer() throws TelegramApiException; void registerWebhook(WebhookBot callback); void setInternalUrl(String internalUrl); - void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException; + void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiException; } 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 41b14334..9c351069 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 @@ -54,7 +54,7 @@ class TestDeserialization { "\"message\":{\"message_id\":97,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154360,\"video_note\":{\"duration\":3,\"length\":240,\"thumb\":{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":6852,\"width\":240,\"height\":240},\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":100544}}},{\"update_id\":79995152,\n" + "\"message\":{\"message_id\":98,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154363,\"voice\":{\"duration\":1,\"mime_type\":\"audio/ogg\",\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":5198}}},{\"update_id\":79995153,\n" + "\"message\":{\"message_id\":99,\"from\":{\"id\":12345678,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"it\"},\"chat\":{\"id\":12345678,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"type\":\"private\"},\"date\":1604154371,\"photo\":[{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":14395,\"width\":180,\"height\":320},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":52852,\"width\":450,\"height\":800},{\"file_id\":\"FILEID\",\"file_unique_id\":\"FILEID\",\"file_size\":84493,\"width\":720,\"height\":1280}]}},{\"update_id\":79995154,\n" + - "\"message\":{\"message_id\":6,\"from\":{\"id\":1234567,\"is_bot\":false,\"first_name\":\"MyFirstName\",\"username\":\"MyUsername\",\"language_code\":\"en\"},\"chat\":{\"id\":-110011556359722345678,\"title\":\"test group\",\"type\":\"supergroup\"},\"date\":1604163105,\"new_chat_members\":[{\"id\":123455678,\"is_bot\":true,\"first_name\":\"Testing\",\"username\":\"TestingBot\"}]}}]}"; + "\"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); diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java index 35dce949..c3cb73c0 100644 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java @@ -1,28 +1,33 @@ package org.telegram.telegrambots.meta.test; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.telegram.telegrambots.meta.TelegramBotsApi; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; -import org.telegram.telegrambots.meta.test.base.TestBase; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; +import org.telegram.telegrambots.meta.generics.BotSession; +import org.telegram.telegrambots.meta.generics.Webhook; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; /** * @author Ruben Bermudez * @version 1.0 */ -class TestTelegramApi extends TestBase { +class TestTelegramApi { - @Test - void TestTelegramApiMustBeInitializableForLongPolling() { - new TelegramBotsApi(); + private Webhook webhook; + + @BeforeEach + public void setUp() { + webhook = mock(Webhook.class); } @Test - void TestTelegramApiMustBeInitializableForWebhookWithoutSecureSupport() { + void TestTelegramApiMustBeInitializableForLongPolling() { try { - new TelegramBotsApi("externalUrl", "internalUrl"); - } catch (TelegramApiRequestException e) { + new TelegramBotsApi(BotSession.class); + } catch (TelegramApiException e) { fail(); } } @@ -30,17 +35,8 @@ class TestTelegramApi extends TestBase { @Test void TestTelegramApiMustBeInitializableForWebhook() { try { - new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl"); - } catch (TelegramApiRequestException e) { - fail(); - } - } - - @Test - void TestTelegramApiMustBeInitializableForWebhookWithSelfSignedCertificate() { - try { - new TelegramBotsApi("keyStore", "keyStorePassword", "externalUrl", "internalUrl", "selfSignedPath"); - } catch (TelegramApiRequestException e) { + new TelegramBotsApi(BotSession.class, webhook); + } catch (TelegramApiException e) { fail(); } } diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/base/TestBase.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/base/TestBase.java deleted file mode 100644 index 08fd07e6..00000000 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/base/TestBase.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.telegram.telegrambots.meta.test.base; - -import org.junit.jupiter.api.BeforeAll; -import org.telegram.telegrambots.meta.ApiContext; -import org.telegram.telegrambots.meta.generics.BotSession; -import org.telegram.telegrambots.meta.generics.Webhook; -import org.telegram.telegrambots.meta.test.fakes.FakeBotSession; -import org.telegram.telegrambots.meta.test.fakes.FakeWebhook; - -/** - * @author Ruben Bermudez - * @version 1.0 - */ -public abstract class TestBase { - - @BeforeAll - public static void beforeClass() { - ApiContext.register(BotSession.class, FakeBotSession.class); - ApiContext.register(Webhook.class, FakeWebhook.class); - } -} diff --git a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java index c47dcdbf..0afac6f6 100644 --- a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java +++ b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/TelegramBotStarterConfiguration.java @@ -6,7 +6,9 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.LongPollingBot; +import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import java.util.Collections; import java.util.List; @@ -19,8 +21,8 @@ public class TelegramBotStarterConfiguration { @Bean @ConditionalOnMissingBean(TelegramBotsApi.class) - public TelegramBotsApi telegramBotsApi() { - return new TelegramBotsApi(); + public TelegramBotsApi telegramBotsApi() throws TelegramApiException { + return new TelegramBotsApi(DefaultBotSession.class); } @Bean diff --git a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java index 1764c4ad..fa2e395c 100644 --- a/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java +++ b/telegrambots-spring-boot-starter/src/test/java/org/telegram/telegrambots/starter/TestTelegramBotStarterRegistrationHooks.java @@ -8,13 +8,18 @@ import org.springframework.context.annotation.Configuration; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.api.objects.Update; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +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.updatesreceivers.DefaultBotSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; class TestTelegramBotStarterRegistrationHooks { @@ -29,7 +34,7 @@ class TestTelegramBotStarterRegistrationHooks { TelegramBotStarterConfiguration.class)); @Test - void longPollingBotWithAnnotatedMethodshouldBeCalled() throws TelegramApiRequestException { + void longPollingBotWithAnnotatedMethodshouldBeCalled() throws TelegramApiException { when(mockTelegramBotsApi.registerBot(any(LongPollingBot.class))).thenReturn(someBotSession); diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 1cf9e4bf..61a550a3 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -97,6 +97,11 @@ telegrambots-meta 5.0.0 + + org.projectlombok + lombok + provided + com.fasterxml.jackson.core jackson-annotations diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java b/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java deleted file mode 100644 index 325106bd..00000000 --- a/telegrambots/src/main/java/org/telegram/telegrambots/ApiContextInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.telegram.telegrambots; - -import org.telegram.telegrambots.meta.generics.BotSession; -import org.telegram.telegrambots.meta.generics.Webhook; -import org.telegram.telegrambots.meta.ApiContext; -import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; -import org.telegram.telegrambots.updatesreceivers.DefaultWebhook; - -/** - * @author Ruben Bermudez - * @version 1.0 - * Initialization of ApiContext - */ -public final class ApiContextInitializer { - private ApiContextInitializer() { - } - - public static void init() { - ApiContext.register(BotSession.class, DefaultBotSession.class); - ApiContext.register(Webhook.class, DefaultWebhook.class); - } -} diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java index 9b2c2855..4468e52b 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramLongPollingBot.java @@ -1,6 +1,5 @@ package org.telegram.telegrambots.bots; -import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.generics.LongPollingBot; import org.telegram.telegrambots.util.WebhookUtils; @@ -13,7 +12,7 @@ import org.telegram.telegrambots.util.WebhookUtils; */ public abstract class TelegramLongPollingBot extends DefaultAbsSender implements LongPollingBot { public TelegramLongPollingBot() { - this(ApiContext.getInstance(DefaultBotOptions.class)); + this(new DefaultBotOptions()); } public TelegramLongPollingBot(DefaultBotOptions options) { 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 4a9e702c..0cabcee9 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java @@ -1,6 +1,5 @@ package org.telegram.telegrambots.bots; -import org.telegram.telegrambots.meta.ApiContext; import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.WebhookBot; @@ -15,7 +14,7 @@ import org.telegram.telegrambots.util.WebhookUtils; @SuppressWarnings("WeakerAccess") public abstract class TelegramWebhookBot extends DefaultAbsSender implements WebhookBot { public TelegramWebhookBot() { - this(ApiContext.getInstance(DefaultBotOptions.class)); + this(new DefaultBotOptions()); } public TelegramWebhookBot(DefaultBotOptions options) { diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java index 4ce3b853..ef777e51 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultBotSession.java @@ -1,7 +1,6 @@ package org.telegram.telegrambots.updatesreceivers; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.inject.Inject; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -61,7 +60,6 @@ public class DefaultBotSession implements BotSession { private DefaultBotOptions options; private UpdatesSupplier updatesSupplier; - @Inject public DefaultBotSession() { } diff --git a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java index c27806f4..1ad1fba1 100644 --- a/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java +++ b/telegrambots/src/main/java/org/telegram/telegrambots/updatesreceivers/DefaultWebhook.java @@ -1,14 +1,12 @@ package org.telegram.telegrambots.updatesreceivers; -import com.google.inject.Inject; - import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.grizzly.ssl.SSLContextConfigurator; import org.glassfish.grizzly.ssl.SSLEngineConfigurator; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; -import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.Webhook; import org.telegram.telegrambots.meta.generics.WebhookBot; @@ -19,8 +17,7 @@ import java.net.URI; /** * @author Ruben Bermudez * @version 1.0 - * @brief Webhook to receive updates - * @date 20 of June of 2015 + * Webhook to receive updates */ public class DefaultWebhook implements Webhook { private String keystoreServerFile; @@ -29,8 +26,7 @@ public class DefaultWebhook implements Webhook { private final RestApi restApi; - @Inject - public DefaultWebhook() throws TelegramApiRequestException { + public DefaultWebhook() { this.restApi = new RestApi(); } @@ -38,7 +34,7 @@ public class DefaultWebhook implements Webhook { this.internalUrl = internalUrl; } - public void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException { + public void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiException { this.keystoreServerFile = keyStore; this.keystoreServerPwd = keyStorePassword; validateServerKeystoreFile(keyStore); @@ -48,7 +44,7 @@ public class DefaultWebhook implements Webhook { restApi.registerCallback(callback); } - public void startServer() throws TelegramApiRequestException { + public void startServer() throws TelegramApiException { ResourceConfig rc = new ResourceConfig(); rc.register(restApi); rc.register(JacksonFeature.class); @@ -71,7 +67,7 @@ public class DefaultWebhook implements Webhook { try { grizzlyServer.start(); } catch (IOException e) { - throw new TelegramApiRequestException("Error starting webhook server", e); + throw new TelegramApiException("Error starting webhook server", e); } } @@ -79,10 +75,10 @@ public class DefaultWebhook implements Webhook { return URI.create(internalUrl); } - private static void validateServerKeystoreFile(String keyStore) throws TelegramApiRequestException { + private static void validateServerKeystoreFile(String keyStore) throws TelegramApiException { File file = new File(keyStore); if (!file.exists() || !file.canRead()) { - throw new TelegramApiRequestException("Can't find or access server keystore file."); + throw new TelegramApiException("Can't find or access server keystore file."); } } } From 95216b90c51ac68344b6b9c73acfd1e8c8afa18d Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Tue, 3 Nov 2020 03:04:14 +0000 Subject: [PATCH 34/45] Pom cleanup --- pom.xml | 23 ++++++++++++++++++++--- telegrambots-meta/pom.xml | 8 -------- telegrambots/pom.xml | 14 -------------- 3 files changed, 20 insertions(+), 25 deletions(-) diff --git a/pom.xml b/pom.xml index 37b23037..d96c1f85 100644 --- a/pom.xml +++ b/pom.xml @@ -70,11 +70,13 @@ 5.7.0 3.6.0 3.6.0 - 2.11.3 + 2.11.3 2.11.3 + 20180813 1.7.30 1.3.5 1.18.16 + 30.0-jre @@ -106,12 +108,22 @@ com.fasterxml.jackson.core jackson-annotations - ${jacksonbase.version} + ${jacksonanotation.version} + + + com.google.guava + guava + ${guava.version} com.fasterxml.jackson.module jackson-module-jaxb-annotations - ${jacksonbase.version} + ${jacksonanotation.version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jacksonanotation.version} com.fasterxml.jackson.core @@ -123,6 +135,11 @@ slf4j-api ${slf4j.version} + + org.json + json + ${json.version} + jakarta.annotation diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index 165f91f5..c88a2c7c 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -69,17 +69,12 @@ UTF-8 UTF-8 - 2.11.3 - 2.11.3 - 20180813 - 30.0-jre com.fasterxml.jackson.core jackson-databind - ${jackson.version} com.fasterxml.jackson.core @@ -90,17 +85,14 @@ com.fasterxml.jackson.core jackson-annotations - ${jacksonanotation.version} com.google.guava guava - ${guava.version} org.json json - ${json.version} org.projectlombok diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 61a550a3..7d5da3ac 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -73,9 +73,6 @@ 2.32 1.19.3 4.5.13 - 20180813 - 2.11.3 - 2.11.3 2.8.0 @@ -105,32 +102,26 @@ com.fasterxml.jackson.core jackson-annotations - ${jacksonanotation.version} com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider - ${jacksonbase.version} com.fasterxml.jackson.module jackson-module-jaxb-annotations - ${jackson.version} com.fasterxml.jackson.core jackson-databind - ${jackson.version} org.glassfish.jersey.inject jersey-hk2 - ${glassfish.version} org.glassfish.jersey.media jersey-media-json-jackson - ${glassfish.version} com.fasterxml.jackson.jaxrs @@ -145,12 +136,10 @@ org.glassfish.jersey.containers jersey-container-grizzly2-http - ${glassfish.version} org.glassfish.jersey.core jersey-server - ${glassfish.version} jakarta.xml.bind @@ -161,7 +150,6 @@ org.json json - ${json.version} org.apache.httpcomponents @@ -182,13 +170,11 @@ org.glassfish.jersey.test-framework jersey-test-framework-core - ${glassfish.version} test org.glassfish.jersey.test-framework.providers jersey-test-framework-provider-grizzly2 - ${glassfish.version} test From 93bd1e0efeb270ae6d739b018cb5a96864e7ba8b Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Tue, 3 Nov 2020 21:09:02 +0000 Subject: [PATCH 35/45] Update changelog and how to update --- README.md | 3 +- TelegramBots.wiki/Changelog.md | 12 +- TelegramBots.wiki/Errors-Handling.md | 7 -- TelegramBots.wiki/FAQ.md | 3 - TelegramBots.wiki/Getting-Started.md | 31 +---- TelegramBots.wiki/How-To-Update.md | 108 ++++++++++++++++++ TelegramBots.wiki/Using-Http-Proxy.md | 11 +- .../telegrambots/meta/TelegramBotsApi.java | 6 + .../meta/test/TestTelegramApi.java | 40 +++++++ telegrambots-spring-boot-starter/README.md | 5 +- .../starter/SpringWebhookBot.java | 33 ++++++ .../test/TestDefaultBotSession.java | 2 + 12 files changed, 206 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 6dd58284..c7ddef60 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,7 @@ Once done, you just need to create a `org.telegram.telegrambots.meta.TelegramBot // Example taken from https://github.com/rubenlagus/TelegramBotsExample public class Main { public static void main(String[] args) { - ApiContextInitializer.init(); - TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); try { telegramBotsApi.registerBot(new ChannelHandlers()); telegramBotsApi.registerBot(new DirectionsHandlers()); diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 70675239..1cc0689b 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,13 +1,17 @@ ### 5.0.0 ### 1. Update Api version [5.0](https://core.telegram.org/bots/api-changelog#june-4-2020) -2. Added Builders for many of the API methods and objects -3. Some setters/getters may have change name. They no longer return a refence to itself, use Builder for that. +2. Added Builders for many of the API methods and objects (hopefully all of them unless I missed something) +3. Some setters/getters may have change name. They no longer return a reference to itself, use Builder for that. 4. Simplified methods to set files in methods. Only InputFile is available now (this class contains constructors for all the cases) 5. Locations now use Double instead of Float to avoid rounding. +6. When using a TelegramApi for webhook usage, a Webhook instance has to be provided in constructor (i.e. DefaultWebhook class) 6. When registering a Webhook Bot, a SetWebhook object must be provided. 7. When using Webhook with Spring, extends class SpringWebhookBot instead of WebhookBot -8. New Async methods returning CompletableFutures. -9. No more Guice to define custom class +8. New Async methods returning CompletableFutures (yes, we still have the existing callback methods) +9. Added new Async methods for missing cases returning CompletableFutures. Like for sendAudio or sendVideo. +10. No more Guice to define custom class + +**[[How to update to version 5.0.0|How-To-Update#5.0.0]]** ### 4.9.2 ### 1. Bug fixing: #792, #801, #804, #810, #812, #813, #820 and #814 diff --git a/TelegramBots.wiki/Errors-Handling.md b/TelegramBots.wiki/Errors-Handling.md index 7bfa5780..169f407c 100644 --- a/TelegramBots.wiki/Errors-Handling.md +++ b/TelegramBots.wiki/Errors-Handling.md @@ -4,10 +4,3 @@ ## Terminated by other long poll or webhook ## It means that you have already a running instance of your bot. To solve it, close all running ones and then you can start a new instance. - -## No implementation for org.telegram.meta.telegrambots.generics.BotSession was bound ## -Please follow the steps as explained [here](https://github.com/rubenlagus/TelegramBots/wiki/How-To-Update#to-version-243) in "How To Update" - > At the beginning of your program (before creating your TelegramBotsApi instance, add the following line: - ``` - ApiContextInitializer.init(); - ``` diff --git a/TelegramBots.wiki/FAQ.md b/TelegramBots.wiki/FAQ.md index 5a94cbf4..a54758e1 100644 --- a/TelegramBots.wiki/FAQ.md +++ b/TelegramBots.wiki/FAQ.md @@ -265,9 +265,6 @@ Your main spring boot class should look like this: public class YourApplicationMainClass { public static void main(String[] args) { - //Add this line to initialize bots context - ApiContextInitializer.init(); - SpringApplication.run(YourApplicationMainClass.class, args); } } diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md index ec56403d..53ffab72 100644 --- a/TelegramBots.wiki/Getting-Started.md +++ b/TelegramBots.wiki/Getting-Started.md @@ -98,15 +98,13 @@ Now that we have the library, we can start coding. There are few steps to follow ``` 2. **Instantiate `TelegramBotsApi` and register our new bot:** - For this part, we need to actually perform 3 steps: _Initialize Api Context_, _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to make it in our `main` method: + For this part, we need to actually perform 2 steps: _Instantiate Telegram Api_ and _Register our Bot_. In this tutorial, we are going to make it in our `main` method: ```java public class Main { public static void main(String[] args) { - // TODO Initialize Api Context - // TODO Instantiate Telegram Bots API // TODO Register our bot @@ -115,33 +113,14 @@ Now that we have the library, we can start coding. There are few steps to follow ``` - * **Initialize Api Context**: This can be easily done calling the only method present in `ApiContextInitializer`: - - ```java - - public class Main { - public static void main(String[] args) { - - ApiContextInitializer.init(); - - // TODO Instantiate Telegram Bots API - - // TODO Register our bot - } - } - - ``` - * **Instantiate Telegram Bots API**: Easy as well, just create a new instance. Remember that a single instance can handle different bots but each bot can run only once (Telegram doesn't support concurrent calls to `GetUpdates`): ```java - + public class Main { public static void main(String[] args) { - - ApiContextInitializer.init(); - - TelegramBotsApi botsApi = new TelegramBotsApi(); + // You can use your own BotSession implementation if needed. + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); // TODO Register our bot } @@ -156,8 +135,6 @@ Now that we have the library, we can start coding. There are few steps to follow public class Main { public static void main(String[] args) { - ApiContextInitializer.init(); - TelegramBotsApi botsApi = new TelegramBotsApi(); try { diff --git a/TelegramBots.wiki/How-To-Update.md b/TelegramBots.wiki/How-To-Update.md index 11fe80e8..9c1c4733 100644 --- a/TelegramBots.wiki/How-To-Update.md +++ b/TelegramBots.wiki/How-To-Update.md @@ -1,3 +1,111 @@ +### To version 5.0.0 ### +1. ApiContextInitializer.init(); has been removed and is not required anymore, instead: + ```java + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); + + // When using webhook, create your own version of DefaultWebhook with all your parameters set. + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class, defaultWebhookInstance); + ``` +2. For location related class, change from Float to Double type, i.e: + ```java + Double latitude = location.getLatitude() + ``` +3. Instead of chain set method, use builder pattern: + ```java + // Before + new SendMessage() + .setChatId("@test") + .setText("Hithere") + .setReplyToMessageId(12) + .setParseMode(ParseMode.HTML) + .setReplyMarkup(new ForceReplyKeyboard()) + // After + SendMessage + .builder() + .chatId("@test") + .text("Hithere") + .replyToMessageId(12) + .parseMode(ParseMode.HTML) + .replyMarkup(new ForceReplyKeyboard()) + .build(); + ``` +4. Method doesn't accept chatId as Long any more, only as a String. Use Long.toString(...) when needed I.e: + ```java + Long chatIdLong = message.getChatId(); + SendMessage + .builder() + .chatId(Long.toString(chatIdLong)) + .text("Hithere") + .build(); + ``` +5. When registering a Webhook bot, provide the SetWebhook method object: + ```java + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class, defaultWebhookInstance); + telegramApi.registerBot(myWebhookBot, mySetWebhook); + ``` +6. When using Spring with a webhook bot, make your bot inherit form SpringWebhookBot instead of WebhookBot and provide your SetWebhook method in the constructor: + ```java + // Extend correct class + public class TestSpringWebhookBot extends SpringWebhookBot { + + public TestSpringWebhookBot(SetWebhook setWebhook) { + super(setWebhook); + } + + public TestSpringWebhookBot(DefaultBotOptions options, SetWebhook setWebhook) { + super(options, setWebhook); + } + + @Override + public String getBotUsername() { + return null; + } + + @Override + public String getBotToken() { + return null; + } + + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + return null; + } + + @Override + public String getBotPath() { + return null; + } + } + + // Create your SetWebhook method + @Bean + public SetWebhook setWebhookInstance() { + return SetWebhook.builder()....build(); + } + + // Create it as + @Bean + public TestSpringWebhookBot testSpringWebhookBot(SetWebhook setWebhookInstance) { + return new TestSpringWebhookBot(setWebhookInstance); + } + ``` +7. Use InputFile to set files to upload instead of different setters, i.e: + ```java + // With a file + SendDocument + .builder() + .chatId("123456") + .document(new InputFile(new File("Filename.pdf"))) + .build() + // With a Stream + SendDocument + .builder() + .chatId("123456") + .document(new InputFile("FileName", new FileInputStream("Filename.pdf"))) + .build() + ``` + + ### To version 4.4.0.2 ### 1. Logging framework has been replaced by slf4j, so now you'll need to manage your own implementation. diff --git a/TelegramBots.wiki/Using-Http-Proxy.md b/TelegramBots.wiki/Using-Http-Proxy.md index 0b7d4c0a..2a44a9c2 100644 --- a/TelegramBots.wiki/Using-Http-Proxy.md +++ b/TelegramBots.wiki/Using-Http-Proxy.md @@ -44,14 +44,11 @@ public class Main { public static void main(String[] args) { try { - - ApiContextInitializer.init(); - // Create the TelegramBotsApi object to register your bots - TelegramBotsApi botsApi = new TelegramBotsApi(); + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSessioin.class); // Set up Http proxy - DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class); + DefaultBotOptions botOptions = new DefaultBotOptions()); botOptions.setProxyHost(PROXY_HOST); botOptions.setProxyPort(PROXY_PORT); @@ -96,13 +93,11 @@ public class Main { } }); - ApiContextInitializer.init(); - // Create the TelegramBotsApi object to register your bots TelegramBotsApi botsApi = new TelegramBotsApi(); // Set up Http proxy - DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class); + DefaultBotOptions botOptions = new DefaultBotOptions(); botOptions.setProxyHost(PROXY_HOST); botOptions.setProxyPort(PROXY_PORT); 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 2642d7b9..437838fa 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 @@ -76,7 +76,13 @@ public class TelegramBotsApi { * @param setWebhook Set webhook request to initialize the bot */ public void registerBot(WebhookBot bot, SetWebhook setWebhook) throws TelegramApiException { + if (setWebhook == null) { + throw new TelegramApiException("Parameter setWebhook can not be null or empty"); + } if (useWebhook) { + if (webhook == null) { + throw new TelegramApiException("This instance doesn't support Webhook bot, use correct constructor"); + } bot.onRegister(); webhook.registerWebhook(bot); bot.setWebhook(setWebhook); diff --git a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java index c3cb73c0..1d0d7aae 100644 --- a/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java +++ b/telegrambots-meta/src/test/java/org/telegram/telegrambots/meta/test/TestTelegramApi.java @@ -3,9 +3,13 @@ package org.telegram.telegrambots.meta.test; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; +import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.generics.BotSession; import org.telegram.telegrambots.meta.generics.Webhook; +import org.telegram.telegrambots.meta.generics.WebhookBot; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; @@ -40,4 +44,40 @@ class TestTelegramApi { fail(); } } + + @Test + void TestTelegramApiMustBeThrowIfNotCreatedForWebhook() { + try { + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(BotSession.class, null); + telegramBotsApi.registerBot(new WebhookBot() { + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + return null; + } + + @Override + public void setWebhook(SetWebhook setWebhook) throws TelegramApiException { + + } + + @Override + public String getBotPath() { + return null; + } + + @Override + public String getBotUsername() { + return null; + } + + @Override + public String getBotToken() { + return null; + } + }, new SetWebhook()); + fail(); + } catch (TelegramApiException e) { + // Ignore + } + } } diff --git a/telegrambots-spring-boot-starter/README.md b/telegrambots-spring-boot-starter/README.md index 9644e564..1548f833 100644 --- a/telegrambots-spring-boot-starter/README.md +++ b/telegrambots-spring-boot-starter/README.md @@ -41,10 +41,7 @@ Your main spring boot class should look like this: @SpringBootApplication public class YourApplicationMainClass { - public static void main(String[] args) { - //Add this line to initialize bots context - ApiContextInitializer.init(); - + public static void main(String[] args) { SpringApplication.run(YourApplicationMainClass.class, args); } } diff --git a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java index a3a7c624..c271956a 100644 --- a/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java +++ b/telegrambots-spring-boot-starter/src/main/java/org/telegram/telegrambots/starter/SpringWebhookBot.java @@ -2,7 +2,9 @@ package org.telegram.telegrambots.starter; import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.bots.TelegramWebhookBot; +import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; +import org.telegram.telegrambots.meta.api.objects.Update; /** * @author Ruben Bermudez @@ -24,4 +26,35 @@ public abstract class SpringWebhookBot extends TelegramWebhookBot { public SetWebhook getSetWebhook() { return setWebhook; } + + public class TestSpringWebhookBot extends SpringWebhookBot { + + public TestSpringWebhookBot(SetWebhook setWebhook) { + super(setWebhook); + } + + public TestSpringWebhookBot(DefaultBotOptions options, SetWebhook setWebhook) { + super(options, setWebhook); + } + + @Override + public String getBotUsername() { + return null; + } + + @Override + public String getBotToken() { + return null; + } + + @Override + public BotApiMethod onWebhookUpdateReceived(Update update) { + return null; + } + + @Override + public String getBotPath() { + return null; + } + } } diff --git a/telegrambots/src/test/java/org/telegram/telegrambots/test/TestDefaultBotSession.java b/telegrambots/src/test/java/org/telegram/telegrambots/test/TestDefaultBotSession.java index 941b3508..7a5c77c9 100644 --- a/telegrambots/src/test/java/org/telegram/telegrambots/test/TestDefaultBotSession.java +++ b/telegrambots/src/test/java/org/telegram/telegrambots/test/TestDefaultBotSession.java @@ -13,6 +13,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.telegram.telegrambots.bots.DefaultBotOptions; +import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.generics.LongPollingBot; import org.telegram.telegrambots.test.Fakes.FakeLongPollingBot; @@ -37,6 +38,7 @@ public class TestDefaultBotSession { @Before public void setUp() throws Exception { session = getDefaultBotSession(); + new TelegramBotsApi(DefaultBotSession.class); } @After From 2f56a05a226848ded95875ab45eac0b2af20bab8 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Wed, 4 Nov 2020 01:23:37 +0000 Subject: [PATCH 36/45] Fix #795 --- .../timedbot/TimedSendLongPollingBot.java | 86 ++++++++++++++++--- 1 file changed, 74 insertions(+), 12 deletions(-) diff --git a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/timedbot/TimedSendLongPollingBot.java b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/timedbot/TimedSendLongPollingBot.java index 00a240a3..97ee169c 100644 --- a/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/timedbot/TimedSendLongPollingBot.java +++ b/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/timedbot/TimedSendLongPollingBot.java @@ -11,9 +11,9 @@ import java.util.concurrent.atomic.AtomicBoolean; * Created by Daniil Nikanov aka JetCoder */ -@SuppressWarnings("unused") public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot { + private static final long MANY_CHATS_SEND_INTERVAL = 33; private static final long ONE_CHAT_SEND_INTERVAL = 1000; private static final long CHAT_INACTIVE_INTERVAL = 1000 * 60 * 10; private final Timer mSendTimer = new Timer(true); @@ -21,29 +21,85 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot private final ArrayList mSendQueues = new ArrayList<>(); private final AtomicBoolean mSendRequested = new AtomicBoolean(false); + private final class MessageSenderTask extends TimerTask + { + @Override + public void run() + { + //mSendRequested used for optimisation to not traverse all mMessagesMap 30 times per second all the time + if (!mSendRequested.getAndSet(false)) + return; + + long currentTime = System.currentTimeMillis(); + mSendQueues.clear(); + boolean processNext = false; + + //First step - find all chats in which already allowed to send message (passed more than 1000 ms from previuos send) + Iterator> it = mMessagesMap.entrySet().iterator(); + while (it.hasNext()) + { + MessageQueue queue = it.next().getValue(); + int state = queue.getCurrentState(currentTime); //Actual check here + if (state == MessageQueue.GET_MESSAGE) + { + mSendQueues.add(queue); + processNext = true; + } + else if (state == MessageQueue.WAIT) + { + processNext = true; + } + else if (state == MessageQueue.DELETE) + { + it.remove(); + } + } + + //If any of chats are in state WAIT or GET_MESSAGE, request another iteration + if (processNext) + mSendRequested.set(true); + + //Second step - find oldest waiting queue and peek it's message + MessageQueue sendQueue = null; + long oldestPutTime = Long.MAX_VALUE; + for (MessageQueue queue : mSendQueues) { + long putTime = queue.getPutTime(); + if (putTime < oldestPutTime) { + oldestPutTime = putTime; + sendQueue = queue; + } + } + if (sendQueue == null) //Possible if on first step wasn't found any chats in state GET_MESSAGE + return; + + //Invoke the send callback. ChatId is passed for possible additional processing + sendMessageCallback(sendQueue.getChatId(), sendQueue.getMessage(currentTime)); + } + } + private static class MessageQueue { - static final int EMPTY = 0; //Queue is empty - static final int WAIT = 1; //Queue has message(s) but not yet allowed to send - static final int DELETE = 2; //No one message of given queue was sent longer than CHAT_INACTIVE_INTERVAL, delete for optimisation - static final int GET_MESSAGE = 3; //Queue has message(s) and ready to send + public static final int EMPTY = 0; //Queue is empty + public static final int WAIT = 1; //Queue has message(s) but not yet allowed to send + public static final int DELETE = 2; //No one message of given queue was sent longer than CHAT_INACTIVE_INTERVAL, delete for optimisation + public static final int GET_MESSAGE = 3; //Queue has message(s) and ready to send private final ConcurrentLinkedQueue mQueue = new ConcurrentLinkedQueue<>(); private final Long mChatId; private long mLastSendTime; //Time of last peek from queue private volatile long mLastPutTime; //Time of last put into queue - MessageQueue(Long chatId) + public MessageQueue(Long chatId) { mChatId = chatId; } - synchronized void putMessage(Object msg) + public synchronized void putMessage(Object msg) { mQueue.add(msg); mLastPutTime = System.currentTimeMillis(); } - synchronized int getCurrentState(long currentTime) + public synchronized int getCurrentState(long currentTime) { //currentTime is passed as parameter for optimisation to do not recall currentTimeMillis() many times long interval = currentTime - mLastSendTime; @@ -58,23 +114,29 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot return WAIT; } - synchronized Object getMessage(long currentTime) + public synchronized Object getMessage(long currentTime) { mLastSendTime = currentTime; return mQueue.poll(); } - long getPutTime() + public long getPutTime() { return mLastPutTime; } - Long getChatId() + public Long getChatId() { return mChatId; } } + //Constructor + protected TimedSendLongPollingBot() + { + mSendTimer.schedule(new MessageSenderTask(), MANY_CHATS_SEND_INTERVAL, MANY_CHATS_SEND_INTERVAL); + } + //Something like destructor public void finish() { @@ -149,5 +211,5 @@ public abstract class TimedSendLongPollingBot extends TelegramLongPollingBot } } */ - abstract void sendMessageCallback(Long chatId, Object messageRequest); + public abstract void sendMessageCallback(Long chatId, Object messageRequest); } From 934e3e8f1ae789d716d29a8278d2b7afd4eb9662 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Wed, 4 Nov 2020 01:25:03 +0000 Subject: [PATCH 37/45] Fix #795 --- TelegramBots.wiki/Changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 1cc0689b..2d9b6174 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -10,6 +10,7 @@ 8. New Async methods returning CompletableFutures (yes, we still have the existing callback methods) 9. Added new Async methods for missing cases returning CompletableFutures. Like for sendAudio or sendVideo. 10. No more Guice to define custom class +11. Bug fixes: #795 **[[How to update to version 5.0.0|How-To-Update#5.0.0]]** From b7ffc5770411ea96081cf801dd1e2ffa5ea7c3f2 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Wed, 4 Nov 2020 15:17:27 +0000 Subject: [PATCH 38/45] Update link --- TelegramBots.wiki/Changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 2d9b6174..1b5dfaf1 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,5 +1,5 @@ ### 5.0.0 ### -1. Update Api version [5.0](https://core.telegram.org/bots/api-changelog#june-4-2020) +1. Update Api version [5.0](https://core.telegram.org/bots/api-changelog#november-4-2020) 2. Added Builders for many of the API methods and objects (hopefully all of them unless I missed something) 3. Some setters/getters may have change name. They no longer return a reference to itself, use Builder for that. 4. Simplified methods to set files in methods. Only InputFile is available now (this class contains constructors for all the cases) From b2fcbaa3c26c460f329c42fa81506dbfaddc7773 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Fri, 6 Nov 2020 01:16:06 +0000 Subject: [PATCH 39/45] Deprecate forgotten setter --- .../meta/api/methods/updatingmessages/EditMessageText.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java index 850fa5a3..d29a01a6 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java @@ -86,6 +86,10 @@ public class EditMessageText extends BotApiMethod { @JsonProperty(ENTITIES_FIELD) private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode + /** + * @deprecated Use {#setChatId(String)} + */ + @Deprecated public void setChatId(Long chatId) { this.chatId = chatId.toString(); } From bd2aa24e0057f6549a5dfaa0e02a516d1f22ffcd Mon Sep 17 00:00:00 2001 From: Victor Melnik Date: Sat, 7 Nov 2020 10:56:42 +0200 Subject: [PATCH 40/45] Fix FAQ.md according to API changes --- TelegramBots.wiki/FAQ.md | 89 ++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 45 deletions(-) diff --git a/TelegramBots.wiki/FAQ.md b/TelegramBots.wiki/FAQ.md index a54758e1..a296ec59 100644 --- a/TelegramBots.wiki/FAQ.md +++ b/TelegramBots.wiki/FAQ.md @@ -79,29 +79,29 @@ Quick example here that is showing ChactActions for commands like "/type" or "/r ```java if (update.hasMessage() && update.getMessage().hasText()) { - String text = update.getMessage().getText(); + String text = update.getMessage().getText(); - SendChatAction sendChatAction = new SendChatAction(); - sendChatAction.setChatId(update.getMessage().getChatId()); + SendChatAction sendChatAction = new SendChatAction(); + sendChatAction.setChatId(update.getMessage().getChatId()); - if (text.equals("/type")) { - // -> "typing" - sendChatAction.setAction(ActionType.TYPING); - // -> "recording a voice message" - } else if (text.equals("/record_audio")) { - sendChatAction.setAction(ActionType.RECORDAUDIO); - } else { - // -> more actions in the Enum ActionType - // For information: https://core.telegram.org/bots/api#sendchataction - sendChatAction.setAction(ActionType.UPLOADDOCUMENT); - } + if (text.equals("/type")) { + // -> "typing" + sendChatAction.setAction(ActionType.TYPING); + // -> "recording a voice message" + } else if (text.equals("/record_audio")) { + sendChatAction.setAction(ActionType.RECORDAUDIO); + } else { + // -> more actions in the Enum ActionType + // For information: https://core.telegram.org/bots/api#sendchataction + sendChatAction.setAction(ActionType.UPLOADDOCUMENT); + } - try { - Boolean wasSuccessfull = execute(sendChatAction); - } catch (TelegramApiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + try { + Boolean wasSuccessfull = execute(sendChatAction); + } catch (TelegramApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } ``` @@ -116,7 +116,7 @@ There are several method to send a photo to an user using `sendPhoto` method: Wi // Set destination chat id sendPhotoRequest.setChatId(chatId); // Set the photo url as a simple photo - sendPhotoRequest.setPhoto(url); + sendPhotoRequest.setPhoto(new InputFile(url)); try { // Execute the method execute(sendPhotoRequest); @@ -131,7 +131,7 @@ There are several method to send a photo to an user using `sendPhoto` method: Wi // Set destination chat id sendPhotoRequest.setChatId(chatId); // Set the photo url as a simple photo - sendPhotoRequest.setPhoto(fileId); + sendPhotoRequest.setPhoto(new InputFile(fileId)); try { // Execute the method execute(sendPhotoRequest); @@ -145,8 +145,8 @@ There are several method to send a photo to an user using `sendPhoto` method: Wi SendPhoto sendPhotoRequest = new SendPhoto(); // Set destination chat id sendPhotoRequest.setChatId(chatId); - // Set the photo file as a new photo (You can also use InputStream with a method overload) - sendPhotoRequest.setNewPhoto(new File(filePath)); + // Set the photo file as a new photo (You can also use InputStream with a constructor overload) + sendPhotoRequest.setPhoto(new InputFile(new File(filePath))); try { // Execute the method execute(sendPhotoRequest); @@ -162,24 +162,23 @@ In this example we will check if user sends to bot a photo, if it is, get Photo' ```java // If it is a photo if (update.hasMessage() && update.getMessage().hasPhoto()) { - // Array with photos - List photos = update.getMessage().getPhoto(); - // Get largest photo's file_id - String f_id = photos.stream() - .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()) - .findFirst() - .orElse(null).getFileId(); - // Send photo by file_id we got before - SendPhoto msg = new SendPhoto() - .setChatId(update.getMessage().getChatId()) - .setPhoto(f_id) - .setCaption("Photo"); - try { - execute(msg); // Call method to send the photo - } catch (TelegramApiException e) { - e.printStackTrace(); - } - } + // Array with photos + List photos = update.getMessage().getPhoto(); + // Get largest photo's file_id + String f_id = photos.stream() + .max(Comparator.comparing(PhotoSize::getFileSize)) + .orElseThrow().getFileId(); + // Send photo by file_id we got before + SendPhoto msg = new SendPhoto() + .setChatId(update.getMessage().getChatId()) + .setPhoto(new InputFile(f_id)) + .setCaption("Photo"); + try { + execute(msg); // Call method to send the photo + } catch (TelegramApiException e) { + e.printStackTrace(); + } +} ``` ## How to use custom keyboards? ## @@ -264,9 +263,9 @@ Your main spring boot class should look like this: @SpringBootApplication public class YourApplicationMainClass { - public static void main(String[] args) { - SpringApplication.run(YourApplicationMainClass.class, args); - } + public static void main(String[] args) { + SpringApplication.run(YourApplicationMainClass.class, args); + } } ``` From c42955985ea229ab2488b8db047fac4fb18e849f Mon Sep 17 00:00:00 2001 From: Dhina17 Date: Sun, 8 Nov 2020 02:58:47 +0530 Subject: [PATCH 41/45] Fix unhandled exception type error in examples --- README.md | 2 +- TelegramBots.wiki/Getting-Started.md | 3 +-- TelegramBots.wiki/Using-Http-Proxy.md | 2 +- TelegramBots.wiki/abilities/Simple-Example.md | 6 +++--- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c7ddef60..1d7d44f1 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ Once done, you just need to create a `org.telegram.telegrambots.meta.TelegramBot // Example taken from https://github.com/rubenlagus/TelegramBotsExample public class Main { public static void main(String[] args) { - TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); try { + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class); telegramBotsApi.registerBot(new ChannelHandlers()); telegramBotsApi.registerBot(new DirectionsHandlers()); telegramBotsApi.registerBot(new RaeHandlers()); diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md index 53ffab72..ef710b88 100644 --- a/TelegramBots.wiki/Getting-Started.md +++ b/TelegramBots.wiki/Getting-Started.md @@ -135,9 +135,8 @@ Now that we have the library, we can start coding. There are few steps to follow public class Main { public static void main(String[] args) { - TelegramBotsApi botsApi = new TelegramBotsApi(); - try { + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); botsApi.registerBot(new MyAmazingBot()); } catch (TelegramApiException e) { e.printStackTrace(); diff --git a/TelegramBots.wiki/Using-Http-Proxy.md b/TelegramBots.wiki/Using-Http-Proxy.md index 2a44a9c2..ea0833d5 100644 --- a/TelegramBots.wiki/Using-Http-Proxy.md +++ b/TelegramBots.wiki/Using-Http-Proxy.md @@ -94,7 +94,7 @@ public class Main { }); // Create the TelegramBotsApi object to register your bots - TelegramBotsApi botsApi = new TelegramBotsApi(); + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); // Set up Http proxy DefaultBotOptions botOptions = new DefaultBotOptions(); diff --git a/TelegramBots.wiki/abilities/Simple-Example.md b/TelegramBots.wiki/abilities/Simple-Example.md index 7c3b7326..f8f549ac 100644 --- a/TelegramBots.wiki/abilities/Simple-Example.md +++ b/TelegramBots.wiki/abilities/Simple-Example.md @@ -81,10 +81,10 @@ Running the bot is just like running the regular Telegram bots. Create a Java cl ```java public class Application { public static void main(String[] args) { - // Create the TelegramBotsApi object to register your bots - TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); - try { + // Create the TelegramBotsApi object to register your bots + TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class); + // Register your newly created AbilityBot botsApi.registerBot(new HelloBot()); } catch (TelegramApiException e) { From 88dd390566b05416912490d32bdaf15e24750b1e Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 8 Nov 2020 11:28:57 +0000 Subject: [PATCH 42/45] Fix deserialization bug --- .../api/methods/commands/GetMyCommands.java | 4 +- .../meta/api/methods/updates/Close.java | 15 +++--- .../meta/api/methods/updates/LogOut.java | 11 ++--- .../meta/test/TestDeserialization.java | 48 +++++++++++++++++++ 4 files changed, 62 insertions(+), 16 deletions(-) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java index ea339716..4fb9c343 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/commands/GetMyCommands.java @@ -1,10 +1,10 @@ package org.telegram.telegrambots.meta.api.methods.commands; import com.fasterxml.jackson.core.type.TypeReference; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; @@ -27,7 +27,7 @@ import java.util.ArrayList; @Getter @Setter @ToString -@NoArgsConstructor +@AllArgsConstructor @Builder public class GetMyCommands extends BotApiMethod> { public static final String PATH = "getMyCommands"; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java index 0e40a1f1..73f461c4 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/Close.java @@ -1,15 +1,14 @@ package org.telegram.telegrambots.meta.api.methods.updates; import com.fasterxml.jackson.core.type.TypeReference; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; -import lombok.NoArgsConstructor; 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.WebhookInfo; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -28,9 +27,9 @@ import java.io.IOException; @Getter @Setter @ToString -@NoArgsConstructor +@AllArgsConstructor @Builder -public class Close extends BotApiMethod { +public class Close extends BotApiMethod { public static final String PATH = "close"; @Override @@ -39,15 +38,15 @@ public class Close extends BotApiMethod { } @Override - public WebhookInfo deserializeResponse(String answer) throws TelegramApiRequestException { + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { try { - ApiResponse result = OBJECT_MAPPER.readValue(answer, - new TypeReference>() { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>() { }); if (result.getOk()) { return result.getResult(); } else { - throw new TelegramApiRequestException("Error logging out info", result); + throw new TelegramApiRequestException("Error closing", result); } } catch (IOException e2) { throw new TelegramApiRequestException("Unable to deserialize response", e2); diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java index 5fa8dea4..bf549d1c 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updates/LogOut.java @@ -9,7 +9,6 @@ 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.WebhookInfo; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; @@ -30,7 +29,7 @@ import java.io.IOException; @ToString @AllArgsConstructor @Builder -public class LogOut extends BotApiMethod { +public class LogOut extends BotApiMethod { public static final String PATH = "logOut"; @Override @@ -39,15 +38,15 @@ public class LogOut extends BotApiMethod { } @Override - public WebhookInfo deserializeResponse(String answer) throws TelegramApiRequestException { + public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { try { - ApiResponse result = OBJECT_MAPPER.readValue(answer, - new TypeReference>() { + ApiResponse result = OBJECT_MAPPER.readValue(answer, + new TypeReference>() { }); if (result.getOk()) { return result.getResult(); } else { - throw new TelegramApiRequestException("Error logging out info", result); + throw new TelegramApiRequestException("Error logging out", result); } } catch (IOException e2) { throw new TelegramApiRequestException("Unable to deserialize response", e2); 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 9c351069..aeb8b0e8 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 @@ -5,7 +5,10 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.telegram.telegrambots.meta.api.methods.commands.GetMyCommands; +import org.telegram.telegrambots.meta.api.methods.updates.Close; import org.telegram.telegrambots.meta.api.methods.updates.GetUpdates; +import org.telegram.telegrambots.meta.api.methods.updates.LogOut; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.api.objects.Audio; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; @@ -17,6 +20,7 @@ import org.telegram.telegrambots.meta.api.objects.MessageEntity; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.Voice; +import org.telegram.telegrambots.meta.api.objects.commands.BotCommand; import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; @@ -151,6 +155,50 @@ class TestDeserialization { } } + @Test + void TestDeserializationCloseMethod() throws Exception { + String updateText = "{\"ok\":true,\"result\": true}"; + + Boolean response = new Close().deserializeResponse(updateText); + + assertTrue(response); + } + + @Test + void TestDeserializationLogoutMethod() throws Exception { + String updateText = "{\"ok\":true,\"result\": true}"; + + Boolean response = new LogOut().deserializeResponse(updateText); + + assertTrue(response); + } + + @Test + void TestDeserializationGetMyCommandsMethod() throws Exception { + String updateText = "{\n" + + " \"ok\": true,\n" + + " \"result\": [\n" + + " {\n" + + " \"command\": \"enabled\",\n" + + " \"description\": \"Enabled Command\"\n" + + " },\n" + + " {\n" + + " \"command\": \"disabled\",\n" + + " \"description\": \"Disabled Command\"\n" + + " }\n" + + " ]\n" + + "}"; + + ArrayList response = new GetMyCommands().deserializeResponse(updateText); + + assertNotNull(response); + assertEquals(2, response.size()); + assertEquals("enabled", response.get(0).getCommand()); + assertEquals("Enabled Command", response.get(0).getDescription()); + assertEquals("disabled", response.get(1).getCommand()); + assertEquals("Disabled Command", response.get(1).getDescription()); + } + @Test void TestUpdateDeserialization() throws Exception { Update update = mapper.readValue(TelegramBotsHelper.GetUpdate(), Update.class); From f60425820a338972696d6057f2f827f96e3469dd Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 8 Nov 2020 11:29:13 +0000 Subject: [PATCH 43/45] Fixed #794 --- .../telegram/telegrambots/meta/api/objects/ChatPermissions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java index e75e9d66..40f52f2b 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatPermissions.java @@ -37,7 +37,7 @@ public class ChatPermissions implements BotApiObject { @JsonProperty(CAN_SEND_MESSAGES_FIELD) private Boolean canSendMessages; ///< Optional. True, if the user is allowed to send text messages, contacts, locations and venues @JsonProperty(CAN_SEND_MEDIA_MESSAGES_FIELD) - private Boolean getCanSendMediaMessages; ///< Optional. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages + private Boolean canSendMediaMessages; ///< Optional. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages @JsonProperty(CAN_SEND_POLLS_FIELD) private Boolean canSendPolls; ///< Optional. True, if the user is allowed to send polls, implies can_send_messages @JsonProperty(CAN_SEND_OTHER_MESSAGES_FIELD) From 4af620770b399bb6156988f51765dd8aacf24d21 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 8 Nov 2020 11:35:09 +0000 Subject: [PATCH 44/45] Remove old method messed --- .../api/methods/updatingmessages/EditMessageText.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java index d29a01a6..a268347a 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/updatingmessages/EditMessageText.java @@ -86,14 +86,6 @@ public class EditMessageText extends BotApiMethod { @JsonProperty(ENTITIES_FIELD) private List entities; ///< Optional. List of special entities that appear in message text, which can be specified instead of parse_mode - /** - * @deprecated Use {#setChatId(String)} - */ - @Deprecated - public void setChatId(Long chatId) { - this.chatId = chatId.toString(); - } - public void disableWebPagePreview() { disableWebPagePreview = true; } From 415d31eaec6cf1516545c6d6383365d6c97c4a22 Mon Sep 17 00:00:00 2001 From: rubenlagus Date: Sun, 8 Nov 2020 16:19:38 +0000 Subject: [PATCH 45/45] Updage 5.0.1 --- README.md | 8 ++++---- TelegramBots.wiki/Changelog.md | 6 ++++++ TelegramBots.wiki/Getting-Started.md | 4 ++-- TelegramBots.wiki/abilities/Simple-Example.md | 4 ++-- pom.xml | 2 +- telegrambots-abilities/README.md | 8 ++++---- telegrambots-abilities/pom.xml | 4 ++-- telegrambots-chat-session-bot/README.md | 2 +- telegrambots-chat-session-bot/pom.xml | 4 ++-- telegrambots-extensions/README.md | 4 ++-- telegrambots-extensions/pom.xml | 4 ++-- telegrambots-meta/pom.xml | 2 +- telegrambots-spring-boot-starter/README.md | 4 ++-- telegrambots-spring-boot-starter/pom.xml | 4 ++-- telegrambots/pom.xml | 4 ++-- 15 files changed, 35 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 1d7d44f1..abb79697 100644 --- a/README.md +++ b/README.md @@ -27,16 +27,16 @@ Just import add the library to your project with one of these options: org.telegram telegrambots - 5.0.0 + 5.0.1 ``` ```gradle - compile "org.telegram:telegrambots:5.0.0" + compile "org.telegram:telegrambots:5.0.1" ``` - 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/5.0.0) - 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/5.0.0) + 2. Using Jitpack from [here](https://jitpack.io/#rubenlagus/TelegramBots/5.0.1) + 3. Download the jar(including all dependencies) from [here](https://mvnrepository.com/artifact/org.telegram/telegrambots/5.0.1) In order to use Long Polling mode, just create your own bot extending `org.telegram.telegrambots.bots.TelegramLongPollingBot`. diff --git a/TelegramBots.wiki/Changelog.md b/TelegramBots.wiki/Changelog.md index 1b5dfaf1..adb8a126 100644 --- a/TelegramBots.wiki/Changelog.md +++ b/TelegramBots.wiki/Changelog.md @@ -1,3 +1,9 @@ +### 5.0.1 ### +1. Fixing couple of bugs from 5.0.0 +2. Buf fixing: #794 +3. Docs updated to reflect usage for version 5.0.0 +4. EditMessageText setChatIId(Long) is removed to keep consistency + ### 5.0.0 ### 1. Update Api version [5.0](https://core.telegram.org/bots/api-changelog#november-4-2020) 2. Added Builders for many of the API methods and objects (hopefully all of them unless I missed something) diff --git a/TelegramBots.wiki/Getting-Started.md b/TelegramBots.wiki/Getting-Started.md index ef710b88..0c8907ca 100644 --- a/TelegramBots.wiki/Getting-Started.md +++ b/TelegramBots.wiki/Getting-Started.md @@ -11,13 +11,13 @@ First you need ot get the library and add it to your project. There are few poss org.telegram telegrambots - 5.0.0 + 5.0.1 ``` * With **Gradle**: ```groovy - compile group: 'org.telegram', name: 'telegrambots', version: '5.0.0' + compile group: 'org.telegram', name: 'telegrambots', version: '5.0.1' ``` 2. Don't like **Maven Central Repository**? It can also be taken from [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots). diff --git a/TelegramBots.wiki/abilities/Simple-Example.md b/TelegramBots.wiki/abilities/Simple-Example.md index f8f549ac..ca569282 100644 --- a/TelegramBots.wiki/abilities/Simple-Example.md +++ b/TelegramBots.wiki/abilities/Simple-Example.md @@ -9,12 +9,12 @@ As with any Java project, you will need to set your dependencies. org.telegram telegrambots-abilities - 5.0.0 + 5.0.1 ``` * **Gradle** ```groovy - implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '5.0.0' + implementation group: 'org.telegram', name: 'telegrambots-abilities', version: '5.0.1' ``` * [JitPack](https://jitpack.io/#rubenlagus/TelegramBots) diff --git a/pom.xml b/pom.xml index d96c1f85..08cae031 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots pom - 5.0.0 + 5.0.1 telegrambots diff --git a/telegrambots-abilities/README.md b/telegrambots-abilities/README.md index 6c58330e..52d18fe0 100644 --- a/telegrambots-abilities/README.md +++ b/telegrambots-abilities/README.md @@ -18,19 +18,19 @@ Usage org.telegram telegrambots-abilities - 5.0.0 + 5.0.1 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-abilities:5.0.0" + compile "org.telegram:telegrambots-abilities:5.0.1" ``` -**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v5.0.0) +**JitPack** - [JitPack](https://jitpack.io/#rubenlagus/TelegramBots/v5.0.1) -**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v5.0.0) +**Plain imports** - [Here](https://github.com/rubenlagus/TelegramBots/releases/tag/v5.0.1) Motivation ---------- diff --git a/telegrambots-abilities/pom.xml b/telegrambots-abilities/pom.xml index 7d4b10fb..a5429c14 100644 --- a/telegrambots-abilities/pom.xml +++ b/telegrambots-abilities/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambots-abilities @@ -84,7 +84,7 @@ org.telegram telegrambots - 5.0.0 + 5.0.1 org.apache.commons diff --git a/telegrambots-chat-session-bot/README.md b/telegrambots-chat-session-bot/README.md index 5cfd0cf7..99446945 100644 --- a/telegrambots-chat-session-bot/README.md +++ b/telegrambots-chat-session-bot/README.md @@ -15,7 +15,7 @@ Usage org.telegram telegrambots-chat-session-bot - 5.0.0 + 5.0.1 ``` diff --git a/telegrambots-chat-session-bot/pom.xml b/telegrambots-chat-session-bot/pom.xml index 00b9368f..4d83e7e2 100644 --- a/telegrambots-chat-session-bot/pom.xml +++ b/telegrambots-chat-session-bot/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambots-chat-session-bot @@ -84,7 +84,7 @@ org.telegram telegrambots - 5.0.0 + 5.0.1 diff --git a/telegrambots-extensions/README.md b/telegrambots-extensions/README.md index e56cf766..5deffb45 100644 --- a/telegrambots-extensions/README.md +++ b/telegrambots-extensions/README.md @@ -16,12 +16,12 @@ Just import add the library to your project with one of these options: org.telegram telegrambotsextensions - 5.0.0 + 5.0.1 ``` 2. Using Gradle: ```gradle - compile "org.telegram:telegrambotsextensions:5.0.0" + compile "org.telegram:telegrambotsextensions:5.0.1" ``` \ No newline at end of file diff --git a/telegrambots-extensions/pom.xml b/telegrambots-extensions/pom.xml index 4dd00ed0..6e6fad0d 100644 --- a/telegrambots-extensions/pom.xml +++ b/telegrambots-extensions/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambotsextensions @@ -75,7 +75,7 @@ org.telegram telegrambots - 5.0.0 + 5.0.1 diff --git a/telegrambots-meta/pom.xml b/telegrambots-meta/pom.xml index c88a2c7c..e5b7595e 100644 --- a/telegrambots-meta/pom.xml +++ b/telegrambots-meta/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambots-meta diff --git a/telegrambots-spring-boot-starter/README.md b/telegrambots-spring-boot-starter/README.md index 1548f833..5501393d 100644 --- a/telegrambots-spring-boot-starter/README.md +++ b/telegrambots-spring-boot-starter/README.md @@ -18,14 +18,14 @@ Usage org.telegram telegrambots-spring-boot-starter - 5.0.0 + 5.0.1 ``` **Gradle** ```gradle - compile "org.telegram:telegrambots-spring-boot-starter:5.0.0" + compile "org.telegram:telegrambots-spring-boot-starter:5.0.1" ``` Motivation diff --git a/telegrambots-spring-boot-starter/pom.xml b/telegrambots-spring-boot-starter/pom.xml index 08f21a38..914e3e54 100644 --- a/telegrambots-spring-boot-starter/pom.xml +++ b/telegrambots-spring-boot-starter/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambots-spring-boot-starter @@ -70,7 +70,7 @@ UTF-8 UTF-8 - 5.0.0 + 5.0.1 2.3.5.RELEASE 3.18.0 diff --git a/telegrambots/pom.xml b/telegrambots/pom.xml index 7d5da3ac..37143391 100644 --- a/telegrambots/pom.xml +++ b/telegrambots/pom.xml @@ -7,7 +7,7 @@ org.telegram Bots - 5.0.0 + 5.0.1 telegrambots @@ -92,7 +92,7 @@ org.telegram telegrambots-meta - 5.0.0 + 5.0.1 org.projectlombok