Browse Source

Api Version 7.2.0

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

127
pom.xml

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save