Browse Source

Api Version 7.2.0

master
ruben 2 years ago
parent
commit
1e47f87f15
  1. 127
      pom.xml
  2. 2
      src/main/java/org/telegram/BuildVars.java
  3. 96
      src/main/java/org/telegram/Main.java
  4. 15
      src/main/java/org/telegram/commands/HelloCommand.java
  5. 15
      src/main/java/org/telegram/commands/HelpCommand.java
  6. 12
      src/main/java/org/telegram/commands/StartCommand.java
  7. 14
      src/main/java/org/telegram/commands/StopCommand.java
  8. 35
      src/main/java/org/telegram/database/ConnectionDB.java
  9. 21
      src/main/java/org/telegram/database/CreationStrings.java
  10. 208
      src/main/java/org/telegram/database/DatabaseManager.java
  11. 44
      src/main/java/org/telegram/services/CustomTimerTask.java
  12. 44
      src/main/java/org/telegram/services/DirectionsService.java
  13. 120
      src/main/java/org/telegram/services/RaeService.java
  14. 8
      src/main/java/org/telegram/services/TimerExecutor.java
  15. 375
      src/main/java/org/telegram/services/TransifexService.java
  16. 218
      src/main/java/org/telegram/services/WeatherService.java
  17. 35
      src/main/java/org/telegram/structure/WeatherAlert.java
  18. 80
      src/main/java/org/telegram/updateshandlers/ChannelHandlers.java
  19. 49
      src/main/java/org/telegram/updateshandlers/CommandsHandler.java
  20. 163
      src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java
  21. 110
      src/main/java/org/telegram/updateshandlers/ElektrollArtFanHandler.java
  22. 160
      src/main/java/org/telegram/updateshandlers/FilesHandlers.java
  23. 82
      src/main/java/org/telegram/updateshandlers/RaeHandlers.java
  24. 141
      src/main/java/org/telegram/updateshandlers/TransifexHandlers.java
  25. 377
      src/main/java/org/telegram/updateshandlers/WeatherHandlers.java
  26. 51
      src/main/java/org/telegram/updateshandlers/WebHookExampleHandlers.java

127
pom.xml

@ -6,47 +6,84 @@
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>botapi</artifactId> <artifactId>botapi</artifactId>
<version>2.1</version> <version>7.2.0</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<httpcompontents.version>4.5.13</httpcompontents.version> <java.version>17</java.version>
<telegrambots.version>5.0.1.1</telegrambots.version> <maven.compiler.release>17</maven.compiler.release>
<json.version>20201115</json.version> <maven.compiler.source>${java.version}</maven.compiler.source>
<jsoup.version>1.13.1</jsoup.version> <maven.compiler.target>${java.version}</maven.compiler.target>
<mysql.version>8.0.23</mysql.version>
<commonsio.version>2.8.0</commonsio.version> <httpcompontents.version>4.5.3</httpcompontents.version>
<lombok.version>1.18.16</lombok.version> <telegrambots.version>7.2.0</telegrambots.version>
<json.version>20240303</json.version>
<jsoup.version>1.17.2</jsoup.version>
<mysql.version>8.3.0</mysql.version>
<commonsio.version>2.15.1</commonsio.version>
<lombok.version>1.18.30</lombok.version>
<okhttp.version>4.12.0</okhttp.version>
<slf4j.version>2.0.12</slf4j.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>org.jetbrains.kotlin</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>kotlin-stdlib-jdk8</artifactId>
<version>2.12.1</version> <version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>24.1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>11.0.19</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.telegram</groupId>
<artifactId>lombok</artifactId> <artifactId>telegrambots-longpolling</artifactId>
<version>${lombok.version}</version> <version>${telegrambots.version}</version>
<scope>provided</scope> </dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-webhook</artifactId>
<version>${telegrambots.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId> <artifactId>telegrambots-client</artifactId>
<version>${telegrambots.version}</version> <version>${telegrambots.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambotsextensions</artifactId> <artifactId>telegrambots-extensions</artifactId>
<version>${telegrambots.version}</version> <version>${telegrambots.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
@ -58,18 +95,8 @@
<version>${commonsio.version}</version> <version>${commonsio.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>com.mysql</groupId>
<artifactId>httpclient</artifactId> <artifactId>mysql-connector-j</artifactId>
<version>${httpcompontents.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpcompontents.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version> <version>${mysql.version}</version>
</dependency> </dependency>
<dependency> <dependency>
@ -88,7 +115,7 @@
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version> <version>3.3.2</version>
<executions> <executions>
<execution> <execution>
<id>clean-project</id> <id>clean-project</id>
@ -101,7 +128,7 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version> <version>3.6.0</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
@ -125,7 +152,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version> <version>3.3.0</version>
<executions> <executions>
<execution> <execution>
<id>attach-sources</id> <id>attach-sources</id>
@ -139,7 +166,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.4</version> <version>3.3.0</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
@ -152,7 +179,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version> <version>3.6.3</version>
<executions> <executions>
<execution> <execution>
<id>attach-javadocs</id> <id>attach-javadocs</id>
@ -163,13 +190,31 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.4.1</version>
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
</execution>
</executions>
<configuration>
<rules>
<DependencyConvergence />
</rules>
</configuration>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version> <version>3.6.1</version>
<executions> <executions>
<execution> <execution>
<id>copy-dependencies</id> <id>copy-dependencies</id>
@ -189,10 +234,18 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration> <configuration>
<source>1.8</source> <source>${java.version}</source>
<target>1.8</target> <target>${java.version}</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

2
src/main/java/org/telegram/BuildVars.java

@ -26,7 +26,7 @@ public class BuildVars {
public static final String TRANSIFEXUSER = "<transifex-user>"; public static final String TRANSIFEXUSER = "<transifex-user>";
public static final String TRANSIFEXPASSWORD = "<transifex-password>"; public static final String TRANSIFEXPASSWORD = "<transifex-password>";
public static final List<Integer> ADMINS = new ArrayList<>(); public static final List<Long> ADMINS = new ArrayList<>();
public static final String pathToLogs = "./"; public static final String pathToLogs = "./";

96
src/main/java/org/telegram/Main.java

@ -1,91 +1,43 @@
package org.telegram; package org.telegram;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.longpolling.TelegramBotsLongPollingApplication;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; import org.telegram.telegrambots.webhook.TelegramBotsWebhookApplication;
import org.telegram.telegrambots.updatesreceivers.DefaultWebhook; import org.telegram.telegrambots.webhook.WebhookOptions;
import org.telegram.updateshandlers.ChannelHandlers;
import org.telegram.updateshandlers.CommandsHandler;
import org.telegram.updateshandlers.DirectionsHandlers;
import org.telegram.updateshandlers.ElektrollArtFanHandler;
import org.telegram.updateshandlers.FilesHandlers;
import org.telegram.updateshandlers.RaeHandlers;
import org.telegram.updateshandlers.WeatherHandlers; import org.telegram.updateshandlers.WeatherHandlers;
import org.telegram.updateshandlers.WebHookExampleHandlers; import org.telegram.updateshandlers.WebHookExampleHandlers;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Main class to create all bots * Main class to create all bots
* @date 20 of June of 2015
*/ */
@Slf4j @Slf4j
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
try { try (TelegramBotsWebhookApplication webhookApplication = new TelegramBotsWebhookApplication(WebhookOptions.builder().enableRequestLogging(true).build())) {
TelegramBotsApi telegramBotsApi = createTelegramBotsApi(); webhookApplication.registerBot(new WebHookExampleHandlers(BotConfig.WEBHOOK_TOKEN));
try { try (TelegramBotsLongPollingApplication botsApplication = new TelegramBotsLongPollingApplication()) {
// Register long polling bots. They work regardless type of TelegramBotsApi we are creating botsApplication.registerBot(BotConfig.WEATHER_TOKEN, new WeatherHandlers(BotConfig.WEATHER_TOKEN));
// telegramBotsApi.registerBot(new ChannelHandlers()); botsApplication.registerBot(BotConfig.CHANNEL_TOKEN, new ChannelHandlers(BotConfig.CHANNEL_TOKEN));
// telegramBotsApi.registerBot(new DirectionsHandlers()); botsApplication.registerBot(BotConfig.COMMANDS_TOKEN, new CommandsHandler(BotConfig.COMMANDS_TOKEN, BotConfig.COMMANDS_USER));
// telegramBotsApi.registerBot(new RaeHandlers()); botsApplication.registerBot(BotConfig.DIRECTIONS_TOKEN, new DirectionsHandlers(BotConfig.DIRECTIONS_TOKEN));
telegramBotsApi.registerBot(new WeatherHandlers()); botsApplication.registerBot(BotConfig.ELEKTROLLART_TOKEN, new ElektrollArtFanHandler(BotConfig.ELEKTROLLART_TOKEN));
// telegramBotsApi.registerBot(new TransifexHandlers()); botsApplication.registerBot(BotConfig.FILES_TOKEN, new FilesHandlers(BotConfig.FILES_TOKEN));
// telegramBotsApi.registerBot(new FilesHandlers()); botsApplication.registerBot(BotConfig.RAE_TOKEN, new RaeHandlers(BotConfig.RAE_TOKEN));
// telegramBotsApi.registerBot(new CommandsHandler(BotConfig.COMMANDS_USER)); Thread.currentThread().join();
// telegramBotsApi.registerBot(new ElektrollArtFanHandler());
} catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e);
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error registering bot", e);
}
}
private static TelegramBotsApi createTelegramBotsApi() throws TelegramApiException {
TelegramBotsApi telegramBotsApi;
if (!BuildVars.useWebHook) {
// Default (long polling only)
telegramBotsApi = createLongPollingTelegramBotsApi();
} else if (!BuildVars.pathToCertificatePublicKey.isEmpty()) {
// Filled a path to a pem file ? looks like you're going for the self signed option then, invoke with store and pem file to supply.
telegramBotsApi = createSelfSignedTelegramBotsApi();
telegramBotsApi.registerBot(new WebHookExampleHandlers(), null);
} else {
// Non self signed, make sure you've added private/public and if needed intermediate to your cert-store.
telegramBotsApi = createNoSelfSignedTelegramBotsApi();
telegramBotsApi.registerBot(new WebHookExampleHandlers(), null);
} }
return telegramBotsApi; } catch (TelegramApiException e) {
} log.error("Error registering bot", e);
/**
* @brief Creates a Telegram Bots Api to use Long Polling (getUpdates) bots.
* @return TelegramBotsApi to register the bots.
*/
private static TelegramBotsApi createLongPollingTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(DefaultBotSession.class);
}
/**
* @brief Creates a Telegram Bots Api to use Long Polling bots and webhooks bots with self-signed certificates.
* @return TelegramBotsApi to register the bots.
*
* @note https://core.telegram.org/bots/self-signed#java-keystore for generating a keypair in store and exporting the pem.
* @note Don't forget to split the pem bundle (begin/end), use only the public key as input!
*/
private static TelegramBotsApi createSelfSignedTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(DefaultBotSession.class, new DefaultWebhook());
} }
/**
* @brief Creates a Telegram Bots Api to use Long Polling bots and webhooks bots with no-self-signed certificates.
* @return TelegramBotsApi to register the bots.
*
* @note Coming from a set of pem files here's one way to do it:
* @code{.sh}
* openssl pkcs12 -export -in public.pem -inkey private.pem > keypair.p12
* keytool -importkeystore -srckeystore keypair.p12 -destkeystore server.jks -srcstoretype pkcs12
* #have (an) intermediate(s) to supply? first:
* cat public.pem intermediate.pem > set.pem (use set.pem as -in)
* @endcode
*/
private static TelegramBotsApi createNoSelfSignedTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(DefaultBotSession.class, new DefaultWebhook());
} }
} }

15
src/main/java/org/telegram/commands/HelloCommand.java

@ -6,8 +6,8 @@ import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
/** /**
* This command simply replies with a hello to the users command and * This command simply replies with a hello to the users command and
@ -17,12 +17,15 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
*/ */
@Slf4j @Slf4j
public class HelloCommand extends BotCommand { public class HelloCommand extends BotCommand {
private static final String LOGTAG = "HELLOCOMMAND";
public HelloCommand() { public HelloCommand() {
super("hello", "Say hallo to this bot"); super("hello", "Say hallo to this bot");
} }
@Override @Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) { public void execute(TelegramClient telegramClient, User user, Chat chat, String[] arguments) {
if (!DatabaseManager.getInstance().getUserStateForCommandsBot(user.getId())) { if (!DatabaseManager.getInstance().getUserStateForCommandsBot(user.getId())) {
return; return;
@ -40,14 +43,12 @@ public class HelloCommand extends BotCommand {
messageTextBuilder.append(String.join(" ", arguments)); messageTextBuilder.append(String.join(" ", arguments));
} }
SendMessage answer = new SendMessage(); SendMessage answer = new SendMessage(chat.getId().toString(), messageTextBuilder.toString());
answer.setChatId(chat.getId().toString());
answer.setText(messageTextBuilder.toString());
try { try {
absSender.execute(answer); telegramClient.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error", e);
} }
} }
} }

15
src/main/java/org/telegram/commands/HelpCommand.java

@ -8,8 +8,8 @@ import org.telegram.telegrambots.extensions.bots.commandbot.commands.ICommandReg
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
/** /**
* This command helps the user to find the command they need * This command helps the user to find the command they need
@ -18,6 +18,9 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
*/ */
@Slf4j @Slf4j
public class HelpCommand extends BotCommand { public class HelpCommand extends BotCommand {
private static final String LOGTAG = "HELPCOMMAND";
private final ICommandRegistry commandRegistry; private final ICommandRegistry commandRegistry;
public HelpCommand(ICommandRegistry commandRegistry) { public HelpCommand(ICommandRegistry commandRegistry) {
@ -26,7 +29,7 @@ public class HelpCommand extends BotCommand {
} }
@Override @Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) { public void execute(TelegramClient telegramClient, User user, Chat chat, String[] strings) {
if (!DatabaseManager.getInstance().getUserStateForCommandsBot(user.getId())) { if (!DatabaseManager.getInstance().getUserStateForCommandsBot(user.getId())) {
return; return;
@ -39,15 +42,13 @@ public class HelpCommand extends BotCommand {
helpMessageBuilder.append(botCommand.toString()).append("\n\n"); helpMessageBuilder.append(botCommand.toString()).append("\n\n");
} }
SendMessage helpMessage = new SendMessage(); SendMessage helpMessage = new SendMessage(chat.getId().toString(), helpMessageBuilder.toString());
helpMessage.setChatId(chat.getId().toString());
helpMessage.enableHtml(true); helpMessage.enableHtml(true);
helpMessage.setText(helpMessageBuilder.toString());
try { try {
absSender.execute(helpMessage); telegramClient.execute(helpMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error", e);
} }
} }
} }

12
src/main/java/org/telegram/commands/StartCommand.java

@ -6,8 +6,8 @@ import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
/** /**
* This commands starts the conversation with the bot * This commands starts the conversation with the bot
@ -21,7 +21,7 @@ public class StartCommand extends BotCommand {
} }
@Override @Override
public void execute(AbsSender absSender, User user, Chat chat, String[] strings) { public void execute(TelegramClient telegramClient, User user, Chat chat, String[] strings) {
DatabaseManager databseManager = DatabaseManager.getInstance(); DatabaseManager databseManager = DatabaseManager.getInstance();
StringBuilder messageBuilder = new StringBuilder(); StringBuilder messageBuilder = new StringBuilder();
@ -36,14 +36,12 @@ public class StartCommand extends BotCommand {
messageBuilder.append("this bot will demonstrate you the command feature of the Java TelegramBots API!"); messageBuilder.append("this bot will demonstrate you the command feature of the Java TelegramBots API!");
} }
SendMessage answer = new SendMessage(); SendMessage answer = new SendMessage(chat.getId().toString(), messageBuilder.toString());
answer.setChatId(chat.getId().toString());
answer.setText(messageBuilder.toString());
try { try {
absSender.execute(answer); telegramClient.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error", e);
} }
} }
} }

14
src/main/java/org/telegram/commands/StopCommand.java

@ -6,8 +6,8 @@ import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
/** /**
* This commands stops the conversation with the bot. * This commands stops the conversation with the bot.
@ -18,6 +18,8 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@Slf4j @Slf4j
public class StopCommand extends BotCommand { public class StopCommand extends BotCommand {
public static final String LOGTAG = "STOPCOMMAND";
/** /**
* Construct * Construct
*/ */
@ -26,21 +28,19 @@ public class StopCommand extends BotCommand {
} }
@Override @Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) { public void execute(TelegramClient telegramClient, User user, Chat chat, String[] arguments) {
DatabaseManager dbManager = DatabaseManager.getInstance(); DatabaseManager dbManager = DatabaseManager.getInstance();
if (dbManager.getUserStateForCommandsBot(user.getId())) { if (dbManager.getUserStateForCommandsBot(user.getId())) {
dbManager.setUserStateForCommandsBot(user.getId(), false); dbManager.setUserStateForCommandsBot(user.getId(), false);
String userName = user.getFirstName() + " " + user.getLastName(); String userName = user.getFirstName() + " " + user.getLastName();
SendMessage answer = new SendMessage(); SendMessage answer = new SendMessage(chat.getId().toString(), "Good bye " + userName + "\n" + "Hope to see you soon!");
answer.setChatId(chat.getId().toString());
answer.setText("Good bye " + userName + "\n" + "Hope to see you soon!");
try { try {
absSender.execute(answer); telegramClient.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error", e);
} }
} }
} }

35
src/main/java/org/telegram/database/ConectionDB.java → src/main/java/org/telegram/database/ConnectionDB.java

@ -10,6 +10,7 @@ package org.telegram.database;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.DriverManager; import java.sql.DriverManager;
@ -24,20 +25,21 @@ import java.sql.Statement;
* Connector to database * Connector to database
*/ */
@Slf4j @Slf4j
public class ConectionDB { public class ConnectionDB {
private Connection currentConection; private final Connection currentConection;
public ConectionDB() { public ConnectionDB() {
this.currentConection = openConexion(); this.currentConection = openConexion();
} }
private Connection openConexion() { private Connection openConexion() {
Connection connection = null; Connection connection = null;
try { try {
Class.forName(BuildVars.controllerDB).newInstance(); Class.forName(BuildVars.controllerDB).getDeclaredConstructor().newInstance();
connection = DriverManager.getConnection(BuildVars.linkDB, BuildVars.userDB, BuildVars.password); connection = DriverManager.getConnection(BuildVars.linkDB, BuildVars.userDB, BuildVars.password);
} catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException e) { } catch (SQLException | ClassNotFoundException | IllegalAccessException | InstantiationException |
log.error(e.getLocalizedMessage(), e); NoSuchMethodException | InvocationTargetException e) {
log.error("Error opening connection", e);
} }
return connection; return connection;
@ -47,7 +49,7 @@ public class ConectionDB {
try { try {
this.currentConection.close(); this.currentConection.close();
} catch (SQLException e) { } catch (SQLException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error closing the connection", e);
} }
} }
@ -79,14 +81,15 @@ public class ConectionDB {
new String[]{"TABLE"}); new String[]{"TABLE"});
while (res.next()) { while (res.next()) {
if (res.getString("TABLE_NAME").compareTo("Versions") == 0) { if (res.getString("TABLE_NAME").compareTo("Versions") == 0) {
final ResultSet result = runSqlQuery("SELECT Max(Version) FROM Versions"); try(ResultSet result = runSqlQuery("SELECT Max(Version) FROM Versions")) {
while (result.next()) { while (result.next()) {
max = (max > result.getInt(1)) ? max : result.getInt(1); max = Math.max(max, result.getInt(1));
}
} }
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error checking version", e);
} }
return max; return max;
} }
@ -111,7 +114,17 @@ public class ConectionDB {
this.currentConection.rollback(); this.currentConection.rollback();
} }
} finally { } finally {
this.currentConection.setAutoCommit(false); this.currentConection.setAutoCommit(true);
}
}
public void rollbackTransaction() throws SQLException {
try {
this.currentConection.rollback();
} catch (SQLException e) {
log.error("Error rolling back the transaction", e);
} finally {
this.currentConection.setAutoCommit(true);
} }
} }
} }

21
src/main/java/org/telegram/database/CreationStrings.java

@ -3,30 +3,29 @@ package org.telegram.database;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 2.0 * @version 2.0
* @brief Strings to create database * Strings to create database
* @date 15 of May of 2015
*/ */
public class CreationStrings { public class CreationStrings {
public static final int version = 8; public static final int version = 8;
public static final String createVersionTable = "CREATE TABLE IF NOT EXISTS Versions(ID INTEGER PRIMARY KEY AUTO_INCREMENT, Version INTEGER);"; public static final String createVersionTable = "CREATE TABLE IF NOT EXISTS Versions(ID INTEGER PRIMARY KEY AUTO_INCREMENT, Version INTEGER);";
public static final String insertCurrentVersion = "INSERT IGNORE INTO Versions (Version) VALUES(%d);"; public static final String insertCurrentVersion = "INSERT IGNORE INTO Versions (Version) VALUES(%d);";
public static final String createFilesTable = "CREATE TABLE IF NOT EXISTS Files (fileId VARCHAR(100) PRIMARY KEY, userId INTEGER NOT NULL, caption TEXT NOT NULL)"; public static final String createFilesTable = "CREATE TABLE IF NOT EXISTS Files (fileId VARCHAR(100) PRIMARY KEY, userId BIGINT NOT NULL, caption TEXT NOT NULL)";
public static final String createUsersForFilesTable = "CREATE TABLE IF NOT EXISTS FilesUsers (userId INTEGER PRIMARY KEY, status INTEGER NOT NULL DEFAULT 0)"; public static final String createUsersForFilesTable = "CREATE TABLE IF NOT EXISTS FilesUsers (userId BIGINT PRIMARY KEY, status INTEGER NOT NULL DEFAULT 0)";
public static final String createRecentWeatherTable = "CREATE TABLE IF NOT EXISTS RecentWeather (ID INTEGER PRIMARY KEY AUTO_INCREMENT, userId INTEGER NOT NULL, " + public static final String createRecentWeatherTable = "CREATE TABLE IF NOT EXISTS RecentWeather (ID INTEGER PRIMARY KEY AUTO_INCREMENT, userId BIGINT NOT NULL, " +
"date TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, cityId INTEGER NOT NULL, cityName VARCHAR(60) NOT NULL," + "date TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, cityId INTEGER NOT NULL, cityName VARCHAR(60) NOT NULL," +
"CONSTRAINT unique_cistyuser UNIQUE (userId,cityId))"; "CONSTRAINT unique_cistyuser UNIQUE (userId,cityId))";
public static final String createDirectionsDatabase = "CREATE TABLE IF NOT EXISTS Directions (userId INTEGER PRIMARY KEY, status INTEGER NOT NULL, " + public static final String createDirectionsDatabase = "CREATE TABLE IF NOT EXISTS Directions (userId BIGINT PRIMARY KEY, status INTEGER NOT NULL, " +
"messageId INTEGER NOT NULL DEFAULT 0, origin VARCHAR(100));"; "messageId INTEGER NOT NULL DEFAULT 0, origin VARCHAR(100));";
public static final String createLastUpdateDatabase = "CREATE TABLE IF NOT EXISTS LastUpdate (token VARCHAR(125) PRIMARY KEY, updateId INTEGER NOT NULL DEFAULT -1);"; public static final String createLastUpdateDatabase = "CREATE TABLE IF NOT EXISTS LastUpdate (token VARCHAR(125) PRIMARY KEY, updateId INTEGER NOT NULL DEFAULT -1);";
public static final String createUserLanguageDatabase = "CREATE TABLE IF NOT EXISTS UserLanguage (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL)"; public static final String createUserLanguageDatabase = "CREATE TABLE IF NOT EXISTS UserLanguage (userId BIGINT PRIMARY KEY, languageCode VARCHAR(10) NOT NULL)";
public static final String createUserWeatherOptionDatabase = "CREATE TABLE IF NOT EXISTS UserWeatherOptions (userId INTEGER PRIMARY KEY, languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + public static final String createUserWeatherOptionDatabase = "CREATE TABLE IF NOT EXISTS UserWeatherOptions (userId BIGINT PRIMARY KEY, languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " +
"units VARCHAR(10) NOT NULL DEFAULT 'metric')"; "units VARCHAR(10) NOT NULL DEFAULT 'metric')";
public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId INTEGER NOT NULL, chatId BIGINT NOT NULL, state INTEGER NOT NULL DEFAULT 0, " + public static final String createWeatherStateTable = "CREATE TABLE IF NOT EXISTS WeatherState (userId BIGINT NOT NULL, chatId BIGINT NOT NULL, state INTEGER NOT NULL DEFAULT 0, " +
"languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " + "languageCode VARCHAR(10) NOT NULL DEFAULT 'en', " +
"CONSTRAINT `watherPrimaryKey` PRIMARY KEY(userId,chatId));"; "CONSTRAINT `watherPrimaryKey` PRIMARY KEY(userId,chatId));";
public static final String createWeatherAlertTable = "CREATE TABLE IF NOT EXISTS WeatherAlert (id INTEGER PRIMARY KEY AUTO_INCREMENT, userId INTEGER NOT NULL, cityId INTEGER NOT NULL, " + public static final String createWeatherAlertTable = "CREATE TABLE IF NOT EXISTS WeatherAlert (id INTEGER PRIMARY KEY AUTO_INCREMENT, userId BIGINT NOT NULL, cityId INTEGER NOT NULL, " +
"cityName VARCHAR(60) NOT NULL, time INTEGER NOT NULL DEFAULT -1, CONSTRAINT unique_cityNameAlert UNIQUE (userId, cityName)," + "cityName VARCHAR(60) NOT NULL, time INTEGER NOT NULL DEFAULT -1, CONSTRAINT unique_cityNameAlert UNIQUE (userId, cityName)," +
"CONSTRAINT unique_cityIdAlert UNIQUE (userId, cityId));"; "CONSTRAINT unique_cityIdAlert UNIQUE (userId, cityId));";
public static final String CREATE_COMMANDS_TABLE = "CREATE TABLE IF NOT EXISTS CommandUsers (userId INTEGER PRIMARY KEY, status INTEGER NOT NULL);"; public static final String CREATE_COMMANDS_TABLE = "CREATE TABLE IF NOT EXISTS CommandUsers (userId BIGINT PRIMARY KEY, status INTEGER NOT NULL);";
} }

208
src/main/java/org/telegram/database/DatabaseManager.java

@ -26,13 +26,13 @@ import java.util.List;
@Slf4j @Slf4j
public class DatabaseManager { public class DatabaseManager {
private static volatile DatabaseManager instance; private static volatile DatabaseManager instance;
private static volatile ConectionDB connetion; private static volatile ConnectionDB connetion;
/** /**
* Private constructor (due to Singleton) * Private constructor (due to Singleton)
*/ */
private DatabaseManager() { private DatabaseManager() {
connetion = new ConectionDB(); connetion = new ConnectionDB();
final int currentVersion = connetion.checkVersion(); final int currentVersion = connetion.checkVersion();
log.info("Current db version: " + currentVersion); log.info("Current db version: " + currentVersion);
if (currentVersion < CreationStrings.version) { if (currentVersion < CreationStrings.version) {
@ -90,9 +90,17 @@ public class DatabaseManager {
if (currentVersion == 7) { if (currentVersion == 7) {
currentVersion = updateToVersion8(); currentVersion = updateToVersion8();
} }
if (currentVersion == 8) {
currentVersion = updateToVersion8();
}
connetion.commitTransaction(); connetion.commitTransaction();
} catch (SQLException e) { } catch (SQLException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error updating DB", e);
try {
connetion.rollbackTransaction();
} catch (SQLException ex) {
log.error("Error rollingback the transaction", ex);
}
} }
} }
@ -140,6 +148,20 @@ public class DatabaseManager {
return 8; return 8;
} }
private int updateToVersion9() throws SQLException {
connetion.executeQuery("ALTER TABLE Files MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE FilesUsers MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE RecentWeather MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE Directions MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE UserLanguage MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE UserWeatherOptions MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE WeatherState MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE WeatherAlert MODIFY COLUMN userId BIGINT;");
connetion.executeQuery("ALTER TABLE CommandUsers MODIFY COLUMN userId BIGINT;");
connetion.executeQuery(String.format(CreationStrings.insertCurrentVersion, 9));
return 8;
}
private int createNewTables() throws SQLException { private int createNewTables() throws SQLException {
connetion.executeQuery(CreationStrings.createVersionTable); connetion.executeQuery(CreationStrings.createVersionTable);
connetion.executeQuery(CreationStrings.createFilesTable); connetion.executeQuery(CreationStrings.createFilesTable);
@ -155,104 +177,104 @@ public class DatabaseManager {
return CreationStrings.version; return CreationStrings.version;
} }
public boolean setUserStateForCommandsBot(Integer userId, boolean active) { public boolean setUserStateForCommandsBot(Long userId, boolean active) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO CommandUsers (userId, status) VALUES(?, ?) ON DUPLICATE KEY UPDATE status=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO CommandUsers (userId, status) VALUES(?, ?) ON DUPLICATE KEY UPDATE status=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, active ? 1 : 0); preparedStatement.setInt(2, active ? 1 : 0);
preparedStatement.setInt(3, active ? 1 : 0); preparedStatement.setInt(3, active ? 1 : 0);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error setting user state for commands bot", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean getUserStateForCommandsBot(Integer userId) { public boolean getUserStateForCommandsBot(Long userId) {
int status = -1; int status = -1;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("Select status FROM CommandUsers WHERE userId=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("Select status FROM CommandUsers WHERE userId=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
status = result.getInt("status"); status = result.getInt("status");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user state for command bot", e);
} }
return status == 1; return status == 1;
} }
public boolean addFile(String fileId, Integer userId, String caption) { public boolean addFile(String fileId, Long userId, String caption) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO Files (fileId, userId, caption) VALUES(?, ?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO Files (fileId, userId, caption) VALUES(?, ?, ?)");
preparedStatement.setString(1, fileId); preparedStatement.setString(1, fileId);
preparedStatement.setInt(2, userId); preparedStatement.setLong(2, userId);
preparedStatement.setString(3, caption); preparedStatement.setString(3, caption);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting file", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public HashMap<String, String> getFilesByUser(Integer userId) { public HashMap<String, String> getFilesByUser(Long userId) {
HashMap<String, String> files = new HashMap<>(); HashMap<String, String> files = new HashMap<>();
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT * FROM Files WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT * FROM Files WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
while (result.next()) { while (result.next()) {
files.put(result.getString("fileId"), result.getString("caption")); files.put(result.getString("fileId"), result.getString("caption"));
} }
result.close(); result.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting files for user", e);
} }
return files; return files;
} }
public boolean addUserForFile(Integer userId, int status) { public boolean addUserForFile(Long userId, int status) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO FilesUsers (userId, status) VALUES(?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO FilesUsers (userId, status) VALUES(?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, status); preparedStatement.setInt(2, status);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user for file", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean deleteUserForFile(Integer userId) { public boolean deleteUserForFile(Long userId) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM FilesUsers WHERE userId=?;"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM FilesUsers WHERE userId=?;");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error deleting user file", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public int getUserStatusForFile(Integer userId) { public int getUserStatusForFile(Long userId) {
int status = -1; int status = -1;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("Select status FROM FilesUsers WHERE userId=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("Select status FROM FilesUsers WHERE userId=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
status = result.getInt("status"); status = result.getInt("status");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user status", e);
} }
return status; return status;
} }
@ -265,7 +287,7 @@ public class DatabaseManager {
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
exists = result.next(); exists = result.next();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error checking file", e);
} }
return exists; return exists;
} }
@ -278,58 +300,58 @@ public class DatabaseManager {
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error deleting files", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean addRecentWeather(Integer userId, Integer cityId, String cityName) { public boolean addRecentWeather(Long userId, Integer cityId, String cityName) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO RecentWeather (userId, cityId, cityName) VALUES(?, ?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO RecentWeather (userId, cityId, cityName) VALUES(?, ?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, cityId); preparedStatement.setInt(2, cityId);
preparedStatement.setString(3, cityName); preparedStatement.setString(3, cityName);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error adding recent weather", e);
} }
cleanUpRecent(userId); cleanUpRecent(userId);
return updatedRows > 0; return updatedRows > 0;
} }
public List<String> getRecentWeather(Integer userId) { public List<String> getRecentWeather(Long userId) {
List<String> recentWeather = new ArrayList<>(); List<String> recentWeather = new ArrayList<>();
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("select * FROM RecentWeather WHERE userId=? order by date desc"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("select * FROM RecentWeather WHERE userId=? order by date desc");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
while (result.next()) { while (result.next()) {
recentWeather.add(result.getString("cityName")); recentWeather.add(result.getString("cityName"));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting recent weather", e);
} }
return recentWeather; return recentWeather;
} }
private void cleanUpRecent(Integer userId) { private void cleanUpRecent(Long userId) {
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM RecentWeather WHERE userid = ? AND ID <= (SELECT ID FROM (SELECT id From RecentWeather where userId = ? ORDER BY id DESC LIMIT 1 OFFSET 4 ) AS T1 )"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM RecentWeather WHERE userid = ? AND ID <= (SELECT ID FROM (SELECT id From RecentWeather where userId = ? ORDER BY id DESC LIMIT 1 OFFSET 4 ) AS T1 )");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, userId); preparedStatement.setLong(2, userId);
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error cleaning up recent user", e);
} }
} }
public boolean addUserForDirection(Integer userId, int status, int messageId, String origin) { public boolean addUserForDirection(Long userId, int status, int messageId, String origin) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO Directions (userId, status, messageId, origin) VALUES(?, ?, ?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO Directions (userId, status, messageId, origin) VALUES(?, ?, ?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, status); preparedStatement.setInt(2, status);
preparedStatement.setInt(3, messageId); preparedStatement.setInt(3, messageId);
if (origin == null || origin.isEmpty()) { if (origin == null || origin.isEmpty()) {
@ -339,65 +361,65 @@ public class DatabaseManager {
} }
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error adding user for direction", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public int getUserDestinationStatus(Integer userId) { public int getUserDestinationStatus(Long userId) {
int status = -1; int status = -1;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT status FROM Directions WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT status FROM Directions WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
status = result.getInt("status"); status = result.getInt("status");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user destination status", e);
} }
return status; return status;
} }
public int getUserDestinationMessageId(Integer userId) { public int getUserDestinationMessageId(Long userId) {
int messageId = 0; int messageId = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT messageId FROM Directions WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT messageId FROM Directions WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
messageId = result.getInt("messageId"); messageId = result.getInt("messageId");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user destination message id", e);
} }
return messageId; return messageId;
} }
public String getUserOrigin(Integer userId) { public String getUserOrigin(Long userId) {
String origin = ""; String origin = "";
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT origin FROM Directions WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT origin FROM Directions WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
origin = result.getString("origin"); origin = result.getString("origin");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error get user origin", e);
} }
return origin; return origin;
} }
public boolean deleteUserForDirections(Integer userId) { public boolean deleteUserForDirections(Long userId) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM Directions WHERE userId=?;"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM Directions WHERE userId=?;");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error deleting user directions", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
@ -410,7 +432,7 @@ public class DatabaseManager {
preparedStatement.setInt(2, updateId); preparedStatement.setInt(2, updateId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error adding last update", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
@ -425,91 +447,91 @@ public class DatabaseManager {
updateId = result.getInt("updateId"); updateId = result.getInt("updateId");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting last update", e);
} }
return updateId; return updateId;
} }
public String getUserLanguage(Integer userId) { public String getUserLanguage(Long userId) {
String languageCode = "en"; String languageCode = "en";
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT languageCode FROM UserLanguage WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT languageCode FROM UserLanguage WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
languageCode = result.getString("languageCode"); languageCode = result.getString("languageCode");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting user language", e);
} }
return languageCode; return languageCode;
} }
public boolean putUserLanguage(Integer userId, String language) { public boolean putUserLanguage(Long userId, String language) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO UserLanguage (userId, languageCode) VALUES(?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO UserLanguage (userId, languageCode) VALUES(?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setString(2, language); preparedStatement.setString(2, language);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error updating user language", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public int getWeatherState(Integer userId, Long chatId) { public int getWeatherState(Long userId, Long chatId) {
int state = 0; int state = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT state FROM WeatherState WHERE userId = ? AND chatId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT state FROM WeatherState WHERE userId = ? AND chatId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setLong(2, chatId); preparedStatement.setLong(2, chatId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
state = result.getInt("state"); state = result.getInt("state");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting weather state", e);
} }
return state; return state;
} }
public boolean insertWeatherState(Integer userId, Long chatId, int state) { public boolean insertWeatherState(Long userId, Long chatId, int state) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO WeatherState (userId, chatId, state) VALUES (?, ?, ?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("REPLACE INTO WeatherState (userId, chatId, state) VALUES (?, ?, ?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setLong(2, chatId); preparedStatement.setLong(2, chatId);
preparedStatement.setInt(3, state); preparedStatement.setInt(3, state);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error insert weather state", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public Integer getRecentWeatherIdByCity(Integer userId, String city) { public Integer getRecentWeatherIdByCity(Long userId, String city) {
Integer cityId = null; Integer cityId = null;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("select cityId FROM RecentWeather WHERE userId=? AND cityName=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("select cityId FROM RecentWeather WHERE userId=? AND cityName=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setString(2, city); preparedStatement.setString(2, city);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
cityId = result.getInt("cityId"); cityId = result.getInt("cityId");
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting recent weather by city", e);
} }
return cityId; return cityId;
} }
public String[] getUserWeatherOptions(Integer userId) { public String[] getUserWeatherOptions(Long userId) {
String[] options = new String[] {"en", "metric"}; String[] options = new String[] {"en", "metric"};
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT * FROM UserWeatherOptions WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("SELECT * FROM UserWeatherOptions WHERE userId = ?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
if (result.next()) { if (result.next()) {
options[0] = result.getString("languageCode"); options[0] = result.getString("languageCode");
@ -518,100 +540,100 @@ public class DatabaseManager {
addNewUserWeatherOptions(userId); addNewUserWeatherOptions(userId);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting wether options", e);
} }
return options; return options;
} }
private boolean addNewUserWeatherOptions(Integer userId) { private boolean addNewUserWeatherOptions(Long userId) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO UserWeatherOptions (userId) VALUES (?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO UserWeatherOptions (userId) VALUES (?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error adding new user weather options", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean putUserWeatherLanguageOption(Integer userId, String language) { public boolean putUserWeatherLanguageOption(Long userId, String language) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("UPDATE UserWeatherOptions SET languageCode = ? WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("UPDATE UserWeatherOptions SET languageCode = ? WHERE userId = ?");
preparedStatement.setString(1, language); preparedStatement.setString(1, language);
preparedStatement.setInt(2, userId); preparedStatement.setLong(2, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error updating weather language options", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean putUserWeatherUnitsOption(Integer userId, String units) { public boolean putUserWeatherUnitsOption(Long userId, String units) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("UPDATE UserWeatherOptions SET units = ? WHERE userId = ?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("UPDATE UserWeatherOptions SET units = ? WHERE userId = ?");
preparedStatement.setString(1, units); preparedStatement.setString(1, units);
preparedStatement.setInt(2, userId); preparedStatement.setLong(2, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error adding weather unit option", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean createNewWeatherAlert(int userId, Integer cityId, String cityName) { public boolean createNewWeatherAlert(long userId, Integer cityId, String cityName) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO WeatherAlert (userId, cityId, cityName) VALUES (?,?,?)"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("INSERT INTO WeatherAlert (userId, cityId, cityName) VALUES (?,?,?)");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setInt(2, cityId); preparedStatement.setInt(2, cityId);
preparedStatement.setString(3, cityName); preparedStatement.setString(3, cityName);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error creating weather alert", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public List<String> getAlertCitiesNameByUser(int userId) { public List<String> getAlertCitiesNameByUser(long userId) {
List<String> alertCitiesNames = new ArrayList<>(); List<String> alertCitiesNames = new ArrayList<>();
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("select cityName FROM WeatherAlert WHERE userId=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("select cityName FROM WeatherAlert WHERE userId=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
final ResultSet result = preparedStatement.executeQuery(); final ResultSet result = preparedStatement.executeQuery();
while (result.next()) { while (result.next()) {
alertCitiesNames.add(result.getString("cityName")); alertCitiesNames.add(result.getString("cityName"));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting alerts by user", e);
} }
return alertCitiesNames; return alertCitiesNames;
} }
public boolean deleteAlertCity(Integer userId, String cityName) { public boolean deleteAlertCity(Long userId, String cityName) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM WeatherAlert WHERE userId=? AND cityName=?;"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM WeatherAlert WHERE userId=? AND cityName=?;");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
preparedStatement.setString(2, cityName); preparedStatement.setString(2, cityName);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error delete city alert", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
public boolean deleteAlertsForUser(Integer userId) { public boolean deleteAlertsForUser(Long userId) {
int updatedRows = 0; int updatedRows = 0;
try { try {
final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM WeatherAlert WHERE userId=?"); final PreparedStatement preparedStatement = connetion.getPreparedStatement("DELETE FROM WeatherAlert WHERE userId=?");
preparedStatement.setInt(1, userId); preparedStatement.setLong(1, userId);
updatedRows = preparedStatement.executeUpdate(); updatedRows = preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error deleting alerts for user", e);
} }
return updatedRows > 0; return updatedRows > 0;
} }
@ -630,7 +652,7 @@ public class DatabaseManager {
allAlerts.add(weatherAlert); allAlerts.add(weatherAlert);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Error getting all alerts", e);
} }
return allAlerts; return allAlerts;

44
src/main/java/org/telegram/services/CustomTimerTask.java

@ -1,11 +1,15 @@
package org.telegram.services; package org.telegram.services;
import lombok.Getter;
import lombok.Setter;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 2.0 * @version 2.0
* @brief Task to be execute periodically * Task to be executed periodically
* @date 28/01/15
*/ */
@Setter
@Getter
public abstract class CustomTimerTask { public abstract class CustomTimerTask {
private String taskName = ""; ///< Task name private String taskName = ""; ///< Task name
private int times = 1; private int times = 1;
@ -20,42 +24,6 @@ public abstract class CustomTimerTask {
this.times = times; this.times = times;
} }
/**
* Get name
*
* @return name
*/
public String getTaskName() {
return this.taskName;
}
/**
* Set name
*
* @param taskName new name
*/
public void setTaskName(String taskName) {
this.taskName = taskName;
}
/**
* Getter for the times
*
* @return Remainint times the task must be executed
*/
public int getTimes() {
return this.times;
}
/**
* Setter for the times
*
* @param times Number of times the task must be executed
*/
public void setTimes(int times) {
this.times = times;
}
public void reduceTimes() { public void reduceTimes() {
if (this.times > 0) { if (this.times > 0) {
this.times -= 1; this.times -= 1;

44
src/main/java/org/telegram/services/DirectionsService.java

@ -1,14 +1,10 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import okhttp3.OkHttpClient;
import org.apache.http.HttpResponse; import okhttp3.Request;
import org.apache.http.client.HttpClient; import okhttp3.Response;
import org.apache.http.client.methods.HttpGet; import okhttp3.ResponseBody;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
@ -16,6 +12,7 @@ import org.telegram.BuildVars;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -23,8 +20,7 @@ import java.util.List;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Weather service * Weather service
* @date 20 of June of 2015
*/ */
@Slf4j @Slf4j
public class DirectionsService { public class DirectionsService {
@ -72,15 +68,18 @@ public class DirectionsService {
try { try {
String completURL = BASEURL + "?origin=" + getQuery(origin) + "&destination=" + String completURL = BASEURL + "?origin=" + getQuery(origin) + "&destination=" +
getQuery(destination) + PARAMS.replace("@language@", language) + APIIDEND; getQuery(destination) + PARAMS.replace("@language@", language) + APIIDEND;
HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
HttpGet request = new HttpGet(completURL); Request request = new Request.Builder()
HttpResponse response = client.execute(request); .url(completURL)
HttpEntity ht = response.getEntity(); .header("charset", StandardCharsets.UTF_8.name())
.header("content-type", "application/json")
BufferedHttpEntity buf = new BufferedHttpEntity(ht); .get()
String responseContent = EntityUtils.toString(buf, "UTF-8"); .build();
try (Response response = okHttpClient.newCall(request).execute()) {
JSONObject jsonObject = new JSONObject(responseContent); if (response.isSuccessful()) {
try (ResponseBody body = response.body()) {
if (body != null) {
JSONObject jsonObject = new JSONObject(body.string());
if (jsonObject.getString("status").equals("OK")) { if (jsonObject.getString("status").equals("OK")) {
JSONObject route = jsonObject.getJSONArray("routes").getJSONObject(0); JSONObject route = jsonObject.getJSONArray("routes").getJSONObject(0);
String startOfAddress = LocalisationService.getString("directionsInit", language); String startOfAddress = LocalisationService.getString("directionsInit", language);
@ -96,8 +95,13 @@ public class DirectionsService {
} else { } else {
responseToUser.add(LocalisationService.getString("directionsNotFound", language)); responseToUser.add(LocalisationService.getString("directionsNotFound", language));
} }
} else {
}
}
}
}
} catch (Exception e) { } catch (Exception e) {
log.warn(e.getLocalizedMessage(), e); log.warn("Error getting directions", e);
responseToUser.add(LocalisationService.getString("errorFetchingDirections", language)); responseToUser.add(LocalisationService.getString("errorFetchingDirections", language));
} }
return responseToUser; return responseToUser;

120
src/main/java/org/telegram/services/RaeService.java

@ -1,14 +1,10 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import okhttp3.OkHttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import okhttp3.Request;
import org.apache.http.client.methods.HttpGet; import okhttp3.Response;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import okhttp3.ResponseBody;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
@ -16,16 +12,17 @@ import org.jsoup.select.Elements;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Rae service * Rae service
* @date 20 of June of 2015
*/ */
@Slf4j @Slf4j
public class RaeService { public class RaeService {
@ -34,24 +31,27 @@ public class RaeService {
private static final String SEARCHWORDURL = "search?m=form&w="; private static final String SEARCHWORDURL = "search?m=form&w=";
private static final String WORDLINKBYID = "http://dle.rae.es/?id="; private static final String WORDLINKBYID = "http://dle.rae.es/?id=";
private final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
public List<RaeResult> getResults(String query) { public List<RaeResult> getResults(String query) {
List<RaeResult> results = new ArrayList<>(); List<RaeResult> results = new ArrayList<>();
String completeURL; String completeURL;
try { try {
completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8"); completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, StandardCharsets.UTF_8);
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completeURL); .url(completeURL)
.header("charset", StandardCharsets.UTF_8.name())
CloseableHttpResponse response = client.execute(request); .header("content-type", "application/json")
HttpEntity ht = response.getEntity(); .get()
.build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8"); try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
Document document = Jsoup.parse(responseString); try (ResponseBody body = response.body()) {
if (body != null) {
Document document = Jsoup.parse(body.string());
Element article = document.getElementsByTag("article").first(); Element article = document.getElementsByTag("article").first();
String articleId = null; String articleId = null;
if (article != null) { if (article != null) {
@ -64,8 +64,12 @@ public class RaeService {
} else { } else {
results = getResultsFromExactMatch(elements, query, articleId); results = getResultsFromExactMatch(elements, query, articleId);
} }
}
}
}
}
} catch (IOException e) { } catch (IOException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error getting RAE results", e);
} }
return results; return results;
@ -76,33 +80,38 @@ public class RaeService {
String completeURL; String completeURL;
try { try {
completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8"); completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, StandardCharsets.UTF_8);
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completeURL); .url(completeURL)
.header("charset", StandardCharsets.UTF_8.name())
CloseableHttpResponse response = client.execute(request); .get()
HttpEntity ht = response.getEntity(); .build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); try (Response response = okHttpClient.newCall(request).execute()) {
String responseString = EntityUtils.toString(buf, "UTF-8"); if (response.isSuccessful()) {
try (ResponseBody body = response.body()) {
Document document = Jsoup.parse(responseString); if (body != null) {
Document document = Jsoup.parse(body.string());
Element list = document.select("body div ul").first(); Element list = document.select("body div ul").first();
if (list != null) { if (list != null) {
Elements links = list.getElementsByTag("a"); Elements links = list.getElementsByTag("a");
if (!links.isEmpty()) { if (!links.isEmpty()) {
for (Element link : links) { for (Element link : links) {
List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), "UTF-8"), link.text()); List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), StandardCharsets.UTF_8), link.text());
if (!partialResults.isEmpty()) { if (!partialResults.isEmpty()) {
results.addAll(partialResults); results.addAll(partialResults);
} }
} }
} }
} }
}
}
}
}
} catch (IOException e) { } catch (IOException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error getting results from search", e);
} }
return results; return results;
@ -115,16 +124,17 @@ public class RaeService {
try { try {
completeURL = BASEURL + link; completeURL = BASEURL + link;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completeURL); .url(completeURL)
.header("charset", StandardCharsets.UTF_8.name())
CloseableHttpResponse response = client.execute(request); .get()
HttpEntity ht = response.getEntity(); .build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); try (Response response = okHttpClient.newCall(request).execute()) {
String responseString = EntityUtils.toString(buf, "UTF-8"); if (response.isSuccessful()) {
try (ResponseBody body = response.body()) {
Document document = Jsoup.parse(responseString); if (body != null) {
Document document = Jsoup.parse(body.string());
Element article = document.getElementsByTag("article").first(); Element article = document.getElementsByTag("article").first();
String articleId = null; String articleId = null;
if (article != null) { if (article != null) {
@ -135,8 +145,12 @@ public class RaeService {
if (!elements.isEmpty()) { if (!elements.isEmpty()) {
results = getResultsFromExactMatch(elements, word, articleId); results = getResultsFromExactMatch(elements, word, articleId);
} }
}
}
}
}
} catch (IOException e) { } catch (IOException e) {
log.error(e.getLocalizedMessage(), e); log.error("Fetching words", e);
} }
return results; return results;
@ -153,19 +167,19 @@ public class RaeService {
result.index = i; result.index = i;
result.word = capitalizeFirstLetter(word); result.word = capitalizeFirstLetter(word);
Elements tags = element.getElementsByTag("abbr"); Elements tags = element.getElementsByTag("abbr");
tags.removeIf(x -> !x.parent().equals(element)); tags.removeIf(x -> !Objects.equals(x.parent(), element));
for (Element tag : tags) { for (Element tag : tags) {
result.tags.put(tag.text(), tag.attributes().get("title")); result.tags.put(tag.text(), tag.attributes().get("title"));
} }
Elements definition = element.getElementsByTag("mark"); Elements definition = element.getElementsByTag("mark");
definition.removeIf(x -> !x.parent().equals(element)); definition.removeIf(x -> !Objects.equals(x.parent(), element));
if (definition.isEmpty()) { if (definition.isEmpty()) {
results.addAll(findResultsFromRedirect(element, word)); results.addAll(findResultsFromRedirect(element, word));
} else { } else {
StringBuilder definitionBuilder = new StringBuilder(); StringBuilder definitionBuilder = new StringBuilder();
definition.stream().forEachOrdered(y -> { definition.forEach(y -> {
String partialText = y.text(); String partialText = y.text();
if (definitionBuilder.length() > 0) { if (!definitionBuilder.isEmpty()) {
definitionBuilder.append(" "); definitionBuilder.append(" ");
partialText = partialText.toLowerCase(); partialText = partialText.toLowerCase();
} }
@ -191,7 +205,7 @@ public class RaeService {
} }
private static String capitalizeFirstLetter(String original) { private static String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) { if (original == null || original.isEmpty()) {
return original; return original;
} }
return original.substring(0, 1).toUpperCase() + original.substring(1); return original.substring(0, 1).toUpperCase() + original.substring(1);

8
src/main/java/org/telegram/services/TimerExecutor.java

@ -55,7 +55,7 @@ public class TimerExecutor {
* @param targetSec Second to execute it * @param targetSec Second to execute it
*/ */
public void startExecutionEveryDayAt(CustomTimerTask task, int targetHour, int targetMin, int targetSec) { public void startExecutionEveryDayAt(CustomTimerTask task, int targetHour, int targetMin, int targetSec) {
log.warn("Posting new task" + task.getTaskName()); log.warn("Posting new task {}", task.getTaskName());
final Runnable taskWrapper = () -> { final Runnable taskWrapper = () -> {
try { try {
task.execute(); task.execute();
@ -82,7 +82,7 @@ public class TimerExecutor {
private long computNextDilay(int targetHour, int targetMin, int targetSec) { private long computNextDilay(int targetHour, int targetMin, int targetSec) {
final LocalDateTime localNow = LocalDateTime.now(Clock.systemUTC()); final LocalDateTime localNow = LocalDateTime.now(Clock.systemUTC());
LocalDateTime localNextTarget = localNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec); LocalDateTime localNextTarget = localNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
while (localNow.compareTo(localNextTarget.minusSeconds(1)) > 0) { while (localNow.isAfter(localNextTarget.minusSeconds(1))) {
localNextTarget = localNextTarget.plusDays(1); localNextTarget = localNextTarget.plusDays(1);
} }
@ -103,9 +103,9 @@ public class TimerExecutor {
try { try {
executorService.awaitTermination(1, TimeUnit.DAYS); executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
log.error(ex.getLocalizedMessage(), ex); log.error("Task interrupted", ex);
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), "Bot threw an unexpected exception at TimerExecutor", e); log.error("Bot threw an unexpected exception at TimerExecutor", e);
} }
} }
} }

375
src/main/java/org/telegram/services/TransifexService.java

@ -1,375 +0,0 @@
package org.telegram.services;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.telegram.BuildVars;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
import org.telegram.telegrambots.meta.api.objects.InputFile;
import java.io.*;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Service that allow transifex files download
* @date 21 of June of 2015
*/
@Slf4j
public class TransifexService {
private static final String BASEURLAndroid = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram/resource/stringsxml-48/translation/@language?file"; ///< Base url for REST
private static final String BASEURLiOS = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/iphone-1/resource/localizablestrings/translation/@language?file"; ///< Base url for REST
private static final String BASEURLOSX = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/osx/resource/localizablestrings/translation/@language?file"; ///< Base url for REST
private static final String BASEURLTDesktop = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram-desktop/resource/langstrings/translation/@language?file"; ///< Base url for REST
private static final String BASEURLTemplates = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram-desktop/resource/tl_generaltxt/translation/@language?file"; ///< Base url for REST
private static final String BASEURLWebogram = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/telegram-web/resource/en-usjson/translation/@language?file"; ///< Base url for REST
private static final String BASEURLWP = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/wp-telegram-messenger-beta/resource/appresourcesresx/translation/@language?file"; ///< Base url for REST
private static final int STATUS200 = 200;
private static final int BYTES1024 = 1024;
private static volatile TransifexService instance; ///< Instance of this class
/**
* Constructor (private due to singleton pattern)
*/
private TransifexService() {
}
/**
* Singleton
*
* @return Return the instance of this class
*/
public static TransifexService getInstance() {
TransifexService currentInstance;
if (instance == null) {
synchronized (TransifexService.class) {
if (instance == null) {
instance = new TransifexService();
}
currentInstance = instance;
}
} else {
currentInstance = instance;
}
return currentInstance;
}
private String getFileAndroid(String query) {
String result = null;
try {
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(BASEURLAndroid.replace("@language", query));
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String line;
String responseString = "";
while ((line = rd.readLine()) != null) {
responseString += line;
}
if (response.getStatusLine().getStatusCode() == STATUS200) {
result = responseString;
}
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
private byte[] getFileiOS(String query) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLiOS.replace("@language", query));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
private byte[] getFileOSX(String query) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLOSX.replace("@language", query));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
private byte[] getFileTDesktop(String query) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLTDesktop.replace("@language", query));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
public byte[] getFileTemplate(String languageCode) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLTemplates.replace("@language", languageCode));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), "UTF-8");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
private byte[] getFileWebogram(String query) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLWebogram.replace("@language", query));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
private byte[] getFileWP(String query) {
byte[] result = null;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(BASEURLWP.replace("@language", query));
HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
return result;
}
/**
* For languages that are composited of a regional part, change that part to uper case for transifex
* @param language Language received
* @return Language fixed
*/
private String fixCaseCompositedLanguages(String language) {
String[] parts = language.split("_");
if (parts.length == 1) {
language = parts[0];
} else {
language = parts[0] + "_" + parts[1].toUpperCase();
}
return language;
}
/**
* Fetch the language file for support members of android
* @param language Language requested
*/
public SendDocument getAndroidSupportLanguageFile(String language) {
SendDocument sendDocument = null;
try {
String file = getFileAndroid(language);
if (file != null && file.getBytes().length / BYTES1024 >= 10) {
file = file.replaceAll("\"LanguageName\"\\>(\\w*)\\<\\/string\\>", "\"LanguageName\"\\>$1_1\\<\\/string\\>").replaceAll("\"LanguageCode\"\\>(\\w*)\\<\\/string\\>", "\"LanguageCode\"\\>$1_1\\<\\/string\\>");
try {
String fileName = "languages_Android_" + language + ".xml";
PrintWriter localFile = new PrintWriter(fileName);
localFile.print(file);
localFile.close();
File fileToUpload = new File(fileName);
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
} catch (FileNotFoundException e) {
log.error(e.getLocalizedMessage(), e);
}
}
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
return sendDocument;
}
/**
* Fetch the language file for Android
* @param language Language requested
*/
public SendDocument getAndroidLanguageFile(String language) {
SendDocument sendDocument = null;
try {
String file = getFileAndroid(language);
if (file != null && file.getBytes().length / BYTES1024 >= 10) {
try {
String fileName = "languages_Android_" + language + ".xml";
PrintWriter localFile = new PrintWriter(fileName);
localFile.print(file);
localFile.close();
File fileToUpload = new File(fileName);
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
} catch (FileNotFoundException e) {
log.error(e.getLocalizedMessage(), e);
}
}
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
return sendDocument;
}
/**
* Fetch the language file for iOS
*
* @param language Language requested
*/
public SendDocument getiOSLanguageFile(String language) {
SendDocument sendDocument = null;
try {
byte[] file = getFileiOS(language);
if (file != null && file.length / BYTES1024 >= 10) {
try {
String fileName = "languages_ios_" + language + ".strings";
File fileToUpload = new File(fileName);
FileOutputStream output = new FileOutputStream(fileToUpload);
IOUtils.write(file, output);
output.close();
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
}
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
return sendDocument;
}
/**
* Fetch the language file for OSX
* @param language Language requested
*/
public SendDocument getOSXLanguageFile(String language) {
SendDocument sendDocument = null;
try {
byte[] file = getFileOSX(language);
if (file != null && file.length / BYTES1024 >= 10) {
try {
String fileName = "languages_osx_" + language + ".strings";
File fileToUpload = new File(fileName);
FileOutputStream output = new FileOutputStream(fileToUpload);
IOUtils.write(file, output);
output.close();
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
}
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
}
return sendDocument;
}
/**
* Fetch the language file for Tdesktop
* @param language Language requested
*/
public SendDocument getTdesktopLanguageFile(String language) {
SendDocument sendDocument = null;
try {
byte[] file = getFileTDesktop(language);
if (file != null && file.length / BYTES1024 >= 10) {
try {
String fileName = "languages_tdesktop_" + language + ".strings";
File fileToUpload = new File(fileName);
FileOutputStream output = new FileOutputStream(fileToUpload);
IOUtils.write(file, output);
output.close();
if (fileToUpload.exists()) {
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sendDocument;
}
/**
* Fetch the language file for Webogram
* @param language Language requested
*/
public SendDocument getWebogramLanguageFile(String language) {
SendDocument sendDocument = null;
try {
byte[] file = getFileWebogram(language);
if (file != null && file.length / BYTES1024 >= 10) {
try {
String fileName = "languages_webogram_" + language + ".json";
File fileToUpload = new File(fileName);
FileOutputStream output = new FileOutputStream(fileToUpload);
IOUtils.write(file, output);
output.close();
if (fileToUpload.exists()) {
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sendDocument;
}
/**
* Fetch the language file for WP
* @param language Language requested
*/
public SendDocument getWPLanguageFile(String language) {
SendDocument sendDocument = null;
try {
byte[] file = getFileWP(language);
if (file != null && file.length / BYTES1024 >= 10) {
try {
String fileName = "languages_wp_" + language + ".xml";
File fileToUpload = new File(fileName);
FileOutputStream output = new FileOutputStream(fileToUpload);
IOUtils.write(file, output);
output.close();
if (fileToUpload.exists()) {
sendDocument = new SendDocument();
sendDocument.setDocument(new InputFile(fileToUpload));
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sendDocument;
}
}

218
src/main/java/org/telegram/services/WeatherService.java

@ -1,20 +1,17 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import okhttp3.OkHttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import okhttp3.Request;
import org.apache.http.client.methods.HttpGet; import okhttp3.Response;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import okhttp3.ResponseBody;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId; import java.time.ZoneId;
@ -23,8 +20,7 @@ import java.time.format.DateTimeFormatter;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Weather service * Weather service
* @date 20 of June of 2015
*/ */
@Slf4j @Slf4j
public class WeatherService { public class WeatherService {
@ -41,6 +37,8 @@ public class WeatherService {
private static final DateTimeFormatter dateFormaterFromDate = DateTimeFormatter.ofPattern("dd/MM/yyyy"); ///< Date to text formater private static final DateTimeFormatter dateFormaterFromDate = DateTimeFormatter.ofPattern("dd/MM/yyyy"); ///< Date to text formater
private static volatile WeatherService instance; ///< Instance of this class private static volatile WeatherService instance; ///< Instance of this class
private final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
/** /**
* Constructor (private due to singleton pattern) * Constructor (private due to singleton pattern)
*/ */
@ -72,25 +70,26 @@ public class WeatherService {
* *
* @param cityId City to get the weather * @param cityId City to get the weather
* @return userHash to be send to use * @return userHash to be send to use
* @note Forecast for the day * @apiNote Forecast for the day
*/ */
public String fetchWeatherAlert(int cityId, int userId, String language, String units) { public String fetchWeatherAlert(int cityId, long userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(cityId + "") + String completeURL = BASEURL + FORECASTPATH + "?" + getCityQuery(cityId + "") +
ALERTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND; ALERTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completURL); .url(completeURL)
.header("charset", StandardCharsets.UTF_8.name())
CloseableHttpResponse response = client.execute(request); .get()
HttpEntity ht = response.getEntity(); .build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); try (Response response = okHttpClient.newCall(request).execute()) {
String responseString = EntityUtils.toString(buf, "UTF-8"); if (response.isSuccessful()) {
try (ResponseBody body = response.body()) {
JSONObject jsonObject = new JSONObject(responseString); if (body != null) {
log.info(jsonObject.toString()); JSONObject jsonObject = new JSONObject(body.string());
log.info("Alert fetched: {}", jsonObject);
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")"; jsonObject.getJSONObject("city").getString("country") + ")";
@ -98,11 +97,19 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getString("weatherAlert", language), responseToUser = String.format(LocalisationService.getString("weatherAlert", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, false)); cityFound, convertListOfForecastToString(jsonObject, language, units, false));
} else { } else {
log.warn(jsonObject.toString()); log.warn("Unable to read alerts fetched {}", jsonObject);
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error fetching alerts", e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -115,23 +122,24 @@ public class WeatherService {
* @return userHash to be send to use * @return userHash to be send to use
* @note Forecast for the following 3 days * @note Forecast for the following 3 days
*/ */
public String fetchWeatherForecast(String city, Integer userId, String language, String units) { public String fetchWeatherForecast(String city, Long userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(city) + String completeURL = BASEURL + FORECASTPATH + "?" + getCityQuery(city) +
FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND; FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completURL); .url(completeURL)
.header("charset", StandardCharsets.UTF_8.name())
CloseableHttpResponse response = client.execute(request); .get()
HttpEntity ht = response.getEntity(); .build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht); try (Response response = okHttpClient.newCall(request).execute()) {
String responseString = EntityUtils.toString(buf, "UTF-8"); if (response.isSuccessful()) {
try (ResponseBody body = response.body()) {
JSONObject jsonObject = new JSONObject(responseString); if (body != null) {
log.info(jsonObject.toString()); JSONObject jsonObject = new JSONObject(body.string());
log.info("Fetched weather forecast {}", jsonObject);
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")"; jsonObject.getJSONObject("city").getString("country") + ")";
@ -139,11 +147,19 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getString("weatherForcast", language), responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true)); cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else { } else {
log.warn(jsonObject.toString()); log.warn("City forecast not found {}", jsonObject);
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error fetching city forecast", e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -155,22 +171,24 @@ public class WeatherService {
* @return userHash to be send to use * @return userHash to be send to use
* @note Forecast for the following 3 days * @note Forecast for the following 3 days
*/ */
public String fetchWeatherForecastByLocation(Double longitude, Double latitude, Integer userId, String language, String units) { public String fetchWeatherForecastByLocation(Double longitude, Double latitude, Long userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
String completURL = BASEURL + FORECASTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon=" String completeURL = BASEURL + FORECASTPATH + "?lat=" + URLEncoder.encode(latitude + "", StandardCharsets.UTF_8) + "&lon="
+ URLEncoder.encode(longitude + "", "UTF-8") + + URLEncoder.encode(longitude + "", StandardCharsets.UTF_8) +
FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND; FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completURL); .url(completeURL)
CloseableHttpResponse response = client.execute(request); .header("charset", StandardCharsets.UTF_8.name())
HttpEntity ht = response.getEntity(); .get()
.build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8"); try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(responseString); try (ResponseBody body = response.body()) {
if (body != null) {
JSONObject jsonObject = new JSONObject(body.string());
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" + cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")"; jsonObject.getJSONObject("city").getString("country") + ")";
@ -178,11 +196,19 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getString("weatherForcast", language), responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true)); cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else { } else {
log.warn(jsonObject.toString()); log.warn("No forecast for location found {}", jsonObject);
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error fetching location forecast", e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -193,24 +219,26 @@ public class WeatherService {
* *
* @param city City to get the weather * @param city City to get the weather
* @return userHash to be send to use * @return userHash to be send to use
* @note Forecast for the following 3 days * @apiNote Forecast for the following 3 days
*/ */
public String fetchWeatherCurrent(String city, Integer userId, String language, String units) { public String fetchWeatherCurrent(String city, Long userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
Emoji emoji = null; Emoji emoji = null;
try { try {
String completURL = BASEURL + CURRENTPATH + "?" + getCityQuery(city) + String completeURL = BASEURL + CURRENTPATH + "?" + getCityQuery(city) +
CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND; CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completURL); .url(completeURL)
CloseableHttpResponse response = client.execute(request); .header("charset", StandardCharsets.UTF_8.name())
HttpEntity ht = response.getEntity(); .get()
.build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8"); try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(responseString); try (ResponseBody body = response.body()) {
if (body != null) {
JSONObject jsonObject = new JSONObject(body.string());
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getString("name") + " (" + cityFound = jsonObject.getString("name") + " (" +
jsonObject.getJSONObject("sys").getString("country") + ")"; jsonObject.getJSONObject("sys").getString("country") + ")";
@ -219,11 +247,19 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getString("weatherCurrent", language), responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji)); cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji));
} else { } else {
log.warn(jsonObject.toString()); log.warn("No current weather found {}", jsonObject);
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error fetching current weather", e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -235,22 +271,24 @@ public class WeatherService {
* @return userHash to be send to use * @return userHash to be send to use
* @note Forecast for the following 3 days * @note Forecast for the following 3 days
*/ */
public String fetchWeatherCurrentByLocation(Double longitude, Double latitude, Integer userId, String language, String units) { public String fetchWeatherCurrentByLocation(Double longitude, Double latitude, Long userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
String completURL = BASEURL + CURRENTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon=" String completeURL = BASEURL + CURRENTPATH + "?lat=" + URLEncoder.encode(latitude + "", StandardCharsets.UTF_8) + "&lon="
+ URLEncoder.encode(longitude + "", "UTF-8") + + URLEncoder.encode(longitude + "", StandardCharsets.UTF_8) +
CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND; CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Request request = new Request.Builder()
HttpGet request = new HttpGet(completURL); .url(completeURL)
CloseableHttpResponse response = client.execute(request); .header("charset", StandardCharsets.UTF_8.name())
HttpEntity ht = response.getEntity(); .get()
.build();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8"); try (Response response = okHttpClient.newCall(request).execute()) {
if (response.isSuccessful()) {
JSONObject jsonObject = new JSONObject(responseString); try (ResponseBody body = response.body()) {
if (body != null) {
JSONObject jsonObject = new JSONObject(body.string());
if (jsonObject.getInt("cod") == 200) { if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getString("name") + " (" + cityFound = jsonObject.getString("name") + " (" +
jsonObject.getJSONObject("sys").getString("country") + ")"; jsonObject.getJSONObject("sys").getString("country") + ")";
@ -258,11 +296,19 @@ public class WeatherService {
responseToUser = String.format(LocalisationService.getString("weatherCurrent", language), responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, null)); cityFound, convertCurrentWeatherToString(jsonObject, language, units, null));
} else { } else {
log.warn(jsonObject.toString()); log.warn("No weather found for location {}", jsonObject);
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} else {
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
}
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error fetching weather for location", e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -342,16 +388,16 @@ public class WeatherService {
return responseToUser; return responseToUser;
} }
private void saveRecentWeather(Integer userId, String cityName, int cityId) { private void saveRecentWeather(Long userId, String cityName, int cityId) {
DatabaseManager.getInstance().addRecentWeather(userId, cityId, cityName); DatabaseManager.getInstance().addRecentWeather(userId, cityId, cityName);
} }
private String getCityQuery(String city) throws UnsupportedEncodingException { private String getCityQuery(String city) throws UnsupportedEncodingException {
String cityQuery = ""; String cityQuery = "";
try { try {
cityQuery += "id=" + URLEncoder.encode(Integer.parseInt(city)+"", "UTF-8"); cityQuery += "id=" + URLEncoder.encode(Integer.parseInt(city)+"", StandardCharsets.UTF_8);
} catch(NumberFormatException | NullPointerException e) { } catch(NumberFormatException | NullPointerException e) {
cityQuery += "q=" + URLEncoder.encode(city, "UTF-8"); cityQuery += "q=" + URLEncoder.encode(city, StandardCharsets.UTF_8);
} }
return cityQuery; return cityQuery;
} }

35
src/main/java/org/telegram/structure/WeatherAlert.java

@ -1,40 +1,15 @@
package org.telegram.structure; package org.telegram.structure;
import lombok.Data;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Weather Alert representation * Weather Alert representation
* @date 23 of July of 2015
*/ */
@Data
public class WeatherAlert { public class WeatherAlert {
private int id; private int id;
private int userId; private long userId;
private int cityId; private int cityId;
public WeatherAlert() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
} }

80
src/main/java/org/telegram/updateshandlers/ChannelHandlers.java

@ -1,14 +1,15 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -16,12 +17,11 @@ import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for updates to channel updates bot * Handler for updates to channel updates bot
* This is a use case that will send a message to a channel if it is added as an admin to it. * This is a use case that will send a message to a channel if it is added as an admin to it.
* @date 24 of June of 2015
*/ */
@Slf4j @Slf4j
public class ChannelHandlers extends TelegramLongPollingBot { public class ChannelHandlers implements LongPollingSingleThreadUpdateConsumer {
private static final int WAITINGCHANNEL = 1; private static final int WAITINGCHANNEL = 1;
private static final String HELP_TEXT = "Send me the channel username where you added me as admin."; private static final String HELP_TEXT = "Send me the channel username where you added me as admin.";
@ -31,36 +31,29 @@ public class ChannelHandlers extends TelegramLongPollingBot {
private static final String CHANNEL_MESSAGE_TEXT = "This message was sent by *@updateschannelbot*. Enjoy!"; private static final String CHANNEL_MESSAGE_TEXT = "This message was sent by *@updateschannelbot*. Enjoy!";
private static final String ERROR_MESSAGE_TEXT = "There was an error sending the message to channel *%s*, the error was: ```%s```"; private static final String ERROR_MESSAGE_TEXT = "There was an error sending the message to channel *%s*, the error was: ```%s```";
private final ConcurrentHashMap<Integer, Integer> userState = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Long, Integer> userState = new ConcurrentHashMap<>();
private final TelegramClient telegramClient;
public ChannelHandlers(String botToken) {
telegramClient = new OkHttpTelegramClient(botToken);
}
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
try { try {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
try { try {
handleIncomingMessage(message); handleIncomingMessage(message);
} catch (InvalidObjectException e) { } catch (InvalidObjectException e) {
log.error(e.getLocalizedMessage(), e); log.error("Channel Handler Error", e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error handling channel message", e);
} }
} }
@Override
public String getBotToken() {
return BotConfig.CHANNEL_TOKEN;
}
@Override
public String getBotUsername() {
return BotConfig.CHANNEL_USER;
}
// region Incoming messages handlers // region Incoming messages handlers
private void handleIncomingMessage(Message message) throws InvalidObjectException { private void handleIncomingMessage(Message message) throws InvalidObjectException {
@ -76,95 +69,80 @@ public class ChannelHandlers extends TelegramLongPollingBot {
} }
} }
private void onWaitingChannelMessage(Message message) throws InvalidObjectException { private void onWaitingChannelMessage(Message message) {
try { try {
if (message.getText().equals(CANCEL_COMMAND)) { if (message.getText().equals(CANCEL_COMMAND)) {
userState.remove(message.getFrom().getId()); userState.remove(message.getFrom().getId());
sendHelpMessage(message.getChatId(), message.getMessageId(), null); sendHelpMessage(message.getChatId(), message.getMessageId(), null);
} else { } else {
if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) { if (message.getText().startsWith("@") && !message.getText().trim().contains(" ")) {
execute(getMessageToChannelSent(message)); telegramClient.execute(getMessageToChannelSent(message));
sendMessageToChannel(message.getText(), message); sendMessageToChannel(message.getText(), message);
userState.remove(message.getFrom().getId()); userState.remove(message.getFrom().getId());
} else { } else {
execute(getWrongUsernameMessage(message)); telegramClient.execute(getWrongUsernameMessage(message));
} }
} }
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error waiting channel message", e);
} }
} }
private void sendMessageToChannel(String username, Message message) { private void sendMessageToChannel(String username, Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(username.trim(), CHANNEL_MESSAGE_TEXT);
sendMessage.enableMarkdown(true);
sendMessage.setChatId(username.trim());
sendMessage.setText(CHANNEL_MESSAGE_TEXT);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
try { try {
execute(sendMessage); telegramClient.execute(sendMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
sendErrorMessage(message, e.getMessage()); sendErrorMessage(message, e.getMessage());
} }
} }
private void sendErrorMessage(Message message, String errorText) { private void sendErrorMessage(Message message, String errorText) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), String.format(ERROR_MESSAGE_TEXT, message.getText().trim(), errorText.replace("\"", "\\\"")));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(String.format(ERROR_MESSAGE_TEXT, message.getText().trim(), errorText.replace("\"", "\\\"")));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
try { try {
execute(sendMessage); telegramClient.execute(sendMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error sending error message", e);
} }
} }
private static SendMessage getWrongUsernameMessage(Message message) { private static SendMessage getWrongUsernameMessage(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), WRONG_CHANNEL_TEXT);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true); forceReplyKeyboard.setSelective(true);
sendMessage.setReplyMarkup(forceReplyKeyboard); sendMessage.setReplyMarkup(forceReplyKeyboard);
sendMessage.setText(WRONG_CHANNEL_TEXT);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
return sendMessage; return sendMessage;
} }
private static SendMessage getMessageToChannelSent(Message message) { private static SendMessage getMessageToChannelSent(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), AFTER_CHANNEL_TEXT);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(AFTER_CHANNEL_TEXT);
return sendMessage; return sendMessage;
} }
private void sendHelpMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) { private void sendHelpMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(chatId), HELP_TEXT);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
} }
sendMessage.setText(HELP_TEXT);
try { try {
execute(sendMessage); telegramClient.execute(sendMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error sending help message", e);
} }
} }
} }

49
src/main/java/org/telegram/updateshandlers/CommandsHandler.java

@ -1,17 +1,17 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.commands.HelloCommand; import org.telegram.commands.HelloCommand;
import org.telegram.commands.HelpCommand; import org.telegram.commands.HelpCommand;
import org.telegram.commands.StartCommand; import org.telegram.commands.StartCommand;
import org.telegram.commands.StopCommand; import org.telegram.commands.StopCommand;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.Emoji; import org.telegram.services.Emoji;
import org.telegram.telegrambots.extensions.bots.commandbot.TelegramLongPollingCommandBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.extensions.bots.commandbot.CommandLongPollingTelegramBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
/** /**
@ -20,43 +20,32 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@Slf4j @Slf4j
public class CommandsHandler extends TelegramLongPollingCommandBot { public class CommandsHandler extends CommandLongPollingTelegramBot {
private final String botUsername;
/** /**
* Constructor. * Constructor.
*/ */
public CommandsHandler(String botUsername) { public CommandsHandler(String botToken, String botUsername) {
super(); super(new OkHttpTelegramClient(botToken), true, () -> botUsername);
this.botUsername = botUsername;
register(new HelloCommand()); register(new HelloCommand());
register(new StartCommand()); register(new StartCommand());
register(new StopCommand()); register(new StopCommand());
HelpCommand helpCommand = new HelpCommand(this); HelpCommand helpCommand = new HelpCommand(this);
register(helpCommand); register(helpCommand);
registerDefaultAction((absSender, message) -> { registerDefaultAction((telegramClient, message) -> {
SendMessage commandUnknownMessage = new SendMessage(); SendMessage commandUnknownMessage = new SendMessage(String.valueOf(message.getChatId()),
commandUnknownMessage.setChatId(Long.toString(message.getChatId())); "The command '" + message.getText() + "' is not known by this bot. Here comes some help " + Emoji.AMBULANCE);
commandUnknownMessage.setText("The command '" + message.getText() + "' is not known by this bot. Here comes some help " + Emoji.AMBULANCE);
try { try {
absSender.execute(commandUnknownMessage); telegramClient.execute(commandUnknownMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error sending message in commands bot", e);
} }
helpCommand.execute(absSender, message.getFrom(), message.getChat(), new String[] {}); helpCommand.execute(telegramClient, message.getFrom(), message.getChat(), new String[] {});
}); });
} }
@Override
public String getBotUsername() {
return botUsername;
}
@Override @Override
public void processNonCommandUpdate(Update update) { public void processNonCommandUpdate(Update update) {
if (update.hasMessage()) { if (update.hasMessage()) {
Message message = update.getMessage(); Message message = update.getMessage();
@ -65,21 +54,13 @@ public class CommandsHandler extends TelegramLongPollingCommandBot {
} }
if (message.hasText()) { if (message.hasText()) {
SendMessage echoMessage = new SendMessage(); SendMessage echoMessage = new SendMessage(String.valueOf(message.getChatId()), "Hey heres your message:\n" + message.getText());
echoMessage.setChatId(Long.toString(message.getChatId()));
echoMessage.setText("Hey heres your message:\n" + message.getText());
try { try {
execute(echoMessage); telegramClient.execute(echoMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error processing non-command update", e);
}
} }
} }
} }
@Override
public String getBotToken() {
return BotConfig.COMMANDS_TOKEN;
} }
} }

163
src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java

@ -1,23 +1,21 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.DirectionsService; import org.telegram.services.DirectionsService;
import org.telegram.services.LocalisationService; import org.telegram.services.LocalisationService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.generics.TelegramClient;
import org.telegram.telegrambots.meta.updateshandlers.SentCallback;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,33 +25,26 @@ import java.util.concurrent.ConcurrentLinkedQueue;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for updates to Directions Bot * Handler for updates to Directions Bot
* @date 24 of June of 2015
*/ */
@Slf4j @Slf4j
public class DirectionsHandlers extends TelegramLongPollingBot { public class DirectionsHandlers implements LongPollingSingleThreadUpdateConsumer {
private static final int WATING_ORIGIN_STATUS = 0; private static final int WATING_ORIGIN_STATUS = 0;
private static final int WATING_DESTINY_STATUS = 1; private static final int WATING_DESTINY_STATUS = 1;
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Long> languageMessages = new ConcurrentLinkedQueue<>();
private final TelegramClient telegramClient;
public DirectionsHandlers(String botToken) {
@Override telegramClient = new OkHttpTelegramClient(botToken);
public String getBotToken() {
return BotConfig.DIRECTIONS_TOKEN;
} }
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
try { try {
handleDirections(update); handleDirections(update);
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error processing update in directions bot", e);
}
} }
@Override
public String getBotUsername() {
return BotConfig.DIRECTIONS_USER;
} }
private void handleDirections(Update update) throws InvalidObjectException { private void handleDirections(Update update) throws InvalidObjectException {
@ -85,13 +76,11 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId()) == -1) { if (DatabaseManager.getInstance().getUserDestinationStatus(message.getFrom().getId()) == -1) {
sendHelpMessage(message, language); sendHelpMessage(message, language);
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("youNeedReplyDirections", language));
sendMessageRequest.setText(LocalisationService.getString("youNeedReplyDirections", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); telegramClient.execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error handling directions", e);
} }
} }
} }
@ -104,122 +93,78 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
String origin = DatabaseManager.getInstance().getUserOrigin(message.getFrom().getId()); String origin = DatabaseManager.getInstance().getUserOrigin(message.getFrom().getId());
String destiny = message.getText(); String destiny = message.getText();
List<String> directions = DirectionsService.getInstance().getDirections(origin, destiny, language); List<String> directions = DirectionsService.getInstance().getDirections(origin, destiny, language);
SendMessage sendMessageRequest = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageRequestBuilder = SendMessage.builder();
sendMessageRequest.setChatId(Long.toString(message.getChatId())); sendMessageRequestBuilder.chatId(message.getChatId());
ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove(); ReplyKeyboardRemove replyKeyboardRemove = ReplyKeyboardRemove.builder().selective(true).build();
replyKeyboardRemove.setSelective(true); sendMessageRequestBuilder.replyMarkup(replyKeyboardRemove);
sendMessageRequest.setReplyMarkup(replyKeyboardRemove); sendMessageRequestBuilder.replyToMessageId(message.getMessageId());
sendMessageRequest.setReplyToMessageId(message.getMessageId());
for (String direction : directions) { for (String direction : directions) {
sendMessageRequest.setText(direction); sendMessageRequestBuilder.text(direction);
try { try {
executeAsync(sendMessageRequest, new SentCallback<Message>() { telegramClient.executeAsync(sendMessageRequestBuilder.build()).thenAccept(sentMessage -> {
@Override
public void onResult(BotApiMethod<Message> botApiMethod, Message sentMessage) {
if (sentMessage != null) { if (sentMessage != null) {
DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForDirections(message.getFrom().getId());
} }
} }).thenAccept(unused -> log.info("Sent destination received"));
@Override
public void onError(BotApiMethod<Message> botApiMethod, TelegramApiRequestException e) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
}
});
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error on destination received", e);
} }
} }
} }
private void onOriginReceived(Message message, String language) { private void onOriginReceived(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("sendDestination", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true); forceReplyKeyboard.setSelective(true);
sendMessageRequest.setReplyMarkup(forceReplyKeyboard); sendMessageRequest.setReplyMarkup(forceReplyKeyboard);
sendMessageRequest.setText(LocalisationService.getString("sendDestination", language));
try { try {
executeAsync(sendMessageRequest, new SentCallback<Message>() { telegramClient.executeAsync(sendMessageRequest).thenAccept(sentMessage -> {
@Override
public void onResult(BotApiMethod<Message> method, Message sentMessage) {
if (sentMessage != null) { if (sentMessage != null) {
DatabaseManager.getInstance().addUserForDirection(message.getFrom().getId(), WATING_DESTINY_STATUS, DatabaseManager.getInstance().addUserForDirection(message.getFrom().getId(), WATING_DESTINY_STATUS,
sentMessage.getMessageId(), message.getText()); sentMessage.getMessageId(), message.getText());
} }
} }).thenAccept(unused -> log.info("Sent origin received"));
@Override
public void onError(BotApiMethod<Message> botApiMethod, TelegramApiRequestException e) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
}
});
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error on origin received", e);
} }
} }
private void sendHelpMessage(Message message, String language) throws InvalidObjectException { private void sendHelpMessage(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage();
String helpDirectionsFormated = String.format( String helpDirectionsFormated = String.format(
LocalisationService.getString("helpDirections", language), LocalisationService.getString("helpDirections", language),
Commands.startDirectionCommand); Commands.startDirectionCommand);
sendMessageRequest.setText(helpDirectionsFormated); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), helpDirectionsFormated);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); telegramClient.execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error sending help", e);
} }
} }
private void onStartdirectionsCommand(Message message, String language) { private void onStartdirectionsCommand(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("initDirections", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
forceReplyKeyboard.setSelective(true); forceReplyKeyboard.setSelective(true);
sendMessageRequest.setReplyMarkup(forceReplyKeyboard); sendMessageRequest.setReplyMarkup(forceReplyKeyboard);
sendMessageRequest.setText(LocalisationService.getString("initDirections", language));
try { try {
executeAsync(sendMessageRequest, new SentCallback<Message>() { telegramClient.executeAsync(sendMessageRequest).thenAccept(sentMessage -> {
@Override
public void onResult(BotApiMethod<Message> method, Message sentMessage) {
if (sentMessage != null) { if (sentMessage != null) {
DatabaseManager.getInstance().addUserForDirection(message.getFrom().getId(), WATING_ORIGIN_STATUS, DatabaseManager.getInstance().addUserForDirection(message.getFrom().getId(), WATING_ORIGIN_STATUS,
sentMessage.getMessageId(), null); sentMessage.getMessageId(), null);
} }
} }).thenAccept(unused -> log.info("Sent start directions"));
@Override
public void onError(BotApiMethod<Message> botApiMethod, TelegramApiRequestException e) {
}
@Override
public void onException(BotApiMethod<Message> botApiMethod, Exception e) {
}
});
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error on start directions", e);
} }
} }
private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException { private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("chooselanguage", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId())); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
List<LocalisationService.Language> languages = LocalisationService.getSupportedLanguages(); List<LocalisationService.Language> languages = LocalisationService.getSupportedLanguages();
List<KeyboardRow> commands = new ArrayList<>(); List<KeyboardRow> commands = new ArrayList<>();
for (LocalisationService.Language languageItem : languages) { for (LocalisationService.Language languageItem : languages) {
@ -227,39 +172,37 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
commandRow.add(languageItem.getCode() + " --> " + languageItem.getName()); commandRow.add(languageItem.getCode() + " --> " + languageItem.getName());
commands.add(commandRow); commands.add(commandRow);
} }
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkupBuilder.oneTimeKeyboard(true);
replyKeyboardMarkup.setKeyboard(commands); replyKeyboardMarkupBuilder.keyboard(commands);
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
sendMessageRequest.setReplyMarkup(replyKeyboardMarkup); sendMessageRequest.setReplyMarkup(replyKeyboardMarkupBuilder.build());
sendMessageRequest.setText(LocalisationService.getString("chooselanguage", language));
try { try {
execute(sendMessageRequest); telegramClient.execute(sendMessageRequest);
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error setting language", e);
} }
} }
private void onLanguageSelected(Message message) throws InvalidObjectException { private void onLanguageSelected(Message message) throws InvalidObjectException {
String[] parts = message.getText().split("-->", 2); String[] parts = message.getText().split("-->", 2);
SendMessage sendMessageRequest = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageRequestBuilder = SendMessage.builder();
sendMessageRequest.setChatId(Long.toString(message.getChatId())); sendMessageRequestBuilder.chatId(message.getChatId());
if (LocalisationService.getLanguageByCode(parts[0].trim()) != null) { if (LocalisationService.getLanguageByCode(parts[0].trim()) != null) {
DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
sendMessageRequest.setText(LocalisationService.getString("languageModified", parts[0].trim())); sendMessageRequestBuilder.text(LocalisationService.getString("languageModified", parts[0].trim()));
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("errorLanguage")); sendMessageRequestBuilder.text(LocalisationService.getString("errorLanguage"));
} }
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequestBuilder.replyToMessageId(message.getMessageId());
ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove(); ReplyKeyboardRemove replyKeyboardRemove = ReplyKeyboardRemove.builder().selective(true).build();
replyKeyboardRemove.setSelective(true); sendMessageRequestBuilder.replyMarkup(replyKeyboardRemove);
sendMessageRequest.setReplyMarkup(replyKeyboardRemove);
try { try {
execute(sendMessageRequest); telegramClient.execute(sendMessageRequestBuilder.build());
languageMessages.remove(message.getFrom().getId()); languageMessages.remove(message.getFrom().getId());
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error on lanaguage selected", e);
} }
} }
} }

110
src/main/java/org/telegram/updateshandlers/ElektrollArtFanHandler.java

@ -1,47 +1,47 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import org.telegram.BotConfig; import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
/** /**
* @author Clevero * @author Clevero
* @version 1.0 * @version 1.0
* @brief Handler for updates to ElektrollArtFanBot * Handler for updates to ElektrollArtFanBot
* This bot is an example for using inline buttons, here to make a gallery. * This bot is an example for using inline buttons, here to make a gallery.
* Bot contains some images from ElektrollArt that are all licensed under creative commons * Bot contains some images from ElektrollArt that are all licensed under creative commons
* @date 28 of October of 2016
*/ */
public class ElektrollArtFanHandler extends TelegramLongPollingBot { @Slf4j
public class ElektrollArtFanHandler implements LongPollingSingleThreadUpdateConsumer {
private ArrayList<String[]> urls; private final ArrayList<String[]> urls;
final private String BACK = "⬅️ Back"; private final String BACK = "⬅️ Back";
final private String NEXT = "Next ➡️"; private final String NEXT = "Next ➡️";
final private String INDEX_OUT_OF_RANGE = "Requested index is out of range!"; private final String INDEX_OUT_OF_RANGE = "Requested index is out of range!";
public ElektrollArtFanHandler() { private final TelegramClient telegramClient;
public ElektrollArtFanHandler(String botToken) {
telegramClient = new OkHttpTelegramClient(botToken);
this.urls = new ArrayList<>(); this.urls = new ArrayList<>();
this.addUrls(); this.addUrls();
} }
@Override
public String getBotUsername() {
return BotConfig.ELEKTROLLART_USER;
}
private void addUrls(){ private void addUrls(){
/* /*
@ -65,7 +65,7 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
} }
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
//check if the update has a message //check if the update has a message
if (update.hasMessage()) { if (update.hasMessage()) {
@ -76,28 +76,25 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
String input = message.getText(); String input = message.getText();
if (input.equals("/start")) { if (input.equals("/start")) {
SendMessage sendMessagerequest = new SendMessage();
sendMessagerequest.setChatId(message.getChatId().toString());
/* /*
* we just add the first link from our array * we just add the first link from our array
* *
* We use markdown to embedd the image * We use markdown to embedd the image
*/ */
sendMessagerequest.setText("[​](" + this.urls.get(0)[1] + ")"); SendMessage sendMessagerequest = new SendMessage(message.getChatId().toString(), "[​](" + this.urls.get(0)[1] + ")");
sendMessagerequest.enableMarkdown(true); sendMessagerequest.enableMarkdown(true);
sendMessagerequest.setReplyMarkup(this.getGalleryView(0, -1)); sendMessagerequest.setReplyMarkup(this.getGalleryView(0, -1));
try { try {
execute(sendMessagerequest); telegramClient.execute(sendMessagerequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); log.error("Error sending start message", e);
}
} }
} }
} }
else if(update.hasCallbackQuery()){ } else if (update.hasCallbackQuery()) {
CallbackQuery callbackquery = update.getCallbackQuery(); CallbackQuery callbackquery = update.getCallbackQuery();
String[] data = callbackquery.getData().split(":"); String[] data = callbackquery.getData().split(":");
int index = Integer.parseInt(data[2]); int index = Integer.parseInt(data[2]);
@ -120,7 +117,7 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
try { try {
this.sendAnswerCallbackQuery("Please use one of the given actions below, instead.", false, callbackquery); this.sendAnswerCallbackQuery("Please use one of the given actions below, instead.", false, callbackquery);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); log.error("Send text response", e);
} }
} }
@ -128,30 +125,26 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
try { try {
this.sendAnswerCallbackQuery(INDEX_OUT_OF_RANGE, false, callbackquery); this.sendAnswerCallbackQuery(INDEX_OUT_OF_RANGE, false, callbackquery);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); log.error("Send index out of range response", e);
} }
} else { } else {
EditMessageText editMarkup = new EditMessageText(); EditMessageText editMarkup = new EditMessageText("[​](" + this.urls.get(index)[1] + ")");
editMarkup.setChatId(callbackquery.getMessage().getChatId().toString()); editMarkup.setChatId(callbackquery.getMessage().getChatId().toString());
editMarkup.setInlineMessageId(callbackquery.getInlineMessageId()); editMarkup.setInlineMessageId(callbackquery.getInlineMessageId());
editMarkup.setText("[​](" + this.urls.get(index)[1] + ")");
editMarkup.enableMarkdown(true); editMarkup.enableMarkdown(true);
editMarkup.setMessageId(callbackquery.getMessage().getMessageId()); editMarkup.setMessageId(callbackquery.getMessage().getMessageId());
editMarkup.setReplyMarkup(markup); editMarkup.setReplyMarkup(markup);
try { try {
execute(editMarkup); telegramClient.execute(editMarkup);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
e.printStackTrace(); log.error("Error updating markup", e);
} }
} }
} }
} }
} }
/** /**
* *
* @param text The text that should be shown * @param text The text that should be shown
@ -160,11 +153,10 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
* @throws TelegramApiException * @throws TelegramApiException
*/ */
private void sendAnswerCallbackQuery(String text, boolean alert, CallbackQuery callbackquery) throws TelegramApiException{ private void sendAnswerCallbackQuery(String text, boolean alert, CallbackQuery callbackquery) throws TelegramApiException{
AnswerCallbackQuery answerCallbackQuery = new AnswerCallbackQuery(); AnswerCallbackQuery answerCallbackQuery = new AnswerCallbackQuery(callbackquery.getId());
answerCallbackQuery.setCallbackQueryId(callbackquery.getId());
answerCallbackQuery.setShowAlert(alert); answerCallbackQuery.setShowAlert(alert);
answerCallbackQuery.setText(text); answerCallbackQuery.setText(text);
execute(answerCallbackQuery); telegramClient.execute(answerCallbackQuery);
} }
/** /**
@ -193,34 +185,18 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
index++; index++;
} }
InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup(); return InlineKeyboardMarkup
.builder()
List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>(); .keyboardRow(new InlineKeyboardRow(
InlineKeyboardButton.builder().text(this.urls.get(index)[2]).callbackData("gallery:text:" + index).build()
List<InlineKeyboardButton> rowInline = new ArrayList<>(); ))
rowInline.add(InlineKeyboardButton.builder().text(this.urls.get(index)[2]).callbackData("gallery:text:" + index).build()); .keyboardRow(new InlineKeyboardRow(
InlineKeyboardButton.builder().text(BACK).callbackData("gallery:back:" + index).build(),
InlineKeyboardButton.builder().text(NEXT).callbackData("gallery:next:" + index).build()
List<InlineKeyboardButton> rowInline2 = new ArrayList<>(); ))
rowInline2.add(InlineKeyboardButton.builder().text(BACK).callbackData("gallery:back:" + index).build()); .keyboardRow(new InlineKeyboardRow(
rowInline2.add(InlineKeyboardButton.builder().text(NEXT).callbackData("gallery:next:" + index).build()); InlineKeyboardButton.builder().text("Link").callbackData(this.urls.get(index)[0]).build()
))
List<InlineKeyboardButton> rowInline3 = new ArrayList<>(); .build();
rowInline3.add(InlineKeyboardButton.builder().text("Link").url(this.urls.get(index)[0]).build());
rowsInline.add(rowInline);
rowsInline.add(rowInline3);
rowsInline.add(rowInline2);
markupInline.setKeyboard(rowsInline);
return markupInline;
} }
@Override
public String getBotToken() {
return BotConfig.ELEKTROLLART_TOKEN;
}
} }

160
src/main/java/org/telegram/updateshandlers/FilesHandlers.java

@ -1,22 +1,23 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.Emoji; import org.telegram.services.Emoji;
import org.telegram.services.LocalisationService; import org.telegram.services.LocalisationService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument; import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.InputFile; 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.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,28 +33,22 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* This bot is an example for the use of sendMessage asynchronously * This bot is an example for the use of sendMessage asynchronously
*/ */
@Slf4j @Slf4j
public class FilesHandlers extends TelegramLongPollingBot { public class FilesHandlers implements LongPollingSingleThreadUpdateConsumer {
private static final int INITIAL_UPLOAD_STATUS = 0; private static final int INITIAL_UPLOAD_STATUS = 0;
private static final int DELETE_UPLOADED_STATUS = 1; private static final int DELETE_UPLOADED_STATUS = 1;
private final ConcurrentLinkedQueue<Integer> languageMessages = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Long> languageMessages = new ConcurrentLinkedQueue<>();
private final TelegramClient telegramClient;
@Override public FilesHandlers(String botToken) {
public String getBotToken() { telegramClient = new OkHttpTelegramClient(botToken);
return BotConfig.FILES_TOKEN;
} }
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
try { try {
if (update.hasMessage()) { if (update.hasMessage()) {
try { try {
SendMessage sendMessageRequest = new SendMessage(); handleFileUpdate(update);
sendMessageRequest.setText("Since this bot was used to spread copyrighted content, we had to disable its functionality until further announcement.\n\nSorry for the troubles, just blame those that used the bot for illegal purposes.");
sendMessageRequest.setChatId(Long.toString(update.getMessage().getChatId()));
execute(sendMessageRequest);
//handleFileUpdate(update);
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
if (e.getApiResponse().contains("Bot was blocked by the user")) { if (e.getApiResponse().contains("Bot was blocked by the user")) {
if (update.getMessage().getFrom() != null) { if (update.getMessage().getFrom() != null) {
@ -61,19 +56,14 @@ public class FilesHandlers extends TelegramLongPollingBot {
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Error handling file update", e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Unknown exception", e);
} }
} }
@Override
public String getBotUsername() {
return BotConfig.FILES_USER;
}
private void handleFileUpdate(Update update) throws InvalidObjectException, TelegramApiException { private void handleFileUpdate(Update update) throws InvalidObjectException, TelegramApiException {
Message message = update.getMessage(); Message message = update.getMessage();
if (message != null && message.hasText()) { if (message != null && message.hasText()) {
@ -110,30 +100,27 @@ public class FilesHandlers extends TelegramLongPollingBot {
&& DatabaseManager.getInstance().getUserStatusForFile(message.getFrom().getId()) == INITIAL_UPLOAD_STATUS) { && DatabaseManager.getInstance().getUserStatusForFile(message.getFrom().getId()) == INITIAL_UPLOAD_STATUS) {
String language = DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId()); String language = DatabaseManager.getInstance().getUserLanguage(update.getMessage().getFrom().getId());
DatabaseManager.getInstance().addFile(message.getDocument().getFileId(), message.getFrom().getId(), message.getDocument().getFileName()); DatabaseManager.getInstance().addFile(message.getDocument().getFileId(), message.getFrom().getId(), message.getDocument().getFileName());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("fileUploaded", language) +
sendMessageRequest.setText(LocalisationService.getString("fileUploaded", language) +
LocalisationService.getString("uploadedFileURL", language) + message.getDocument().getFileId()); LocalisationService.getString("uploadedFileURL", language) + message.getDocument().getFileId());
sendMessageRequest.setChatId(Long.toString(message.getChatId())); telegramClient.execute(sendMessageRequest);
execute(sendMessageRequest);
} }
} }
private void onListCommand(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onListCommand(Message message, String language) throws InvalidObjectException, TelegramApiException {
HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId());
SendMessage sendMessageRequest = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageRequestBuilder = SendMessage.builder();
if (files.size() > 0) { if (!files.isEmpty()) {
String text = LocalisationService.getString("listOfFiles", language) + ":\n\n"; StringBuilder text = new StringBuilder(LocalisationService.getString("listOfFiles", language) + ":\n\n");
for (Map.Entry<String, String> entry : files.entrySet()) { for (Map.Entry<String, String> entry : files.entrySet()) {
text += LocalisationService.getString("uploadedFileURL", language) text.append(LocalisationService.getString("uploadedFileURL", language)).append(entry.getKey()).append(" ").append(Emoji.LEFT_RIGHT_ARROW).append(" ").append(entry.getValue()).append("\n");
+ entry.getKey() + " " + Emoji.LEFT_RIGHT_ARROW.toString() + " " + entry.getValue() + "\n";
} }
sendMessageRequest.setText(text); sendMessageRequestBuilder.text(text.toString());
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("noFiles", language)); sendMessageRequestBuilder.text(LocalisationService.getString("noFiles", language));
} }
sendMessageRequest.setChatId(Long.toString(message.getChatId())); sendMessageRequestBuilder.chatId(message.getChatId());
sendMessageRequest.setReplyMarkup(new ReplyKeyboardRemove()); sendMessageRequestBuilder.replyMarkup(ReplyKeyboardRemove.builder().build());
execute(sendMessageRequest); telegramClient.execute(sendMessageRequestBuilder.build());
} }
private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException, TelegramApiException { private void onDeleteCommand(Message message, String language, String[] parts) throws InvalidObjectException, TelegramApiException {
@ -145,122 +132,107 @@ public class FilesHandlers extends TelegramLongPollingBot {
} }
} }
private void onDeleteCommandWithoutParameters(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onDeleteCommandWithoutParameters(Message message, String language) throws TelegramApiException {
DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), DELETE_UPLOADED_STATUS); DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), DELETE_UPLOADED_STATUS);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("deleteUploadedFile", language));
sendMessageRequest.setText(LocalisationService.getString("deleteUploadedFile", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId()); HashMap<String, String> files = DatabaseManager.getInstance().getFilesByUser(message.getFrom().getId());
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup replyKeyboardMarkup = null;
if (files.size() > 0) { if (!files.isEmpty()) {
List<KeyboardRow> commands = new ArrayList<>(); List<KeyboardRow> commands = new ArrayList<>();
for (Map.Entry<String, String> entry : files.entrySet()) { for (Map.Entry<String, String> entry : files.entrySet()) {
KeyboardRow commandRow = new KeyboardRow(); KeyboardRow commandRow = new KeyboardRow();
commandRow.add(Commands.deleteCommand + " " + entry.getKey() + " " + Emoji.LEFT_RIGHT_ARROW.toString() commandRow.add(Commands.deleteCommand + " " + entry.getKey() + " " + Emoji.LEFT_RIGHT_ARROW
+ " " + entry.getValue()); + " " + entry.getValue());
commands.add(commandRow); commands.add(commandRow);
} }
replyKeyboardMarkup = new ReplyKeyboardMarkup(commands);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkup.setResizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkup.setOneTimeKeyboard(true);
replyKeyboardMarkup.setKeyboard(commands);
} }
sendMessageRequest.setReplyMarkup(replyKeyboardMarkup); sendMessageRequest.setReplyMarkup(replyKeyboardMarkup);
execute(sendMessageRequest); telegramClient.execute(sendMessageRequest);
} }
private void onDeleteCommandWithParameters(Message message, String language, String part) throws InvalidObjectException, TelegramApiException { private void onDeleteCommandWithParameters(Message message, String language, String part) throws TelegramApiException {
String[] innerParts = part.split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); String[] innerParts = part.split(Emoji.LEFT_RIGHT_ARROW.toString(), 2);
boolean removed = DatabaseManager.getInstance().deleteFile(innerParts[0].trim()); boolean removed = DatabaseManager.getInstance().deleteFile(innerParts[0].trim());
SendMessage sendMessageRequest = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageRequestBuilder = SendMessage.builder();
if (removed) { if (removed) {
sendMessageRequest.setText(LocalisationService.getString("fileDeleted", language)); sendMessageRequestBuilder.text(LocalisationService.getString("fileDeleted", language));
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language)); sendMessageRequestBuilder.text(LocalisationService.getString("wrongFileId", language));
} }
sendMessageRequest.setChatId(Long.toString(message.getChatId())); sendMessageRequestBuilder.chatId(message.getChatId());
execute(sendMessageRequest); telegramClient.execute(sendMessageRequestBuilder.build());
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
} }
private void onCancelCommand(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onCancelCommand(Message message, String language) throws TelegramApiException {
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("processFinished", language));
sendMessageRequest.setText(LocalisationService.getString("processFinished", language)); telegramClient.execute(sendMessageRequest);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest);
} }
private void onUploadCommand(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onUploadCommand(Message message, String language) throws TelegramApiException {
DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), INITIAL_UPLOAD_STATUS); DatabaseManager.getInstance().addUserForFile(message.getFrom().getId(), INITIAL_UPLOAD_STATUS);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("sendFileToUpload", language));
sendMessageRequest.setText(LocalisationService.getString("sendFileToUpload", language)); telegramClient.execute(sendMessageRequest);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest);
} }
private void sendHelpMessage(Message message, String language) throws InvalidObjectException, TelegramApiException { private void sendHelpMessage(Message message, String language) throws TelegramApiException {
SendMessage sendMessageRequest = new SendMessage();
String formatedString = String.format( String formatedString = String.format(
LocalisationService.getString("helpFiles", language), LocalisationService.getString("helpFiles", language),
Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand, Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand,
Commands.listCommand); Commands.listCommand);
sendMessageRequest.setText(formatedString); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), formatedString);
sendMessageRequest.setChatId(Long.toString(message.getChatId())); telegramClient.execute(sendMessageRequest);
execute(sendMessageRequest);
} }
private void onStartWithParameters(Message message, String language, String part) throws InvalidObjectException, TelegramApiException { private void onStartWithParameters(Message message, String language, String part) throws TelegramApiException {
if (DatabaseManager.getInstance().doesFileExists(part.trim())) { if (DatabaseManager.getInstance().doesFileExists(part.trim())) {
SendDocument sendDocumentRequest = new SendDocument(); SendDocument sendDocumentRequest = new SendDocument(String.valueOf(message.getChatId()), new InputFile(part.trim()));
sendDocumentRequest.setDocument(new InputFile(part.trim())); telegramClient.execute(sendDocumentRequest);
sendDocumentRequest.setChatId(Long.toString(message.getChatId()));
execute(sendDocumentRequest);
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("wrongFileId", language));
sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language)); telegramClient.execute(sendMessageRequest);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest);
} }
} }
private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onSetLanguageCommand(Message message, String language) throws TelegramApiException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("chooselanguage", language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
List<LocalisationService.Language> languages = LocalisationService.getSupportedLanguages(); List<LocalisationService.Language> languages = LocalisationService.getSupportedLanguages();
List<KeyboardRow> commands = new ArrayList<>(); List<KeyboardRow> commands = new ArrayList<>();
for (LocalisationService.Language languageItem : languages) { for (LocalisationService.Language languageItem : languages) {
KeyboardRow commandRow = new KeyboardRow(); KeyboardRow commandRow = new KeyboardRow();
commandRow.add(languageItem.getCode() + " " + Emoji.LEFT_RIGHT_ARROW.toString() + " " + languageItem.getName()); commandRow.add(languageItem.getCode() + " " + Emoji.LEFT_RIGHT_ARROW + " " + languageItem.getName());
commands.add(commandRow); commands.add(commandRow);
} }
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(commands);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkup.setResizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkup.setOneTimeKeyboard(true);
replyKeyboardMarkup.setKeyboard(commands);
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkup.setSelective(true);
sendMessageRequest.setReplyMarkup(replyKeyboardMarkup); sendMessageRequest.setReplyMarkup(replyKeyboardMarkup);
sendMessageRequest.setText(LocalisationService.getString("chooselanguage", language)); telegramClient.execute(sendMessageRequest);
execute(sendMessageRequest);
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} }
private void onLanguageReceived(Message message) throws InvalidObjectException, TelegramApiException { private void onLanguageReceived(Message message) throws TelegramApiException {
String[] parts = message.getText().split(Emoji.LEFT_RIGHT_ARROW.toString(), 2); String[] parts = message.getText().split(Emoji.LEFT_RIGHT_ARROW.toString(), 2);
SendMessage sendMessageRequest = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageRequestBuilder = SendMessage.builder();
sendMessageRequest.setChatId(Long.toString(message.getChatId())); sendMessageRequestBuilder.chatId(message.getChatId());
if (LocalisationService.getLanguageByCode(parts[0].trim()) != null) { if (LocalisationService.getLanguageByCode(parts[0].trim()) != null) {
DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim()); DatabaseManager.getInstance().putUserLanguage(message.getFrom().getId(), parts[0].trim());
sendMessageRequest.setText(LocalisationService.getString("languageModified", parts[0].trim())); sendMessageRequestBuilder.text(LocalisationService.getString("languageModified", parts[0].trim()));
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("errorLanguage")); sendMessageRequestBuilder.text(LocalisationService.getString("errorLanguage"));
} }
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequestBuilder.replyToMessageId(message.getMessageId());
ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove(); ReplyKeyboardRemove replyKeyboardRemove = ReplyKeyboardRemove.builder().selective(true).build();
replyKeyboardRemove.setSelective(true); sendMessageRequestBuilder.replyMarkup(replyKeyboardRemove);
sendMessageRequest.setReplyMarkup(replyKeyboardRemove); telegramClient.execute(sendMessageRequestBuilder.build());
execute(sendMessageRequest);
languageMessages.remove(message.getFrom().getId()); languageMessages.remove(message.getFrom().getId());
} }
} }

82
src/main/java/org/telegram/updateshandlers/RaeHandlers.java

@ -1,19 +1,20 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.services.RaeService; import org.telegram.services.RaeService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery; import org.telegram.telegrambots.meta.api.methods.AnswerInlineQuery;
import org.telegram.telegrambots.meta.api.methods.ParseMode; import org.telegram.telegrambots.meta.api.methods.ParseMode;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputTextMessageContent; import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessagecontent.InputTextMessageContent;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResult;
import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResultArticle; import org.telegram.telegrambots.meta.api.objects.inlinequery.result.InlineQueryResultArticle;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -21,11 +22,10 @@ import java.util.List;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for inline queries in Raebot * Handler for inline queries in Raebot
* @date 24 of June of 2015
*/ */
@Slf4j @Slf4j
public class RaeHandlers extends TelegramLongPollingBot { public class RaeHandlers implements LongPollingSingleThreadUpdateConsumer {
private static final Integer CACHETIME = 86400; private static final Integer CACHETIME = 86400;
private final RaeService raeService = new RaeService(); private final RaeService raeService = new RaeService();
private static final String THUMBNAILBLUE = "https://lh5.ggpht.com/-kSFHGvQkFivERzyCNgKPIECtIOELfPNWAQdXqQ7uqv2xztxqll4bVibI0oHJYAuAas=w300"; private static final String THUMBNAILBLUE = "https://lh5.ggpht.com/-kSFHGvQkFivERzyCNgKPIECtIOELfPNWAQdXqQ7uqv2xztxqll4bVibI0oHJYAuAas=w300";
@ -36,31 +36,27 @@ public class RaeHandlers extends TelegramLongPollingBot {
"\n\n" + "\n\n" +
"Por ejemplo, intenta escribir `@raebot Punto` aquí."; "Por ejemplo, intenta escribir `@raebot Punto` aquí.";
@Override private final TelegramClient telegramClient;
public String getBotToken() {
return BotConfig.RAE_TOKEN; public RaeHandlers(String botToken) {
telegramClient = new OkHttpTelegramClient(botToken);
} }
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
try { try {
if (update.hasInlineQuery()) { if (update.hasInlineQuery()) {
handleIncomingInlineQuery(update.getInlineQuery()); handleIncomingInlineQuery(update.getInlineQuery());
} else if (update.hasMessage() && update.getMessage().isUserMessage()) { } else if (update.hasMessage() && update.getMessage().isUserMessage()) {
try { try {
execute(getHelpMessage(update.getMessage())); telegramClient.execute(getHelpMessage(update.getMessage()));
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error", e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Unknown exception", e);
}
} }
@Override
public String getBotUsername() {
return BotConfig.RAE_USER;
} }
/** /**
@ -69,16 +65,16 @@ public class RaeHandlers extends TelegramLongPollingBot {
*/ */
private void handleIncomingInlineQuery(InlineQuery inlineQuery) { private void handleIncomingInlineQuery(InlineQuery inlineQuery) {
String query = inlineQuery.getQuery(); String query = inlineQuery.getQuery();
log.debug("Searching: " + query); log.debug("Searching: {}", query);
try { try {
if (!query.isEmpty()) { if (!query.isEmpty()) {
List<RaeService.RaeResult> results = raeService.getResults(query); List<RaeService.RaeResult> results = raeService.getResults(query);
execute(converteResultsToResponse(inlineQuery, results)); telegramClient.execute(converteResultsToResponse(inlineQuery, results));
} else { } else {
execute(converteResultsToResponse(inlineQuery, new ArrayList<>())); telegramClient.execute(converteResultsToResponse(inlineQuery, new ArrayList<>()));
} }
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error handing inline query", e);
} }
} }
@ -89,11 +85,12 @@ public class RaeHandlers extends TelegramLongPollingBot {
* @return AnswerInlineQuery method to answer the query * @return AnswerInlineQuery method to answer the query
*/ */
private static AnswerInlineQuery converteResultsToResponse(InlineQuery inlineQuery, List<RaeService.RaeResult> results) { private static AnswerInlineQuery converteResultsToResponse(InlineQuery inlineQuery, List<RaeService.RaeResult> results) {
AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery(); return AnswerInlineQuery
answerInlineQuery.setInlineQueryId(inlineQuery.getId()); .builder()
answerInlineQuery.setCacheTime(CACHETIME); .inlineQueryId(inlineQuery.getId())
answerInlineQuery.setResults(convertRaeResults(results)); .cacheTime(CACHETIME)
return answerInlineQuery; .results(convertRaeResults(results))
.build();
} }
/** /**
@ -106,16 +103,18 @@ public class RaeHandlers extends TelegramLongPollingBot {
for (int i = 0; i < raeResults.size(); i++) { for (int i = 0; i < raeResults.size(); i++) {
RaeService.RaeResult raeResult = raeResults.get(i); RaeService.RaeResult raeResult = raeResults.get(i);
InputTextMessageContent messageContent = new InputTextMessageContent(); InlineQueryResultArticle article = new InlineQueryResultArticle(
messageContent.setDisableWebPagePreview(true); Integer.toString(i),
messageContent.setParseMode(ParseMode.MARKDOWN); raeResult.getTitle(),
messageContent.setMessageText(raeResult.getDefinition()); InputTextMessageContent
InlineQueryResultArticle article = new InlineQueryResultArticle(); .builder()
article.setInputMessageContent(messageContent); .disableWebPagePreview(true)
article.setId(Integer.toString(i)); .parseMode(ParseMode.MARKDOWN)
article.setTitle(raeResult.getTitle()); .messageText(raeResult.getDefinition())
.build()
);
article.setDescription(raeResult.getDescription()); article.setDescription(raeResult.getDescription());
article.setThumbUrl(THUMBNAILBLUE); article.setThumbnailUrl(THUMBNAILBLUE);
results.add(article); results.add(article);
} }
@ -128,10 +127,11 @@ public class RaeHandlers extends TelegramLongPollingBot {
* @return SendMessage method * @return SendMessage method
*/ */
private static SendMessage getHelpMessage(Message message) { private static SendMessage getHelpMessage(Message message) {
SendMessage sendMessage = new SendMessage(); return SendMessage
sendMessage.setChatId(Long.toString(message.getChatId())); .builder()
sendMessage.enableMarkdown(true); .chatId(message.getChatId())
sendMessage.setText(helpMessage); .parseMode(ParseMode.MARKDOWN)
return sendMessage; .text(helpMessage)
.build();
} }
} }

141
src/main/java/org/telegram/updateshandlers/TransifexHandlers.java

@ -1,141 +0,0 @@
package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.BuildVars;
import org.telegram.Commands;
import org.telegram.database.DatabaseManager;
import org.telegram.services.LocalisationService;
import org.telegram.services.TransifexService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.InvalidObjectException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Handler for updates to Transifex Bot
* @date 24 of June of 2015
*/
@Slf4j
public class TransifexHandlers extends TelegramLongPollingBot {
@Override
public String getBotToken() {
return BotConfig.TRANSIFEX_TOKEN;
}
@Override
public void onUpdateReceived(Update update) {
try {
handleUpdate(update);
} catch (Throwable e) {
log.error(e.getLocalizedMessage(), e);
}
}
private void handleUpdate(Update update) throws InvalidObjectException, TelegramApiException {
if (update.hasMessage() && update.getMessage().hasText()) {
Message message = update.getMessage();
if (BuildVars.ADMINS.contains(message.getFrom().getId())) {
sendTransifexFile(message);
} else {
sendMovedToMessage(message);
}
}
}
@Override
public String getBotUsername() {
return BotConfig.TRANSIFEX_USER;
}
private void sendTransifexFile(Message message) throws InvalidObjectException {
String language = DatabaseManager.getInstance().getUserLanguage(message.getFrom().getId());
String text = message.getText();
String[] parts = text.split(" ", 2);
SendDocument sendDocument = null;
if (parts.length == 2) {
if (parts[0].startsWith(Commands.transifexiOSCommand)) {
sendDocument = TransifexService.getInstance().getiOSLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexAndroidCommand)) {
sendDocument = TransifexService.getInstance().getAndroidLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexTDesktop)) {
sendDocument = TransifexService.getInstance().getTdesktopLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexWebogram)) {
sendDocument = TransifexService.getInstance().getWebogramLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexWP)) {
sendDocument = TransifexService.getInstance().getWPLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexOSX)) {
sendDocument = TransifexService.getInstance().getOSXLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.transifexAndroidSupportCommand)) {
sendDocument = TransifexService.getInstance().getAndroidSupportLanguageFile(parts[1].trim());
} else if (parts[0].startsWith(Commands.help)) {
SendMessage sendMessageRequest = new SendMessage();
String helpFormated = String.format(
LocalisationService.getString("helpTransifex", language),
Commands.transifexiOSCommand, Commands.transifexAndroidCommand, Commands.transifexWebogram,
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try {
execute(sendMessageRequest);
} catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e);
}
}
if (sendDocument != null) {
sendDocument.setChatId(Long.toString(message.getChatId()));
try {
execute(sendDocument);
} catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e);
}
}
} else if (parts[0].startsWith(Commands.help) ||
(message.getText().startsWith(Commands.startCommand) || !message.isGroupMessage())) {
SendMessage sendMessageRequest = new SendMessage();
String helpFormated = String.format(
LocalisationService.getString("helpTransifex", language),
Commands.transifexiOSCommand, Commands.transifexAndroidCommand, Commands.transifexWebogram,
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try {
execute(sendMessageRequest);
} catch (TelegramApiException e) {
log.error(e.getLocalizedMessage(), e);
}
}
}
private void sendMovedToMessage(Message message) throws InvalidObjectException, TelegramApiException {
String language = DatabaseManager.getInstance().getUserLanguage(message.getFrom().getId());
SendMessage answer = new SendMessage();
answer.setChatId(Long.toString(message.getChatId()));
answer.setReplyToMessageId(message.getMessageId());
answer.setText(LocalisationService.getString("movedToLangBot", language));
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
List<List<InlineKeyboardButton>> rows = new ArrayList<>();
List<InlineKeyboardButton> row = new ArrayList<>();
InlineKeyboardButton button = new InlineKeyboardButton();
button.setText(LocalisationService.getString("checkLangBot", language));
button.setUrl("https://telegram.me/langbot");
row.add(button);
rows.add(row);
inlineKeyboardMarkup.setKeyboard(rows);
answer.setReplyMarkup(inlineKeyboardMarkup);
execute(answer);
}
}

377
src/main/java/org/telegram/updateshandlers/WeatherHandlers.java

@ -1,15 +1,20 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.services.*; import org.telegram.services.CustomTimerTask;
import org.telegram.services.Emoji;
import org.telegram.services.LocalisationService;
import org.telegram.services.TimerExecutor;
import org.telegram.services.WeatherService;
import org.telegram.structure.WeatherAlert; import org.telegram.structure.WeatherAlert;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer;
import org.telegram.telegrambots.meta.api.methods.ParseMode;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ForceReplyKeyboard;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
@ -17,19 +22,18 @@ import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRem
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for updates to Weather Bot * Handler for updates to Weather Bot
* @date 24 of June of 2015
*/ */
@Slf4j @Slf4j
public class WeatherHandlers extends TelegramLongPollingBot { public class WeatherHandlers implements LongPollingSingleThreadUpdateConsumer {
private static final int STARTSTATE = 0; private static final int STARTSTATE = 0;
private static final int MAINMENU = 1; private static final int MAINMENU = 1;
private static final int CURRENTWEATHER = 2; private static final int CURRENTWEATHER = 2;
@ -45,18 +49,15 @@ public class WeatherHandlers extends TelegramLongPollingBot {
private static final int LANGUAGE = 12; private static final int LANGUAGE = 12;
private static final int UNITS = 13; private static final int UNITS = 13;
public WeatherHandlers() { private final TelegramClient telegramClient;
super();
startAlertTimers();
}
@Override public WeatherHandlers(String botToken) {
public String getBotToken() { startAlertTimers();
return BotConfig.WEATHER_TOKEN; telegramClient = new OkHttpTelegramClient(botToken);
} }
@Override @Override
public void onUpdateReceived(Update update) { public void consume(Update update) {
try { try {
if (update.hasMessage()) { if (update.hasMessage()) {
Message message = update.getMessage(); Message message = update.getMessage();
@ -65,15 +66,10 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Weather Handler error", e);
} }
} }
@Override
public String getBotUsername() {
return BotConfig.WEATHER_USER;
}
private void startAlertTimers() { private void startAlertTimers() {
TimerExecutor.getInstance().startExecutionEveryDayAt(new CustomTimerTask("First day alert", -1) { TimerExecutor.getInstance().startExecutionEveryDayAt(new CustomTimerTask("First day alert", -1) {
@Override @Override
@ -97,37 +93,32 @@ public class WeatherHandlers extends TelegramLongPollingBot {
try { try {
Thread.currentThread().wait(35); Thread.currentThread().wait(35);
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error(e.getLocalizedMessage(), e); log.error("Error sleeping for alerts", e);
} }
} }
String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId()); String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId());
String weather = WeatherService.getInstance().fetchWeatherAlert(weatherAlert.getCityId(), String weather = WeatherService.getInstance().fetchWeatherAlert(weatherAlert.getCityId(),
weatherAlert.getUserId(), userOptions[0], userOptions[1]); weatherAlert.getUserId(), userOptions[0], userOptions[1]);
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(weatherAlert.getUserId()), weather);
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(String.valueOf(weatherAlert.getUserId()));
sendMessage.setText(weather);
try { try {
execute(sendMessage); telegramClient.execute(sendMessage);
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
log.warn(e.getLocalizedMessage(), e); log.warn("Error sending alerts", e);
if (e.getApiResponse().contains("Can't access the chat") || e.getApiResponse().contains("Bot was blocked by the user")) { if (e.getApiResponse().contains("Can't access the chat") || e.getApiResponse().contains("Bot was blocked by the user")) {
DatabaseManager.getInstance().deleteAlertsForUser(weatherAlert.getUserId()); DatabaseManager.getInstance().deleteAlertsForUser(weatherAlert.getUserId());
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getLocalizedMessage(), e); log.error("Unknown error sending alerts", e);
} }
} }
} }
private static SendMessage onCancelCommand(Long chatId, Integer userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) { private static SendMessage onCancelCommand(Long chatId, Long userId, Integer messageId, ReplyKeyboard replyKeyboard, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("backToMainMenu", language));
sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(replyKeyboard); sendMessage.setReplyMarkup(replyKeyboard);
sendMessage.setText(LocalisationService.getString("backToMainMenu", language));
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessage; return sendMessage;
} }
@ -179,21 +170,18 @@ public class WeatherHandlers extends TelegramLongPollingBot {
break; break;
} }
execute(sendMessageRequest); telegramClient.execute(sendMessageRequest);
} }
private void sendHideKeyboard(Integer userId, Long chatId, Integer messageId) throws TelegramApiException { private void sendHideKeyboard(Long userId, Long chatId, Integer messageId) throws TelegramApiException {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), Emoji.WAVING_HAND_SIGN.toString());
sendMessage.setChatId(chatId.toString());
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setText(Emoji.WAVING_HAND_SIGN.toString());
ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove(); ReplyKeyboardRemove replyKeyboardRemove = ReplyKeyboardRemove.builder().selective(true).build();
replyKeyboardRemove.setSelective(true);
sendMessage.setReplyMarkup(replyKeyboardRemove); sendMessage.setReplyMarkup(replyKeyboardRemove);
execute(sendMessage); telegramClient.execute(sendMessage);
DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE); DatabaseManager.getInstance().insertWeatherState(userId, chatId, STARTSTATE);
} }
@ -240,24 +228,20 @@ public class WeatherHandlers extends TelegramLongPollingBot {
private static SendMessage onAlertDeleteCityOptionSelected(Message message, String language) { private static SendMessage onAlertDeleteCityOptionSelected(Message message, String language) {
DatabaseManager.getInstance().deleteAlertCity(message.getFrom().getId(), message.getText()); DatabaseManager.getInstance().deleteAlertCity(message.getFrom().getId(), message.getText());
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("alertDeleted", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertDeleted", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT);
return sendMessage; return sendMessage;
} }
private static SendMessage onAlertDeleteBackOptionSelected(Message message, String language) { private static SendMessage onAlertDeleteBackOptionSelected(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("alertsMenuMessage", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT);
return sendMessage; return sendMessage;
@ -267,12 +251,10 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessageRequest = null; SendMessage sendMessageRequest = null;
if (message.hasText()) { if (message.hasText()) {
if (message.getText().equals(getCancelCommand(language))) { if (message.getText().equals(getCancelCommand(language))) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("alertsMenuMessage", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT);
sendMessageRequest = sendMessage; sendMessageRequest = sendMessage;
} else { } else {
@ -283,16 +265,14 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onNewAlertCityReceived(Message message, String language) { private static SendMessage onNewAlertCityReceived(Message message, String language) {
int userId = message.getFrom().getId(); long userId = message.getFrom().getId();
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, message.getText()); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, message.getText());
if (cityId != null) { if (cityId != null) {
DatabaseManager.getInstance().createNewWeatherAlert(userId, cityId, message.getText()); DatabaseManager.getInstance().createNewWeatherAlert(userId, cityId, message.getText());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = SendMessage.builder().chatId(message.getChatId()).text(getChooseNewAlertSetMessage(message.getText(), language)).build();
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getAlertsKeyboard(language)); sendMessageRequest.setReplyMarkup(getAlertsKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language));
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT);
return sendMessageRequest; return sendMessageRequest;
@ -322,59 +302,50 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onBackAlertCommand(Message message, String language) { private static SendMessage onBackAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getSettingsMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static SendMessage onListAlertCommand(Message message, String language) { private static SendMessage onListAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getAlertListMessage(message.getFrom().getId(), language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(getAlertListMessage(message.getFrom().getId(), language));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
return sendMessage; return sendMessage;
} }
private static SendMessage onDeleteAlertCommand(Message message, String language) { private static SendMessage onDeleteAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageBuilder = SendMessage.builder();
sendMessage.enableMarkdown(true); sendMessageBuilder.parseMode(ParseMode.MARKDOWN);
sendMessageBuilder.chatId(message.getChatId());
sendMessage.setChatId(Long.toString(message.getChatId()));
ReplyKeyboardMarkup replyKeyboardMarkup = getAlertsListKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getAlertsListKeyboard(message.getFrom().getId(), language);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessageBuilder.replyMarkup(replyKeyboardMarkup);
sendMessage.setText(LocalisationService.getString("chooseNewAlertCity", language)); sendMessageBuilder.text(LocalisationService.getString("chooseNewAlertCity", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERTDELETE); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERTDELETE);
} else { } else {
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessageBuilder.replyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("noAlertList", language)); sendMessageBuilder.text(LocalisationService.getString("noAlertList", language));
} }
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessageBuilder.replyToMessageId(message.getMessageId());
return sendMessage; return sendMessageBuilder.build();
} }
private static SendMessage onNewAlertCommand(Message message, String language) { private static SendMessage onNewAlertCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("chooseNewAlertCity", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getRecentsKeyboard(message.getFrom().getId(), language, false)); sendMessage.setReplyMarkup(getRecentsKeyboard(message.getFrom().getId(), language, false));
sendMessage.setText(LocalisationService.getString("chooseNewAlertCity", language));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERTNEW); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERTNEW);
@ -405,39 +376,30 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onAlertsCommand(Message message, String language) { private static SendMessage onAlertsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), LocalisationService.getString("alertsMenuMessage", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), ALERT);
return sendMessage; return sendMessage;
} }
private static SendMessage onUnitsCommand(Message message, String language) { private static SendMessage onUnitsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getUnitsMessage(message.getFrom().getId(), language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getUnitsKeyboard(language)); sendMessage.setReplyMarkup(getUnitsKeyboard(language));
sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), UNITS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), UNITS);
return sendMessage; return sendMessage;
} }
private static SendMessage onLanguageCommand(Message message, String language) { private static SendMessage onLanguageCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getLanguageMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getLanguagesKeyboard(language)); sendMessage.setReplyMarkup(getLanguagesKeyboard(language));
sendMessage.setText(getLanguageMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), LANGUAGE); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), LANGUAGE);
return sendMessage; return sendMessage;
@ -466,37 +428,31 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onBackUnitsCommand(Message message, String language) { private static SendMessage onBackUnitsCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getSettingsMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static SendMessage onUnitsError(Long chatId, Integer messageId, String language) { private static SendMessage onUnitsError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), LocalisationService.getString("errorUnitsNotFound", language));
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setReplyMarkup(getUnitsKeyboard(language)); sendMessageRequest.setReplyMarkup(getUnitsKeyboard(language));
sendMessageRequest.setText(LocalisationService.getString("errorUnitsNotFound", language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
return sendMessageRequest; return sendMessageRequest;
} }
private static SendMessage onUnitsChosen(Integer userId, Long chatId, Integer messageId, String units, String language) { private static SendMessage onUnitsChosen(Long userId, Long chatId, Integer messageId, String units, String language) {
DatabaseManager.getInstance().putUserWeatherUnitsOption(userId, units); DatabaseManager.getInstance().putUserWeatherUnitsOption(userId, units);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), LocalisationService.getString("unitsUpdated", language));
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setText(LocalisationService.getString("unitsUpdated", language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
@ -524,38 +480,32 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onBackLanguageCommand(Message message, String language) { private static SendMessage onBackLanguageCommand(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getSettingsMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static SendMessage onLanguageError(Long chatId, Integer messageId, String language) { private static SendMessage onLanguageError(Long chatId, Integer messageId, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), LocalisationService.getString("errorLanguageNotFound", language));
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setReplyMarkup(getLanguagesKeyboard(language)); sendMessageRequest.setReplyMarkup(getLanguagesKeyboard(language));
sendMessageRequest.setText(LocalisationService.getString("errorLanguageNotFound", language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
return sendMessageRequest; return sendMessageRequest;
} }
private static SendMessage onLanguageChosen(Integer userId, Long chatId, Integer messageId, String language) { private static SendMessage onLanguageChosen(Long userId, Long chatId, Integer messageId, String language) {
String languageCode = LocalisationService.getLanguageCodeByName(language); String languageCode = LocalisationService.getLanguageCodeByName(language);
DatabaseManager.getInstance().putUserWeatherLanguageOption(userId, languageCode); DatabaseManager.getInstance().putUserWeatherLanguageOption(userId, languageCode);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), LocalisationService.getString("languageUpdated", languageCode));
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setChatId(chatId.toString());
sendMessageRequest.setText(LocalisationService.getString("languageUpdated", languageCode));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(languageCode)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(languageCode));
@ -609,17 +559,15 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
private static SendMessage onForecastWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage onForecastWeatherCityReceived(Long chatId, Long userId, Integer messageId, String text, String language) {
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text);
if (cityId != null) { if (cityId != null) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherForecast(cityId.toString(), userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherForecast(cityId.toString(), userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
@ -628,29 +576,25 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
private static SendMessage onLocationForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onLocationForecastWeatherCommand(Long chatId, Long userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("onWeatherLocationCommand", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId.toString());
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(forceReplyKeyboard); sendMessage.setReplyMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getString("onWeatherLocationCommand", language));
DatabaseManager.getInstance().insertWeatherState(userId, chatId, FORECASTLOCATIONWEATHER); DatabaseManager.getInstance().insertWeatherState(userId, chatId, FORECASTLOCATIONWEATHER);
return sendMessage; return sendMessage;
} }
private static SendMessage onNewForecastWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onNewForecastWeatherCommand(Long chatId, Long userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("onWeatherNewCommand", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId.toString());
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(forceReplyKeyboard); sendMessage.setReplyMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getString("onWeatherNewCommand", language));
DatabaseManager.getInstance().insertWeatherState(userId, chatId, FORECASTNEWWEATHER); DatabaseManager.getInstance().insertWeatherState(userId, chatId, FORECASTNEWWEATHER);
return sendMessage; return sendMessage;
@ -711,17 +655,15 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
private static SendMessage onCurrentWeatherCityReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage onCurrentWeatherCityReceived(Long chatId, Long userId, Integer messageId, String text, String language) {
Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text); Integer cityId = DatabaseManager.getInstance().getRecentWeatherIdByCity(userId, text);
if (cityId != null) { if (cityId != null) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherCurrent(cityId.toString(), userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherCurrent(cityId.toString(), userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} else { } else {
@ -729,29 +671,25 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
private static SendMessage onLocationCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onLocationCurrentWeatherCommand(Long chatId, Long userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("onWeatherLocationCommand", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId.toString());
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(forceReplyKeyboard); sendMessage.setReplyMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getString("onWeatherLocationCommand", language));
DatabaseManager.getInstance().insertWeatherState(userId, chatId, CURRENTLOCATIONWEATHER); DatabaseManager.getInstance().insertWeatherState(userId, chatId, CURRENTLOCATIONWEATHER);
return sendMessage; return sendMessage;
} }
private static SendMessage onNewCurrentWeatherCommand(Long chatId, Integer userId, Integer messageId, String language) { private static SendMessage onNewCurrentWeatherCommand(Long chatId, Long userId, Integer messageId, String language) {
ForceReplyKeyboard forceReplyKeyboard = getForceReply(); ForceReplyKeyboard forceReplyKeyboard = getForceReply();
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("onWeatherNewCommand", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId.toString());
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(forceReplyKeyboard); sendMessage.setReplyMarkup(forceReplyKeyboard);
sendMessage.setText(LocalisationService.getString("onWeatherNewCommand", language));
DatabaseManager.getInstance().insertWeatherState(userId, chatId, CURRENTNEWWEATHER); DatabaseManager.getInstance().insertWeatherState(userId, chatId, CURRENTNEWWEATHER);
return sendMessage; return sendMessage;
@ -793,53 +731,51 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
private static SendMessage onSettingsChoosen(Message message, String language) { private static SendMessage onSettingsChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(message.getChatId()), getSettingsMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
return sendMessage; return sendMessage;
} }
private static SendMessage onForecastChoosen(Message message, String language) { private static SendMessage onForecastChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageBuilder = SendMessage.builder();
sendMessage.enableMarkdown(true); sendMessageBuilder.parseMode(ParseMode.MARKDOWN);
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessageBuilder.replyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessageBuilder.replyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId())); sendMessageBuilder.chatId(message.getChatId());
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getString("onForecastCommandFromHistory", language)); sendMessageBuilder.text(LocalisationService.getString("onForecastCommandFromHistory", language));
} else { } else {
sendMessage.setText(LocalisationService.getString("onForecastCommandWithoutHistory", language)); sendMessageBuilder.text(LocalisationService.getString("onForecastCommandWithoutHistory", language));
} }
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), FORECASTWEATHER); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), FORECASTWEATHER);
return sendMessage; return sendMessageBuilder.build();
} }
private static SendMessage onCurrentChoosen(Message message, String language) { private static SendMessage onCurrentChoosen(Message message, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage.SendMessageBuilder<?, ?> sendMessageBuilder = SendMessage.builder();
sendMessage.enableMarkdown(true); sendMessageBuilder.parseMode(ParseMode.MARKDOWN);
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessageBuilder.replyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessageBuilder.replyToMessageId(message.getMessageId());
sendMessage.setChatId(Long.toString(message.getChatId())); sendMessageBuilder.chatId(message.getChatId());
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getString("onCurrentCommandFromHistory", language)); sendMessageBuilder.text(LocalisationService.getString("onCurrentCommandFromHistory", language));
} else { } else {
sendMessage.setText(LocalisationService.getString("onCurrentCommandWithoutHistory", language)); sendMessageBuilder.text(LocalisationService.getString("onCurrentCommandWithoutHistory", language));
} }
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), CURRENTWEATHER); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), CURRENTWEATHER);
return sendMessage; return sendMessageBuilder.build();
} }
// endregion Main menu options selected // endregion Main menu options selected
@ -865,7 +801,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
return String.format(baseString, language); return String.format(baseString, language);
} }
private static String getUnitsMessage(Integer userId, String language) { private static String getUnitsMessage(Long userId, String language) {
String baseString = LocalisationService.getString("selectUnits", language); String baseString = LocalisationService.getString("selectUnits", language);
return String.format(baseString, DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]); return String.format(baseString, DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]);
} }
@ -875,16 +811,16 @@ public class WeatherHandlers extends TelegramLongPollingBot {
return String.format(baseString, Emoji.THUMBS_UP_SIGN.toString(), city); return String.format(baseString, Emoji.THUMBS_UP_SIGN.toString(), city);
} }
private static String getAlertListMessage(int userId, String language) { private static String getAlertListMessage(long userId, String language) {
String alertListMessage; String alertListMessage;
List<String> alertCities = DatabaseManager.getInstance().getAlertCitiesNameByUser(userId); List<String> alertCities = DatabaseManager.getInstance().getAlertCitiesNameByUser(userId);
if (alertCities.size() > 0) { if (!alertCities.isEmpty()) {
String baseAlertListString = LocalisationService.getString("initialAlertList", language); String baseAlertListString = LocalisationService.getString("initialAlertList", language);
String partialAlertListString = LocalisationService.getString("partialAlertList", language); String partialAlertListString = LocalisationService.getString("partialAlertList", language);
String fullListOfAlerts = ""; StringBuilder fullListOfAlerts = new StringBuilder();
for (String alertCity : alertCities) { for (String alertCity : alertCities) {
fullListOfAlerts += String.format(partialAlertListString, Emoji.ALARM_CLOCK.toString(), alertCity); fullListOfAlerts.append(String.format(partialAlertListString, Emoji.ALARM_CLOCK, alertCity));
} }
alertListMessage = String.format(baseAlertListString, alertCities.size(), fullListOfAlerts); alertListMessage = String.format(baseAlertListString, alertCities.size(), fullListOfAlerts);
} else { } else {
@ -900,10 +836,10 @@ public class WeatherHandlers extends TelegramLongPollingBot {
// region ReplyKeyboards // region ReplyKeyboards
private static ReplyKeyboardMarkup getMainMenuKeyboard(String language) { private static ReplyKeyboardMarkup getMainMenuKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(false); replyKeyboardMarkupBuilder.oneTimeKeyboard(false);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
KeyboardRow keyboardFirstRow = new KeyboardRow(); KeyboardRow keyboardFirstRow = new KeyboardRow();
@ -914,20 +850,20 @@ public class WeatherHandlers extends TelegramLongPollingBot {
keyboardSecondRow.add(getRateCommand(language)); keyboardSecondRow.add(getRateCommand(language));
keyboard.add(keyboardFirstRow); keyboard.add(keyboardFirstRow);
keyboard.add(keyboardSecondRow); keyboard.add(keyboardSecondRow);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getLanguagesKeyboard(String language) { private static ReplyKeyboardMarkup getLanguagesKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(false); replyKeyboardMarkupBuilder.oneTimeKeyboard(false);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
for (String languageName : LocalisationService.getSupportedLanguages().stream().map( for (String languageName : LocalisationService.getSupportedLanguages().stream().map(
LocalisationService.Language::getName).collect(Collectors.toList())) { LocalisationService.Language::getName).toList()) {
KeyboardRow row = new KeyboardRow(); KeyboardRow row = new KeyboardRow();
row.add(languageName); row.add(languageName);
keyboard.add(row); keyboard.add(row);
@ -936,16 +872,16 @@ public class WeatherHandlers extends TelegramLongPollingBot {
KeyboardRow row = new KeyboardRow(); KeyboardRow row = new KeyboardRow();
row.add(getCancelCommand(language)); row.add(getCancelCommand(language));
keyboard.add(row); keyboard.add(row);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getUnitsKeyboard(String language) { private static ReplyKeyboardMarkup getUnitsKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(false); replyKeyboardMarkupBuilder.oneTimeKeyboard(false);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
KeyboardRow row = new KeyboardRow(); KeyboardRow row = new KeyboardRow();
@ -957,16 +893,16 @@ public class WeatherHandlers extends TelegramLongPollingBot {
row = new KeyboardRow(); row = new KeyboardRow();
row.add(getCancelCommand(language)); row.add(getCancelCommand(language));
keyboard.add(row); keyboard.add(row);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getSettingsKeyboard(String language) { private static ReplyKeyboardMarkup getSettingsKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(false); replyKeyboardMarkupBuilder.oneTimeKeyboard(false);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
KeyboardRow keyboardFirstRow = new KeyboardRow(); KeyboardRow keyboardFirstRow = new KeyboardRow();
@ -977,20 +913,20 @@ public class WeatherHandlers extends TelegramLongPollingBot {
keyboardSecondRow.add(getBackCommand(language)); keyboardSecondRow.add(getBackCommand(language));
keyboard.add(keyboardFirstRow); keyboard.add(keyboardFirstRow);
keyboard.add(keyboardSecondRow); keyboard.add(keyboardSecondRow);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getRecentsKeyboard(Integer userId, String language) { private static ReplyKeyboardMarkup getRecentsKeyboard(Long userId, String language) {
return getRecentsKeyboard(userId, language, true); return getRecentsKeyboard(userId, language, true);
} }
private static ReplyKeyboardMarkup getRecentsKeyboard(Integer userId, String language, boolean allowNew) { private static ReplyKeyboardMarkup getRecentsKeyboard(Long userId, String language, boolean allowNew) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkupBuilder.oneTimeKeyboard(true);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
for (String recentWeather : DatabaseManager.getInstance().getRecentWeather(userId)) { for (String recentWeather : DatabaseManager.getInstance().getRecentWeather(userId)) {
@ -1013,16 +949,16 @@ public class WeatherHandlers extends TelegramLongPollingBot {
row.add(getCancelCommand(language)); row.add(getCancelCommand(language));
keyboard.add(row); keyboard.add(row);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getAlertsKeyboard(String language) { private static ReplyKeyboardMarkup getAlertsKeyboard(String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkupBuilder.oneTimeKeyboard(true);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
@ -1036,20 +972,18 @@ public class WeatherHandlers extends TelegramLongPollingBot {
row.add(getBackCommand(language)); row.add(getBackCommand(language));
keyboard.add(row); keyboard.add(row);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkup; return replyKeyboardMarkupBuilder.build();
} }
private static ReplyKeyboardMarkup getAlertsListKeyboard(Integer userId, String language) { private static ReplyKeyboardMarkup getAlertsListKeyboard(Long userId, String language) {
ReplyKeyboardMarkup replyKeyboardMarkup = null;
List<String> alertCitiesNames = DatabaseManager.getInstance().getAlertCitiesNameByUser(userId); List<String> alertCitiesNames = DatabaseManager.getInstance().getAlertCitiesNameByUser(userId);
if (alertCitiesNames.size() > 0) { if (!alertCitiesNames.isEmpty()) {
replyKeyboardMarkup = new ReplyKeyboardMarkup(); ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder<?, ?> replyKeyboardMarkupBuilder = ReplyKeyboardMarkup.builder();
replyKeyboardMarkup.setSelective(true); replyKeyboardMarkupBuilder.selective(true);
replyKeyboardMarkup.setResizeKeyboard(true); replyKeyboardMarkupBuilder.resizeKeyboard(true);
replyKeyboardMarkup.setOneTimeKeyboard(true); replyKeyboardMarkupBuilder.oneTimeKeyboard(true);
List<KeyboardRow> keyboard = new ArrayList<>(); List<KeyboardRow> keyboard = new ArrayList<>();
for (String alertCityName: alertCitiesNames) { for (String alertCityName: alertCitiesNames) {
@ -1061,10 +995,11 @@ public class WeatherHandlers extends TelegramLongPollingBot {
row.add(getCancelCommand(language)); row.add(getCancelCommand(language));
keyboard.add(row); keyboard.add(row);
replyKeyboardMarkup.setKeyboard(keyboard); replyKeyboardMarkupBuilder.keyboard(keyboard);
return replyKeyboardMarkupBuilder.build();
} }
return replyKeyboardMarkup; return null;
} }
private static ForceReplyKeyboard getForceReply() { private static ForceReplyKeyboard getForceReply() {
@ -1153,37 +1088,31 @@ public class WeatherHandlers extends TelegramLongPollingBot {
private static SendMessage sendChooseOptionMessage(Long chatId, Integer messageId, private static SendMessage sendChooseOptionMessage(Long chatId, Integer messageId,
ReplyKeyboard replyKeyboard, String language) { ReplyKeyboard replyKeyboard, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(chatId.toString(), LocalisationService.getString("chooseOption", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId.toString());
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
sendMessage.setReplyMarkup(replyKeyboard); sendMessage.setReplyMarkup(replyKeyboard);
sendMessage.setText(LocalisationService.getString("chooseOption", language));
return sendMessage; return sendMessage;
} }
private static SendMessage sendHelpMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static SendMessage sendHelpMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(chatId), getHelpMessage(language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
} }
sendMessage.setText(getHelpMessage(language));
return sendMessage; return sendMessage;
} }
private static SendMessage sendRateMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) { private static SendMessage sendRateMessage(Long chatId, Integer messageId, ReplyKeyboardMarkup replyKeyboardMarkup, String language) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage(String.valueOf(chatId), LocalisationService.getString("rateMeMessage", language));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
} }
sendMessage.setText(LocalisationService.getString("rateMeMessage", language));
return sendMessage; return sendMessage;
} }
@ -1196,26 +1125,22 @@ public class WeatherHandlers extends TelegramLongPollingBot {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1];
String weather = WeatherService.getInstance().fetchWeatherForecastByLocation(message.getLocation().getLongitude(), String weather = WeatherService.getInstance().fetchWeatherForecastByLocation(message.getLocation().getLongitude(),
message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem); message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} }
private static SendMessage onForecastWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage onForecastWeatherReceived(Long chatId, Long userId, Integer messageId, String text, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherForecast(text, userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherForecast(text, userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;
@ -1225,26 +1150,22 @@ public class WeatherHandlers extends TelegramLongPollingBot {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(message.getFrom().getId())[1];
String weather = WeatherService.getInstance().fetchWeatherCurrentByLocation(message.getLocation().getLongitude(), String weather = WeatherService.getInstance().fetchWeatherCurrentByLocation(message.getLocation().getLongitude(),
message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem); message.getLocation().getLatitude(), message.getFrom().getId(), language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(String.valueOf(message.getChatId()), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(Long.toString(message.getChatId()));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), MAINMENU);
return sendMessageRequest; return sendMessageRequest;
} }
private static SendMessage onCurrentWeatherReceived(Long chatId, Integer userId, Integer messageId, String text, String language) { private static SendMessage onCurrentWeatherReceived(Long chatId, Long userId, Integer messageId, String text, String language) {
String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1]; String unitsSystem = DatabaseManager.getInstance().getUserWeatherOptions(userId)[1];
String weather = WeatherService.getInstance().fetchWeatherCurrent(text, userId, language, unitsSystem); String weather = WeatherService.getInstance().fetchWeatherCurrent(text, userId, language, unitsSystem);
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage(chatId.toString(), weather);
sendMessageRequest.enableMarkdown(true); sendMessageRequest.enableMarkdown(true);
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(messageId); sendMessageRequest.setReplyToMessageId(messageId);
sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(chatId.toString());
DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU); DatabaseManager.getInstance().insertWeatherState(userId, chatId, MAINMENU);
return sendMessageRequest; return sendMessageRequest;

51
src/main/java/org/telegram/updateshandlers/WebHookExampleHandlers.java

@ -1,40 +1,67 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.telegrambots.bots.TelegramWebhookBot; import org.telegram.BuildVars;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient;
import org.telegram.telegrambots.meta.api.methods.botapimethods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
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.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import org.telegram.telegrambots.webhook.TelegramWebhookBot;
/** /**
* @author pithera * @author pithera
* @version 1.0 * @version 1.0
* Simple Webhook example * Simple Webhook example
*/ */
public class WebHookExampleHandlers extends TelegramWebhookBot { @Slf4j
public class WebHookExampleHandlers implements TelegramWebhookBot {
private final TelegramClient telegramClient;
public WebHookExampleHandlers(String botToken) {
telegramClient = new OkHttpTelegramClient(botToken);
}
@Override @Override
public BotApiMethod onWebhookUpdateReceived(Update update) { public BotApiMethod<?> consumeUpdate(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) { if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = SendMessage
sendMessage.setChatId(update.getMessage().getChatId().toString()); .builder()
sendMessage.setText("Well, all information looks like noise until you break the code."); .chatId(update.getMessage().getChatId().toString())
.text("Well, all information looks like noise until you break the code.")
.build();
return sendMessage; return sendMessage;
} }
return null; return null;
} }
@Override @Override
public String getBotUsername() { public void runDeleteWebhook() {
return BotConfig.WEBHOOK_USER; try {
telegramClient.execute(new DeleteWebhook());
} catch (TelegramApiException e) {
log.info("Error deleting webhook");
}
} }
@Override @Override
public String getBotToken() { public void runSetWebhook() {
return BotConfig.WEBHOOK_TOKEN; try {
telegramClient.execute(SetWebhook
.builder()
.url(BuildVars.EXTERNALWEBHOOKURL + getBotPath())
.build());
} catch (TelegramApiException e) {
log.info("Error setting webhook");
}
} }
@Override @Override
public String getBotPath() { public String getBotPath() {
return BotConfig.WEBHOOK_USER; //arbitrary path to deliver updates on, username is an example. return "/" + BotConfig.WEBHOOK_USER; //arbitrary path to deliver updates on, username is an example.
} }
} }

Loading…
Cancel
Save