Browse Source

Merge pull request #51 from rubenlagus/dev

Dev
master
Ruben Bermudez 2 years ago
committed by GitHub
parent
commit
12b286ed36
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 47
      pom.xml
  2. 2
      src/main/java/org/telegram/Commands.java
  3. 55
      src/main/java/org/telegram/Main.java
  4. 8
      src/main/java/org/telegram/commands/HelloCommand.java
  5. 8
      src/main/java/org/telegram/commands/HelpCommand.java
  6. 8
      src/main/java/org/telegram/commands/StartCommand.java
  7. 7
      src/main/java/org/telegram/commands/StopCommand.java
  8. 18
      src/main/java/org/telegram/database/ConectionDB.java
  9. 12
      src/main/java/org/telegram/database/DatabaseManager.java
  10. 7
      src/main/java/org/telegram/services/DirectionsService.java
  11. 11
      src/main/java/org/telegram/services/RaeService.java
  12. 12
      src/main/java/org/telegram/services/TimerExecutor.java
  13. 50
      src/main/java/org/telegram/services/TransifexService.java
  14. 33
      src/main/java/org/telegram/services/WeatherService.java
  15. 23
      src/main/java/org/telegram/updateshandlers/ChannelHandlers.java
  16. 22
      src/main/java/org/telegram/updateshandlers/CommandsHandler.java
  17. 35
      src/main/java/org/telegram/updateshandlers/DirectionsHandlers.java
  18. 8
      src/main/java/org/telegram/updateshandlers/ElektrollArtFanHandler.java
  19. 43
      src/main/java/org/telegram/updateshandlers/FilesHandlers.java
  20. 20
      src/main/java/org/telegram/updateshandlers/RaeHandlers.java
  21. 21
      src/main/java/org/telegram/updateshandlers/TransifexHandlers.java
  22. 53
      src/main/java/org/telegram/updateshandlers/WeatherHandlers.java
  23. 2
      src/main/resources/strings.properties
  24. 2
      src/main/resources/strings_eo.properties
  25. 2
      src/main/resources/strings_es.properties
  26. 2
      src/main/resources/strings_it.properties
  27. 2
      src/main/resources/strings_nl.properties
  28. 2
      src/main/resources/strings_pt.properties

47
pom.xml

@ -11,15 +11,32 @@
<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.3</httpcompontents.version> <httpcompontents.version>4.5.13</httpcompontents.version>
<telegrambots.version>4.0.1</telegrambots.version> <telegrambots.version>5.0.1.1</telegrambots.version>
<json.version>20160810</json.version> <json.version>20201115</json.version>
<jsoup.version>1.10.2</jsoup.version> <jsoup.version>1.13.1</jsoup.version>
<mysql.version>6.0.6</mysql.version> <mysql.version>8.0.23</mysql.version>
<commonsio.version>2.5</commonsio.version> <commonsio.version>2.8.0</commonsio.version>
<lombok.version>1.18.16</lombok.version>
</properties> </properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.telegram</groupId> <groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId> <artifactId>telegrambots</artifactId>
@ -146,24 +163,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.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>

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

@ -26,6 +26,8 @@ public class Commands {
public static final String help = commandInitChar + "help"; public static final String help = commandInitChar + "help";
/// Upload command /// Upload command
public static final String uploadCommand = commandInitChar + "upload"; public static final String uploadCommand = commandInitChar + "upload";
/// Report command
public static final String reportCommand = commandInitChar + "report";
/// Start command /// Start command
public static final String startCommand = commandInitChar + "start"; public static final String startCommand = commandInitChar + "start";
/// Cancel command /// Cancel command

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

@ -1,15 +1,12 @@
package org.telegram; package org.telegram;
import org.telegram.telegrambots.ApiContextInitializer; import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.TelegramBotsApi; import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger; import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import org.telegram.telegrambots.meta.logging.BotsFileHandler; import org.telegram.telegrambots.updatesreceivers.DefaultWebhook;
import org.telegram.updateshandlers.*; import org.telegram.updateshandlers.WeatherHandlers;
import org.telegram.updateshandlers.WebHookExampleHandlers;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
@ -17,36 +14,26 @@ import java.util.logging.Level;
* @brief Main class to create all bots * @brief Main class to create all bots
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
@Slf4j
public class Main { public class Main {
private static final String LOGTAG = "MAIN";
public static void main(String[] args) { public static void main(String[] args) {
BotLogger.setLevel(Level.ALL);
BotLogger.registerLogger(new ConsoleHandler());
try {
BotLogger.registerLogger(new BotsFileHandler());
} catch (IOException e) {
BotLogger.severe(LOGTAG, e);
}
try { try {
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = createTelegramBotsApi(); TelegramBotsApi telegramBotsApi = createTelegramBotsApi();
try { try {
// Register long polling bots. They work regardless type of TelegramBotsApi we are creating // Register long polling bots. They work regardless type of TelegramBotsApi we are creating
telegramBotsApi.registerBot(new ChannelHandlers()); // telegramBotsApi.registerBot(new ChannelHandlers());
telegramBotsApi.registerBot(new DirectionsHandlers()); // telegramBotsApi.registerBot(new DirectionsHandlers());
telegramBotsApi.registerBot(new RaeHandlers()); // telegramBotsApi.registerBot(new RaeHandlers());
telegramBotsApi.registerBot(new WeatherHandlers()); telegramBotsApi.registerBot(new WeatherHandlers());
telegramBotsApi.registerBot(new TransifexHandlers()); // telegramBotsApi.registerBot(new TransifexHandlers());
telegramBotsApi.registerBot(new FilesHandlers()); // telegramBotsApi.registerBot(new FilesHandlers());
telegramBotsApi.registerBot(new CommandsHandler(BotConfig.COMMANDS_USER)); // telegramBotsApi.registerBot(new CommandsHandler(BotConfig.COMMANDS_USER));
telegramBotsApi.registerBot(new ElektrollArtFanHandler()); // telegramBotsApi.registerBot(new ElektrollArtFanHandler());
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -58,11 +45,11 @@ public class Main {
} else if (!BuildVars.pathToCertificatePublicKey.isEmpty()) { } 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. // 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 = createSelfSignedTelegramBotsApi();
telegramBotsApi.registerBot(new WebHookExampleHandlers()); telegramBotsApi.registerBot(new WebHookExampleHandlers(), null);
} else { } else {
// Non self signed, make sure you've added private/public and if needed intermediate to your cert-store. // Non self signed, make sure you've added private/public and if needed intermediate to your cert-store.
telegramBotsApi = createNoSelfSignedTelegramBotsApi(); telegramBotsApi = createNoSelfSignedTelegramBotsApi();
telegramBotsApi.registerBot(new WebHookExampleHandlers()); telegramBotsApi.registerBot(new WebHookExampleHandlers(), null);
} }
return telegramBotsApi; return telegramBotsApi;
} }
@ -71,8 +58,8 @@ public class Main {
* @brief Creates a Telegram Bots Api to use Long Polling (getUpdates) bots. * @brief Creates a Telegram Bots Api to use Long Polling (getUpdates) bots.
* @return TelegramBotsApi to register the bots. * @return TelegramBotsApi to register the bots.
*/ */
private static TelegramBotsApi createLongPollingTelegramBotsApi() { private static TelegramBotsApi createLongPollingTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(); return new TelegramBotsApi(DefaultBotSession.class);
} }
/** /**
@ -83,7 +70,7 @@ public class Main {
* @note Don't forget to split the pem bundle (begin/end), use only the public key as input! * @note Don't forget to split the pem bundle (begin/end), use only the public key as input!
*/ */
private static TelegramBotsApi createSelfSignedTelegramBotsApi() throws TelegramApiException { private static TelegramBotsApi createSelfSignedTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(BuildVars.pathToCertificateStore, BuildVars.certificateStorePassword, BuildVars.EXTERNALWEBHOOKURL, BuildVars.INTERNALWEBHOOKURL, BuildVars.pathToCertificatePublicKey); return new TelegramBotsApi(DefaultBotSession.class, new DefaultWebhook());
} }
/** /**
@ -99,6 +86,6 @@ public class Main {
* @endcode * @endcode
*/ */
private static TelegramBotsApi createNoSelfSignedTelegramBotsApi() throws TelegramApiException { private static TelegramBotsApi createNoSelfSignedTelegramBotsApi() throws TelegramApiException {
return new TelegramBotsApi(BuildVars.pathToCertificateStore, BuildVars.certificateStorePassword, BuildVars.EXTERNALWEBHOOKURL, BuildVars.INTERNALWEBHOOKURL); return new TelegramBotsApi(DefaultBotSession.class, new DefaultWebhook());
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.commands; package org.telegram.commands;
import lombok.extern.slf4j.Slf4j;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand; 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;
@ -7,7 +8,6 @@ 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.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
/** /**
* This command simply replies with a hello to the users command and * This command simply replies with a hello to the users command and
@ -15,10 +15,8 @@ import org.telegram.telegrambots.meta.logging.BotLogger;
* *
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@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");
} }
@ -49,7 +47,7 @@ public class HelloCommand extends BotCommand {
try { try {
absSender.execute(answer); absSender.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.commands; package org.telegram.commands;
import lombok.extern.slf4j.Slf4j;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand; import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.IBotCommand; import org.telegram.telegrambots.extensions.bots.commandbot.commands.IBotCommand;
@ -9,17 +10,14 @@ 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.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
/** /**
* This command helps the user to find the command they need * This command helps the user to find the command they need
* *
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@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) {
@ -49,7 +47,7 @@ public class HelpCommand extends BotCommand {
try { try {
absSender.execute(helpMessage); absSender.execute(helpMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.commands; package org.telegram.commands;
import lombok.extern.slf4j.Slf4j;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand; 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;
@ -7,17 +8,14 @@ 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.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
/** /**
* This commands starts the conversation with the bot * This commands starts the conversation with the bot
* *
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@Slf4j
public class StartCommand extends BotCommand { public class StartCommand extends BotCommand {
public static final String LOGTAG = "STARTCOMMAND";
public StartCommand() { public StartCommand() {
super("start", "With this command you can start the Bot"); super("start", "With this command you can start the Bot");
} }
@ -45,7 +43,7 @@ public class StartCommand extends BotCommand {
try { try {
absSender.execute(answer); absSender.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.commands; package org.telegram.commands;
import lombok.extern.slf4j.Slf4j;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
import org.telegram.telegrambots.extensions.bots.commandbot.commands.BotCommand; 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;
@ -7,7 +8,6 @@ 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.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
/** /**
* This commands stops the conversation with the bot. * This commands stops the conversation with the bot.
@ -15,10 +15,9 @@ import org.telegram.telegrambots.meta.logging.BotLogger;
* *
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@Slf4j
public class StopCommand extends BotCommand { public class StopCommand extends BotCommand {
public static final String LOGTAG = "STOPCOMMAND";
/** /**
* Construct * Construct
*/ */
@ -41,7 +40,7 @@ public class StopCommand extends BotCommand {
try { try {
absSender.execute(answer); absSender.execute(answer);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

18
src/main/java/org/telegram/database/ConectionDB.java

@ -7,18 +7,24 @@
*/ */
package org.telegram.database; package org.telegram.database;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.sql.*; import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 2.0 * @version 2.0
* Connector to database * Connector to database
*/ */
@Slf4j
public class ConectionDB { public class ConectionDB {
private static final String LOGTAG = "CONNECTIONDB";
private Connection currentConection; private Connection currentConection;
public ConectionDB() { public ConectionDB() {
@ -31,7 +37,7 @@ public class ConectionDB {
Class.forName(BuildVars.controllerDB).newInstance(); Class.forName(BuildVars.controllerDB).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 e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return connection; return connection;
@ -41,7 +47,7 @@ public class ConectionDB {
try { try {
this.currentConection.close(); this.currentConection.close();
} catch (SQLException e) { } catch (SQLException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -80,7 +86,7 @@ public class ConectionDB {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return max; return max;
} }

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

@ -7,8 +7,8 @@
*/ */
package org.telegram.database; package org.telegram.database;
import lombok.extern.slf4j.Slf4j;
import org.telegram.structure.WeatherAlert; import org.telegram.structure.WeatherAlert;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -21,12 +21,10 @@ import java.util.List;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 2.0 * @version 2.0
* @brief Database Manager to perform database operations * Database Manager to perform database operations
* @date 3/12/14
*/ */
@Slf4j
public class DatabaseManager { public class DatabaseManager {
private static final String LOGTAG = "DATABASEMANAGER";
private static volatile DatabaseManager instance; private static volatile DatabaseManager instance;
private static volatile ConectionDB connetion; private static volatile ConectionDB connetion;
@ -36,7 +34,7 @@ public class DatabaseManager {
private DatabaseManager() { private DatabaseManager() {
connetion = new ConectionDB(); connetion = new ConectionDB();
final int currentVersion = connetion.checkVersion(); final int currentVersion = connetion.checkVersion();
BotLogger.info(LOGTAG, "Current db version: " + currentVersion); log.info("Current db version: " + currentVersion);
if (currentVersion < CreationStrings.version) { if (currentVersion < CreationStrings.version) {
recreateTable(currentVersion); recreateTable(currentVersion);
} }
@ -94,7 +92,7 @@ public class DatabaseManager {
} }
connetion.commitTransaction(); connetion.commitTransaction();
} catch (SQLException e) { } catch (SQLException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@ -12,7 +13,6 @@ import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
@ -26,9 +26,8 @@ import java.util.List;
* @brief Weather service * @brief Weather service
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
@Slf4j
public class DirectionsService { public class DirectionsService {
private static final String LOGTAG = "DIRECTIONSSERVICE";
private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST private static final String BASEURL = "https://maps.googleapis.com/maps/api/directions/json"; ///< Base url for REST
private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey; private static final String APIIDEND = "&key=" + BuildVars.DirectionsApiKey;
private static final String PARAMS = "&language=@language@&units=metric"; private static final String PARAMS = "&language=@language@&units=metric";
@ -98,7 +97,7 @@ public class DirectionsService {
responseToUser.add(LocalisationService.getString("directionsNotFound", language)); responseToUser.add(LocalisationService.getString("directionsNotFound", language));
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.warn(LOGTAG, e); log.warn(e.getLocalizedMessage(), e);
responseToUser.add(LocalisationService.getString("errorFetchingDirections", language)); responseToUser.add(LocalisationService.getString("errorFetchingDirections", language));
} }
return responseToUser; return responseToUser;

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

@ -1,5 +1,6 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -12,7 +13,6 @@ import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder; import java.net.URLEncoder;
@ -27,9 +27,8 @@ import java.util.Map;
* @brief Rae service * @brief Rae service
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
@Slf4j
public class RaeService { public class RaeService {
private static final String LOGTAG = "RAESERVICE";
private static final String BASEURL = "http://dle.rae.es/srv/"; ///< Base url for REST private static final String BASEURL = "http://dle.rae.es/srv/"; ///< Base url for REST
private static final String SEARCHEXACTURL = "search?m=30&w="; private static final String SEARCHEXACTURL = "search?m=30&w=";
private static final String SEARCHWORDURL = "search?m=form&w="; private static final String SEARCHWORDURL = "search?m=form&w=";
@ -66,7 +65,7 @@ public class RaeService {
results = getResultsFromExactMatch(elements, query, articleId); results = getResultsFromExactMatch(elements, query, articleId);
} }
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return results; return results;
@ -103,7 +102,7 @@ public class RaeService {
} }
} }
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return results; return results;
@ -137,7 +136,7 @@ public class RaeService {
results = getResultsFromExactMatch(elements, word, articleId); results = getResultsFromExactMatch(elements, word, articleId);
} }
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return results; return results;

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

@ -1,6 +1,6 @@
package org.telegram.services; package org.telegram.services;
import org.telegram.telegrambots.meta.logging.BotLogger; import lombok.extern.slf4j.Slf4j;
import java.time.Clock; import java.time.Clock;
import java.time.Duration; import java.time.Duration;
@ -14,8 +14,8 @@ import java.util.concurrent.TimeUnit;
* @version 2.0 * @version 2.0
* Execute a task periodically * Execute a task periodically
*/ */
@Slf4j
public class TimerExecutor { public class TimerExecutor {
private static final String LOGTAG = "TIMEREXECUTOR";
private static volatile TimerExecutor instance; ///< Instance private static volatile TimerExecutor instance; ///< Instance
private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); ///< Thread to execute operations private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); ///< Thread to execute operations
@ -55,14 +55,14 @@ 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) {
BotLogger.warn(LOGTAG, "Posting new task" + task.getTaskName()); log.warn("Posting new task" + task.getTaskName());
final Runnable taskWrapper = () -> { final Runnable taskWrapper = () -> {
try { try {
task.execute(); task.execute();
task.reduceTimes(); task.reduceTimes();
startExecutionEveryDayAt(task, targetHour, targetMin, targetSec); startExecutionEveryDayAt(task, targetHour, targetMin, targetSec);
} catch (Exception e) { } catch (Exception e) {
BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e); log.error("Bot threw an unexpected exception at TimerExecutor", e);
} }
}; };
if (task.getTimes() != 0) { if (task.getTimes() != 0) {
@ -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) {
BotLogger.severe(LOGTAG, ex); log.error(ex.getLocalizedMessage(), ex);
} catch (Exception e) { } catch (Exception e) {
BotLogger.severe(LOGTAG, "Bot threw an unexpected exception at TimerExecutor", e); log.error(e.getLocalizedMessage(), "Bot threw an unexpected exception at TimerExecutor", e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@ -9,7 +10,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument; import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
import org.telegram.telegrambots.meta.logging.BotLogger; import org.telegram.telegrambots.meta.api.objects.InputFile;
import java.io.*; import java.io.*;
@ -19,9 +20,8 @@ import java.io.*;
* @brief Service that allow transifex files download * @brief Service that allow transifex files download
* @date 21 of June of 2015 * @date 21 of June of 2015
*/ */
@Slf4j
public class TransifexService { public class TransifexService {
private static final String LOGTAG = "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 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 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 BASEURLOSX = "http://" + BuildVars.TRANSIFEXUSER + ":" + BuildVars.TRANSIFEXPASSWORD + "@www.transifex.com/api/2/project/osx/resource/localizablestrings/translation/@language?file"; ///< Base url for REST
@ -77,7 +77,7 @@ public class TransifexService {
result = responseString; result = responseString;
} }
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -90,7 +90,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -103,7 +103,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -116,7 +116,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -129,7 +129,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), "UTF-8"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), "UTF-8");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -142,7 +142,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -155,7 +155,7 @@ public class TransifexService {
HttpResponse response = client.execute(request); HttpResponse response = client.execute(request);
result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE"); result = IOUtils.toByteArray(new InputStreamReader(response.getEntity().getContent(), "UTF-16LE"), "UTF-16LE");
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return result; return result;
} }
@ -193,13 +193,13 @@ public class TransifexService {
localFile.close(); localFile.close();
File fileToUpload = new File(fileName); File fileToUpload = new File(fileName);
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return sendDocument; return sendDocument;
} }
@ -220,13 +220,13 @@ public class TransifexService {
localFile.close(); localFile.close();
File fileToUpload = new File(fileName); File fileToUpload = new File(fileName);
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return sendDocument; return sendDocument;
} }
@ -248,13 +248,13 @@ public class TransifexService {
IOUtils.write(file, output); IOUtils.write(file, output);
output.close(); output.close();
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return sendDocument; return sendDocument;
} }
@ -275,13 +275,13 @@ public class TransifexService {
IOUtils.write(file, output); IOUtils.write(file, output);
output.close(); output.close();
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} catch (IOException e) { } catch (IOException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
return sendDocument; return sendDocument;
} }
@ -303,7 +303,7 @@ public class TransifexService {
output.close(); output.close();
if (fileToUpload.exists()) { if (fileToUpload.exists()) {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -332,7 +332,7 @@ public class TransifexService {
output.close(); output.close();
if (fileToUpload.exists()) { if (fileToUpload.exists()) {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -361,7 +361,7 @@ public class TransifexService {
output.close(); output.close();
if (fileToUpload.exists()) { if (fileToUpload.exists()) {
sendDocument = new SendDocument(); sendDocument = new SendDocument();
sendDocument.setDocument(fileToUpload); sendDocument.setDocument(new InputFile(fileToUpload));
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

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

@ -1,5 +1,6 @@
package org.telegram.services; package org.telegram.services;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -11,7 +12,6 @@ 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 org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
@ -26,9 +26,8 @@ import java.time.format.DateTimeFormatter;
* @brief Weather service * @brief Weather service
* @date 20 of June of 2015 * @date 20 of June of 2015
*/ */
@Slf4j
public class WeatherService { public class WeatherService {
private static final String LOGTAG = "WEATHERSERVICE";
public static final String METRICSYSTEM = "metric"; public static final String METRICSYSTEM = "metric";
public static final String IMPERIALSYSTEM = "imperial"; public static final String IMPERIALSYSTEM = "imperial";
@ -91,7 +90,7 @@ public class WeatherService {
String responseString = EntityUtils.toString(buf, "UTF-8"); String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString); JSONObject jsonObject = new JSONObject(responseString);
BotLogger.info(LOGTAG, jsonObject.toString()); log.info(jsonObject.toString());
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") + ")";
@ -99,11 +98,11 @@ 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 {
BotLogger.warn(LOGTAG, jsonObject.toString()); log.warn(jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -132,7 +131,7 @@ public class WeatherService {
String responseString = EntityUtils.toString(buf, "UTF-8"); String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString); JSONObject jsonObject = new JSONObject(responseString);
BotLogger.info(LOGTAG, jsonObject.toString()); log.info(jsonObject.toString());
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") + ")";
@ -140,11 +139,11 @@ 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 {
BotLogger.warn(LOGTAG, jsonObject.toString()); log.warn(jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -156,7 +155,7 @@ 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(Float longitude, Float latitude, Integer userId, String language, String units) { public String fetchWeatherForecastByLocation(Double longitude, Double latitude, Integer userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
@ -179,11 +178,11 @@ 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 {
BotLogger.warn(LOGTAG, jsonObject.toString()); log.warn(jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -220,11 +219,11 @@ 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 {
BotLogger.warn(LOGTAG, jsonObject.toString()); log.warn(jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;
@ -236,7 +235,7 @@ 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(Float longitude, Float latitude, Integer userId, String language, String units) { public String fetchWeatherCurrentByLocation(Double longitude, Double latitude, Integer userId, String language, String units) {
String cityFound; String cityFound;
String responseToUser; String responseToUser;
try { try {
@ -259,11 +258,11 @@ 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 {
BotLogger.warn(LOGTAG, jsonObject.toString()); log.warn(jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language); responseToUser = LocalisationService.getString("cityNotFound", language);
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language); responseToUser = LocalisationService.getString("errorFetchingWeather", language);
} }
return responseToUser; return responseToUser;

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

@ -1,5 +1,6 @@
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.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
@ -8,7 +9,6 @@ import org.telegram.telegrambots.meta.api.objects.Update;
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.logging.BotLogger;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -20,9 +20,8 @@ import java.util.concurrent.ConcurrentHashMap;
* 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 * @date 24 of June of 2015
*/ */
@Slf4j
public class ChannelHandlers extends TelegramLongPollingBot { public class ChannelHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "CHANNELHANDLERS";
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.";
@ -42,11 +41,11 @@ public class ChannelHandlers extends TelegramLongPollingBot {
try { try {
handleIncomingMessage(message); handleIncomingMessage(message);
} catch (InvalidObjectException e) { } catch (InvalidObjectException e) {
BotLogger.severe(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -92,7 +91,7 @@ public class ChannelHandlers extends TelegramLongPollingBot {
} }
} }
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -114,7 +113,7 @@ public class ChannelHandlers extends TelegramLongPollingBot {
private void sendErrorMessage(Message message, String errorText) { private void sendErrorMessage(Message message, String errorText) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); 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.setText(String.format(ERROR_MESSAGE_TEXT, message.getText().trim(), errorText.replace("\"", "\\\"")));
@ -123,14 +122,14 @@ public class ChannelHandlers extends TelegramLongPollingBot {
try { try {
execute(sendMessage); execute(sendMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
private static SendMessage getWrongUsernameMessage(Message message) { private static SendMessage getWrongUsernameMessage(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard(); ForceReplyKeyboard forceReplyKeyboard = new ForceReplyKeyboard();
@ -145,7 +144,7 @@ public class ChannelHandlers extends TelegramLongPollingBot {
private static SendMessage getMessageToChannelSent(Message message) { private static SendMessage getMessageToChannelSent(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(AFTER_CHANNEL_TEXT); sendMessage.setText(AFTER_CHANNEL_TEXT);
@ -155,7 +154,7 @@ public class ChannelHandlers extends TelegramLongPollingBot {
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();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
@ -165,7 +164,7 @@ public class ChannelHandlers extends TelegramLongPollingBot {
try { try {
execute(sendMessage); execute(sendMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.commands.HelloCommand; import org.telegram.commands.HelloCommand;
import org.telegram.commands.HelpCommand; import org.telegram.commands.HelpCommand;
@ -12,23 +13,23 @@ import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message; 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.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
/** /**
* This handler mainly works with commands to demonstrate the Commands feature of the API * This handler mainly works with commands to demonstrate the Commands feature of the API
* *
* @author Timo Schulz (Mit0x2) * @author Timo Schulz (Mit0x2)
*/ */
@Slf4j
public class CommandsHandler extends TelegramLongPollingCommandBot { public class CommandsHandler extends TelegramLongPollingCommandBot {
public static final String LOGTAG = "COMMANDSHANDLER"; private final String botUsername;
/** /**
* Constructor. * Constructor.
*/ */
public CommandsHandler(String botUsername) { public CommandsHandler(String botUsername) {
super(botUsername); super();
this.botUsername = botUsername;
register(new HelloCommand()); register(new HelloCommand());
register(new StartCommand()); register(new StartCommand());
register(new StopCommand()); register(new StopCommand());
@ -37,17 +38,22 @@ public class CommandsHandler extends TelegramLongPollingCommandBot {
registerDefaultAction((absSender, message) -> { registerDefaultAction((absSender, message) -> {
SendMessage commandUnknownMessage = new SendMessage(); SendMessage commandUnknownMessage = new SendMessage();
commandUnknownMessage.setChatId(message.getChatId()); commandUnknownMessage.setChatId(Long.toString(message.getChatId()));
commandUnknownMessage.setText("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); absSender.execute(commandUnknownMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
helpCommand.execute(absSender, message.getFrom(), message.getChat(), new String[] {}); helpCommand.execute(absSender, message.getFrom(), message.getChat(), new String[] {});
}); });
} }
@Override
public String getBotUsername() {
return botUsername;
}
@Override @Override
public void processNonCommandUpdate(Update update) { public void processNonCommandUpdate(Update update) {
@ -60,13 +66,13 @@ public class CommandsHandler extends TelegramLongPollingCommandBot {
if (message.hasText()) { if (message.hasText()) {
SendMessage echoMessage = new SendMessage(); SendMessage echoMessage = new SendMessage();
echoMessage.setChatId(message.getChatId()); echoMessage.setChatId(Long.toString(message.getChatId()));
echoMessage.setText("Hey heres your message:\n" + message.getText()); echoMessage.setText("Hey heres your message:\n" + message.getText());
try { try {
execute(echoMessage); execute(echoMessage);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -1,5 +1,6 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
@ -16,7 +17,6 @@ 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.logging.BotLogger;
import org.telegram.telegrambots.meta.updateshandlers.SentCallback; import org.telegram.telegrambots.meta.updateshandlers.SentCallback;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
@ -30,9 +30,8 @@ import java.util.concurrent.ConcurrentLinkedQueue;
* @brief Handler for updates to Directions Bot * @brief Handler for updates to Directions Bot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
@Slf4j
public class DirectionsHandlers extends TelegramLongPollingBot { public class DirectionsHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "DIRECTIONSHANDLERS";
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<Integer> languageMessages = new ConcurrentLinkedQueue<>();
@ -48,7 +47,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
try { try {
handleDirections(update); handleDirections(update);
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -88,11 +87,11 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getString("youNeedReplyDirections", language)); sendMessageRequest.setText(LocalisationService.getString("youNeedReplyDirections", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }
@ -106,7 +105,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
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 sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove(); ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove();
replyKeyboardRemove.setSelective(true); replyKeyboardRemove.setSelective(true);
sendMessageRequest.setReplyMarkup(replyKeyboardRemove); sendMessageRequest.setReplyMarkup(replyKeyboardRemove);
@ -131,7 +130,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
} }
}); });
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -139,7 +138,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
private void onOriginReceived(Message message, String language) { private void onOriginReceived(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); 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);
@ -165,7 +164,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
} }
}); });
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -176,17 +175,17 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
LocalisationService.getString("helpDirections", language), LocalisationService.getString("helpDirections", language),
Commands.startDirectionCommand); Commands.startDirectionCommand);
sendMessageRequest.setText(helpDirectionsFormated); sendMessageRequest.setText(helpDirectionsFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
private void onStartdirectionsCommand(Message message, String language) { private void onStartdirectionsCommand(Message message, String language) {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); 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);
@ -212,14 +211,14 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
} }
}); });
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), 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();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); 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<>();
@ -238,14 +237,14 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
execute(sendMessageRequest); execute(sendMessageRequest);
languageMessages.add(message.getFrom().getId()); languageMessages.add(message.getFrom().getId());
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), 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 sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(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())); sendMessageRequest.setText(LocalisationService.getString("languageModified", parts[0].trim()));
@ -260,7 +259,7 @@ public class DirectionsHandlers extends TelegramLongPollingBot {
execute(sendMessageRequest); execute(sendMessageRequest);
languageMessages.remove(message.getFrom().getId()); languageMessages.remove(message.getFrom().getId());
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }

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

@ -198,15 +198,15 @@ public class ElektrollArtFanHandler extends TelegramLongPollingBot {
List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>(); List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
List<InlineKeyboardButton> rowInline = new ArrayList<>(); List<InlineKeyboardButton> rowInline = new ArrayList<>();
rowInline.add(new InlineKeyboardButton().setText(this.urls.get(index)[2]).setCallbackData("gallery:text:" + index)); rowInline.add(InlineKeyboardButton.builder().text(this.urls.get(index)[2]).callbackData("gallery:text:" + index).build());
List<InlineKeyboardButton> rowInline2 = new ArrayList<>(); List<InlineKeyboardButton> rowInline2 = new ArrayList<>();
rowInline2.add(new InlineKeyboardButton().setText(BACK).setCallbackData("gallery:back:" + index)); rowInline2.add(InlineKeyboardButton.builder().text(BACK).callbackData("gallery:back:" + index).build());
rowInline2.add(new InlineKeyboardButton().setText(NEXT).setCallbackData("gallery:next:" + index)); rowInline2.add(InlineKeyboardButton.builder().text(NEXT).callbackData("gallery:next:" + index).build());
List<InlineKeyboardButton> rowInline3 = new ArrayList<>(); List<InlineKeyboardButton> rowInline3 = new ArrayList<>();
rowInline3.add(new InlineKeyboardButton().setText("Link").setUrl(this.urls.get(index)[0])); rowInline3.add(InlineKeyboardButton.builder().text("Link").url(this.urls.get(index)[0]).build());
rowsInline.add(rowInline); rowsInline.add(rowInline);

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

@ -1,5 +1,6 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
@ -8,6 +9,7 @@ import org.telegram.services.LocalisationService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramLongPollingBot;
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.Message; 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.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
@ -15,7 +17,6 @@ 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.logging.BotLogger;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,12 +28,11 @@ import java.util.concurrent.ConcurrentLinkedQueue;
/** /**
* @author Ruben Bermudez * @author Ruben Bermudez
* @version 1.0 * @version 1.0
* @brief Handler for updates to Files Bot * Handler for updates to Files Bot
* This bot is an example for the use of sendMessage asynchronously * This bot is an example for the use of sendMessage asynchronously
* @date 24 of June of 2015
*/ */
@Slf4j
public class FilesHandlers extends TelegramLongPollingBot { public class FilesHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "FILESHANDLERS";
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;
@ -48,7 +48,12 @@ public class FilesHandlers extends TelegramLongPollingBot {
try { try {
if (update.hasMessage()) { if (update.hasMessage()) {
try { try {
handleFileUpdate(update); SendMessage sendMessageRequest = new SendMessage();
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) {
@ -56,11 +61,11 @@ public class FilesHandlers extends TelegramLongPollingBot {
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.severe(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -108,7 +113,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(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(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest); execute(sendMessageRequest);
} }
} }
@ -126,7 +131,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("noFiles", language)); sendMessageRequest.setText(LocalisationService.getString("noFiles", language));
} }
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
sendMessageRequest.setReplyMarkup(new ReplyKeyboardRemove()); sendMessageRequest.setReplyMarkup(new ReplyKeyboardRemove());
execute(sendMessageRequest); execute(sendMessageRequest);
} }
@ -144,7 +149,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
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();
sendMessageRequest.setText(LocalisationService.getString("deleteUploadedFile", language)); sendMessageRequest.setText(LocalisationService.getString("deleteUploadedFile", language));
sendMessageRequest.setChatId(message.getChatId()); 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 = new ReplyKeyboardMarkup();
if (files.size() > 0) { if (files.size() > 0) {
@ -172,7 +177,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
} else { } else {
sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language)); sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language));
} }
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest); execute(sendMessageRequest);
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
@ -183,7 +188,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId()); DatabaseManager.getInstance().deleteUserForFile(message.getFrom().getId());
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getString("processFinished", language)); sendMessageRequest.setText(LocalisationService.getString("processFinished", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest); execute(sendMessageRequest);
} }
@ -191,7 +196,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
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();
sendMessageRequest.setText(LocalisationService.getString("sendFileToUpload", language)); sendMessageRequest.setText(LocalisationService.getString("sendFileToUpload", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest); execute(sendMessageRequest);
} }
@ -202,27 +207,27 @@ public class FilesHandlers extends TelegramLongPollingBot {
Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand, Commands.startCommand, Commands.uploadCommand, Commands.deleteCommand,
Commands.listCommand); Commands.listCommand);
sendMessageRequest.setText(formatedString); sendMessageRequest.setText(formatedString);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
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 InvalidObjectException, TelegramApiException {
if (DatabaseManager.getInstance().doesFileExists(part.trim())) { if (DatabaseManager.getInstance().doesFileExists(part.trim())) {
SendDocument sendDocumentRequest = new SendDocument(); SendDocument sendDocumentRequest = new SendDocument();
sendDocumentRequest.setDocument(part.trim()); sendDocumentRequest.setDocument(new InputFile(part.trim()));
sendDocumentRequest.setChatId(message.getChatId()); sendDocumentRequest.setChatId(Long.toString(message.getChatId()));
execute(sendDocumentRequest); execute(sendDocumentRequest);
} else { } else {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language)); sendMessageRequest.setText(LocalisationService.getString("wrongFileId", language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
execute(sendMessageRequest); execute(sendMessageRequest);
} }
} }
private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException, TelegramApiException { private void onSetLanguageCommand(Message message, String language) throws InvalidObjectException, TelegramApiException {
SendMessage sendMessageRequest = new SendMessage(); SendMessage sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup(); 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<>();
@ -244,7 +249,7 @@ public class FilesHandlers extends TelegramLongPollingBot {
private void onLanguageReceived(Message message) throws InvalidObjectException, TelegramApiException { private void onLanguageReceived(Message message) throws InvalidObjectException, 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 sendMessageRequest = new SendMessage();
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(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())); sendMessageRequest.setText(LocalisationService.getString("languageModified", parts[0].trim()));

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

@ -1,9 +1,11 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.services.RaeService; import org.telegram.services.RaeService;
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.bots.TelegramLongPollingBot;
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.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.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
@ -12,7 +14,6 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.inputmessageconten
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.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -23,9 +24,8 @@ import java.util.List;
* @brief Handler for inline queries in Raebot * @brief Handler for inline queries in Raebot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
@Slf4j
public class RaeHandlers extends TelegramLongPollingBot { public class RaeHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "RAEHANDLERS";
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";
@ -50,11 +50,11 @@ public class RaeHandlers extends TelegramLongPollingBot {
try { try {
execute(getHelpMessage(update.getMessage())); execute(getHelpMessage(update.getMessage()));
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -69,7 +69,7 @@ public class RaeHandlers extends TelegramLongPollingBot {
*/ */
private void handleIncomingInlineQuery(InlineQuery inlineQuery) { private void handleIncomingInlineQuery(InlineQuery inlineQuery) {
String query = inlineQuery.getQuery(); String query = inlineQuery.getQuery();
BotLogger.debug(LOGTAG, "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);
@ -78,7 +78,7 @@ public class RaeHandlers extends TelegramLongPollingBot {
execute(converteResultsToResponse(inlineQuery, new ArrayList<>())); execute(converteResultsToResponse(inlineQuery, new ArrayList<>()));
} }
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -107,8 +107,8 @@ 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(); InputTextMessageContent messageContent = new InputTextMessageContent();
messageContent.disableWebPagePreview(); messageContent.setDisableWebPagePreview(true);
messageContent.enableMarkdown(true); messageContent.setParseMode(ParseMode.MARKDOWN);
messageContent.setMessageText(raeResult.getDefinition()); messageContent.setMessageText(raeResult.getDefinition());
InlineQueryResultArticle article = new InlineQueryResultArticle(); InlineQueryResultArticle article = new InlineQueryResultArticle();
article.setInputMessageContent(messageContent); article.setInputMessageContent(messageContent);
@ -129,7 +129,7 @@ public class RaeHandlers extends TelegramLongPollingBot {
*/ */
private static SendMessage getHelpMessage(Message message) { private static SendMessage getHelpMessage(Message message) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setText(helpMessage); sendMessage.setText(helpMessage);
return sendMessage; return sendMessage;

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

@ -1,5 +1,6 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.BuildVars; import org.telegram.BuildVars;
import org.telegram.Commands; import org.telegram.Commands;
@ -14,7 +15,6 @@ 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.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.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.logging.BotLogger;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.util.ArrayList; import java.util.ArrayList;
@ -26,9 +26,8 @@ import java.util.List;
* @brief Handler for updates to Transifex Bot * @brief Handler for updates to Transifex Bot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
@Slf4j
public class TransifexHandlers extends TelegramLongPollingBot { public class TransifexHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "TRANSIFEXHANDLERS";
@Override @Override
public String getBotToken() { public String getBotToken() {
return BotConfig.TRANSIFEX_TOKEN; return BotConfig.TRANSIFEX_TOKEN;
@ -39,7 +38,7 @@ public class TransifexHandlers extends TelegramLongPollingBot {
try { try {
handleUpdate(update); handleUpdate(update);
} catch (Throwable e) { } catch (Throwable e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -87,20 +86,20 @@ public class TransifexHandlers extends TelegramLongPollingBot {
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
if (sendDocument != null) { if (sendDocument != null) {
sendDocument.setChatId(message.getChatId()); sendDocument.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendDocument); execute(sendDocument);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} else if (parts[0].startsWith(Commands.help) || } else if (parts[0].startsWith(Commands.help) ||
@ -112,11 +111,11 @@ public class TransifexHandlers extends TelegramLongPollingBot {
Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP, Commands.transifexTDesktop, Commands.transifexOSX, Commands.transifexWP,
Commands.transifexAndroidSupportCommand); Commands.transifexAndroidSupportCommand);
sendMessageRequest.setText(helpFormated); sendMessageRequest.setText(helpFormated);
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
try { try {
execute(sendMessageRequest); execute(sendMessageRequest);
} catch (TelegramApiException e) { } catch (TelegramApiException e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }
@ -124,7 +123,7 @@ public class TransifexHandlers extends TelegramLongPollingBot {
private void sendMovedToMessage(Message message) throws InvalidObjectException, TelegramApiException { private void sendMovedToMessage(Message message) throws InvalidObjectException, TelegramApiException {
String language = DatabaseManager.getInstance().getUserLanguage(message.getFrom().getId()); String language = DatabaseManager.getInstance().getUserLanguage(message.getFrom().getId());
SendMessage answer = new SendMessage(); SendMessage answer = new SendMessage();
answer.setChatId(message.getChatId()); answer.setChatId(Long.toString(message.getChatId()));
answer.setReplyToMessageId(message.getMessageId()); answer.setReplyToMessageId(message.getMessageId());
answer.setText(LocalisationService.getString("movedToLangBot", language)); answer.setText(LocalisationService.getString("movedToLangBot", language));
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();

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

@ -1,5 +1,6 @@
package org.telegram.updateshandlers; package org.telegram.updateshandlers;
import lombok.extern.slf4j.Slf4j;
import org.telegram.BotConfig; import org.telegram.BotConfig;
import org.telegram.Commands; import org.telegram.Commands;
import org.telegram.database.DatabaseManager; import org.telegram.database.DatabaseManager;
@ -16,7 +17,6 @@ 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.logging.BotLogger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -28,9 +28,8 @@ import java.util.stream.Collectors;
* @brief Handler for updates to Weather Bot * @brief Handler for updates to Weather Bot
* @date 24 of June of 2015 * @date 24 of June of 2015
*/ */
@Slf4j
public class WeatherHandlers extends TelegramLongPollingBot { public class WeatherHandlers extends TelegramLongPollingBot {
private static final String LOGTAG = "WEATHERHANDLERS";
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;
@ -66,7 +65,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
} }
} }
} catch (Exception e) { } catch (Exception e) {
BotLogger.error(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
@ -98,7 +97,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
try { try {
Thread.currentThread().wait(35); Thread.currentThread().wait(35);
} catch (InterruptedException e) { } catch (InterruptedException e) {
BotLogger.severe(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId()); String[] userOptions = DatabaseManager.getInstance().getUserWeatherOptions(weatherAlert.getUserId());
@ -111,12 +110,12 @@ public class WeatherHandlers extends TelegramLongPollingBot {
try { try {
execute(sendMessage); execute(sendMessage);
} catch (TelegramApiRequestException e) { } catch (TelegramApiRequestException e) {
BotLogger.warn(LOGTAG, e); log.warn(e.getLocalizedMessage(), 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) {
BotLogger.severe(LOGTAG, e); log.error(e.getLocalizedMessage(), e);
} }
} }
} }
@ -244,7 +243,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertDeleted", language)); sendMessage.setText(LocalisationService.getString("alertDeleted", language));
@ -256,7 +255,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
@ -270,7 +269,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
if (message.getText().equals(getCancelCommand(language))) { if (message.getText().equals(getCancelCommand(language))) {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); 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)); sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
@ -293,7 +292,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessageRequest.setReplyMarkup(getAlertsKeyboard(language)); sendMessageRequest.setReplyMarkup(getAlertsKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language)); sendMessageRequest.setText(getChooseNewAlertSetMessage(message.getText(), language));
sendMessageRequest.setChatId(message.getChatId()); sendMessageRequest.setChatId(Long.toString(message.getChatId()));
DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT); DatabaseManager.getInstance().insertWeatherState(userId, message.getChatId(), ALERT);
return sendMessageRequest; return sendMessageRequest;
@ -329,7 +328,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -340,7 +339,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); 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.setText(getAlertListMessage(message.getFrom().getId(), language));
@ -353,7 +352,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(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) {
@ -373,7 +372,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
SendMessage sendMessage = new SendMessage(); SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId()); 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.setText(LocalisationService.getString("chooseNewAlertCity", language));
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
@ -410,7 +409,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getAlertsKeyboard(language)); sendMessage.setReplyMarkup(getAlertsKeyboard(language));
sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language)); sendMessage.setText(LocalisationService.getString("alertsMenuMessage", language));
@ -423,7 +422,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getUnitsKeyboard(language)); sendMessage.setReplyMarkup(getUnitsKeyboard(language));
sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language)); sendMessage.setText(getUnitsMessage(message.getFrom().getId(), language));
@ -436,7 +435,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setReplyMarkup(getLanguagesKeyboard(language)); sendMessage.setReplyMarkup(getLanguagesKeyboard(language));
sendMessage.setText(getLanguageMessage(language)); sendMessage.setText(getLanguageMessage(language));
@ -473,7 +472,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -531,7 +530,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -800,7 +799,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language); ReplyKeyboardMarkup replyKeyboardMarkup = getSettingsKeyboard(language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
sendMessage.setText(getSettingsMessage(language)); sendMessage.setText(getSettingsMessage(language));
DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS); DatabaseManager.getInstance().insertWeatherState(message.getFrom().getId(), message.getChatId(), SETTINGS);
@ -814,7 +813,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getString("onForecastCommandFromHistory", language)); sendMessage.setText(LocalisationService.getString("onForecastCommandFromHistory", language));
} else { } else {
@ -832,7 +831,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language); ReplyKeyboardMarkup replyKeyboardMarkup = getRecentsKeyboard(message.getFrom().getId(), language);
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
sendMessage.setReplyToMessageId(message.getMessageId()); sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setChatId(message.getChatId()); sendMessage.setChatId(Long.toString(message.getChatId()));
if (replyKeyboardMarkup.getKeyboard().size() > 3) { if (replyKeyboardMarkup.getKeyboard().size() > 3) {
sendMessage.setText(LocalisationService.getString("onCurrentCommandFromHistory", language)); sendMessage.setText(LocalisationService.getString("onCurrentCommandFromHistory", language));
} else { } else {
@ -1167,7 +1166,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
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();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
@ -1179,7 +1178,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
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();
sendMessage.enableMarkdown(true); sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId); sendMessage.setChatId(Long.toString(chatId));
sendMessage.setReplyToMessageId(messageId); sendMessage.setReplyToMessageId(messageId);
if (replyKeyboardMarkup != null) { if (replyKeyboardMarkup != null) {
sendMessage.setReplyMarkup(replyKeyboardMarkup); sendMessage.setReplyMarkup(replyKeyboardMarkup);
@ -1202,7 +1201,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(message.getChatId()); 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;
@ -1231,7 +1230,7 @@ public class WeatherHandlers extends TelegramLongPollingBot {
sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language)); sendMessageRequest.setReplyMarkup(getMainMenuKeyboard(language));
sendMessageRequest.setReplyToMessageId(message.getMessageId()); sendMessageRequest.setReplyToMessageId(message.getMessageId());
sendMessageRequest.setText(weather); sendMessageRequest.setText(weather);
sendMessageRequest.setChatId(message.getChatId()); 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;

2
src/main/resources/strings.properties

@ -83,4 +83,4 @@ noAlertList=I couldn't find any alert for you.
alertDeleted=The selected alert has been deleted. alertDeleted=The selected alert has been deleted.
cityNotFound= City not found cityNotFound= City not found
errorFetchingWeather= We're sorry, there was an error fetching the weather. errorFetchingWeather= We're sorry, there was an error fetching the weather.
rateMeMessage=If you like this bot, please rate it using [@storebot](https://telegram.me/storebot?start=weatherbot) rateMeMessage=If you like this bot, please rate it using [@findbot](https://telegram.me/findbot?start=weatherbot)

2
src/main/resources/strings_eo.properties

@ -72,4 +72,4 @@ noAlertList=Mi ne povas trovi ajnan averton por vi.
alertDeleted=La elektita averto estas forigita. alertDeleted=La elektita averto estas forigita.
cityNotFound= Urbo ne estas trovita cityNotFound= Urbo ne estas trovita
errorFetchingWeather= Mi beda\u016dras, eraro okazis dum ricevado de la vetero. errorFetchingWeather= Mi beda\u016dras, eraro okazis dum ricevado de la vetero.
rateMeMessage=Se vi \u015datas \u0109i tiun roboton, bonvolu klasifikadi \u011din \u0109e https\://telegram.me/storebot?start\=weatherbot rateMeMessage=Se vi \u015datas \u0109i tiun roboton, bonvolu klasifikadi \u011din \u0109e https\://telegram.me/findbot?start\=weatherbot

2
src/main/resources/strings_es.properties

@ -72,4 +72,4 @@ noAlertList=No pude encontrar ninguna alerta.
alertDeleted=La alerta seleccionada fue eliminada. alertDeleted=La alerta seleccionada fue eliminada.
cityNotFound= Ciudad no encontrada cityNotFound= Ciudad no encontrada
errorFetchingWeather= Lo sentimos, hubo un error solicitando el tiempo. errorFetchingWeather= Lo sentimos, hubo un error solicitando el tiempo.
rateMeMessage=Si te gusta este bot, por favor, puntúalo en https\://telegram.me/storebot?start\=weatherbot rateMeMessage=Si te gusta este bot, por favor, puntúalo en https\://telegram.me/findbot?start\=weatherbot

2
src/main/resources/strings_it.properties

@ -72,4 +72,4 @@ noAlertList=Non sono riuscito a trovare alcun allarme per te.
alertDeleted=L'allarme selezionato è stato eliminato. alertDeleted=L'allarme selezionato è stato eliminato.
cityNotFound= Città non trovata cityNotFound= Città non trovata
errorFetchingWeather= Siamo spiacenti, c'è stato un errore nel caricare le previsioni. errorFetchingWeather= Siamo spiacenti, c'è stato un errore nel caricare le previsioni.
rateMeMessage=Se ti piace questo bot, per favore votalo su https\://telegram.me/storebot?start\=weatherbot rateMeMessage=Se ti piace questo bot, per favore votalo su https\://telegram.me/findbot?start\=weatherbot

2
src/main/resources/strings_nl.properties

@ -72,4 +72,4 @@ noAlertList=Geen waarschuwingen gevonden.
alertDeleted=De geselecteerde waarschuwing is verwijderd. alertDeleted=De geselecteerde waarschuwing is verwijderd.
cityNotFound= Stad niet gevonden. cityNotFound= Stad niet gevonden.
errorFetchingWeather= Sorry, er is iets misgegaan bij het ophalen van het weer. errorFetchingWeather= Sorry, er is iets misgegaan bij het ophalen van het weer.
rateMeMessage=Als je deze bot leuk vindt dan kan je hem hier beoordelen https\://telegram.me/storebot?start\=weatherbot rateMeMessage=Als je deze bot leuk vindt dan kan je hem hier beoordelen https\://telegram.me/findbot?start\=weatherbot

2
src/main/resources/strings_pt.properties

@ -72,4 +72,4 @@ noAlertList=Eu não consegui encontrar nenhum alerta para você.
alertDeleted=O alerta selecionado foi apagado. alertDeleted=O alerta selecionado foi apagado.
cityNotFound= Cidade não encontrada cityNotFound= Cidade não encontrada
errorFetchingWeather= Desculpe, houve um erro ao obter o clima. errorFetchingWeather= Desculpe, houve um erro ao obter o clima.
rateMeMessage=Se você gosta deste bot, por favor nos avalie em https\://telegram.me/storebot?start\=weatherbot rateMeMessage=Se você gosta deste bot, por favor nos avalie em https\://telegram.me/findbot?start\=weatherbot

Loading…
Cancel
Save