Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added sendler message for subscribed users. Added saving and getting … #50

Merged
merged 2 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 53 additions & 13 deletions src/main/java/org/oopproject/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class Database {
Expand Down Expand Up @@ -34,6 +36,33 @@ public void insertChatId(long chatId) {
}
}

public void updateUserAge(long chatId, int userAge) {
String updateAgeQuery = "UPDATE users SET userAge = ? WHERE chatId = ?";

try (PreparedStatement updateStatement = connection.prepareStatement(updateAgeQuery)) {
updateStatement.setInt(1, userAge);
updateStatement.setLong(2, chatId);
updateStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Integer getUserAge(long chatId) {
String selectUserAgeQuery = "SELECT userAge FROM users WHERE chatId = ?";
try (PreparedStatement selectStatement = connection.prepareStatement(selectUserAgeQuery)) {
selectStatement.setLong(1, chatId);
ResultSet resultSet = selectStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("userAge");
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;

}


public void updateGenreIndexesJson(long chatId, String genreIndexesJson) {
String updateQuery = "UPDATE users SET genreIndexesJson = ? WHERE chatId = ?";
try (PreparedStatement updateStatement = connection.prepareStatement(updateQuery)) {
Expand Down Expand Up @@ -83,18 +112,29 @@ public String getYearIndexesJson(long chatId) {
}
return null;
}
public void updateSubscribe(long chatId, boolean subscribed) {
String query = "UPDATE users SET subscribed = ? WHERE chatId = ?";
try (PreparedStatement updateStatement = connection.prepareStatement(query)) {
updateStatement.setBoolean(1, subscribed);
updateStatement.setLong(2, chatId);
updateStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}














public List<Long> getSubscribedUsers() {
String selectQuery = "SELECT chatId FROM users WHERE subscribed = TRUE";
List<Long> users = new ArrayList<>();
try (PreparedStatement selectStatement = connection.prepareStatement(selectQuery)) {
ResultSet resultSet = selectStatement.executeQuery();
while (resultSet.next()) {
users.add(resultSet.getLong("chatId"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
}

137 changes: 111 additions & 26 deletions src/main/java/org/oopproject/TelegramBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.*;

import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.generics.TelegramClient;
import org.telegram.telegrambots.meta.api.objects.Update;
Expand All @@ -34,6 +33,7 @@
public class TelegramBot implements LongPollingSingleThreadUpdateConsumer {
private final TelegramClient telegramClient;
private final ExecutorService executorService = Executors.newFixedThreadPool(4);
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final Database database=new Database();
private final Gson gson = new Gson();

Expand All @@ -45,6 +45,7 @@ public class TelegramBot implements LongPollingSingleThreadUpdateConsumer {

public TelegramBot(String botToken) throws SQLException {
telegramClient = new OkHttpTelegramClient(botToken);
startBroadcasting();
}

@Override
Expand All @@ -61,28 +62,32 @@ public void handleUpdate(Update update) {

String messageText = update.getMessage().getText();
String responseMessage;
CommandWaiter waiter = commandWaiter.getOrDefault(userID, NONE);
CommandWaiter waiter = commandWaiter.getOrDefault(chatId, NONE);

switch (waiter) {
case YEAR:
responseMessage = handleYear(messageText, userID);
commandWaiter.put(userID, NONE);
responseMessage = handleYear(messageText, chatId);
commandWaiter.put(chatId, NONE);
break;
case GENRE:
responseMessage = handleGenre(messageText, userID);
commandWaiter.put(userID, NONE);
responseMessage = handleGenre(messageText, chatId);
commandWaiter.put(chatId, NONE);
break;
case SETAGE:
responseMessage = handleAge(messageText, userID);
commandWaiter.put(userID, NONE);
responseMessage = handleAge(messageText, chatId);
commandWaiter.put(chatId, NONE);
break;
case SUBSCRIBE:
responseMessage = handleSubscription(messageText, chatId);
commandWaiter.put(chatId, NONE);
break;
default:
responseMessage = handleCommands(messageText, userID);
responseMessage = handleCommands(messageText, chatId);
break;
}

SendMessage message = SendMessage.builder()
.chatId(userID)
.chatId(chatId)
.text(responseMessage)
.replyMarkup(createCommandKeyboard())
.build();
Expand Down Expand Up @@ -112,7 +117,7 @@ private void loadYearIndexFromDatabase(long chatId) {



protected String handleCommands(String messageText, long userID) {
protected String handleCommands(String messageText, long chatId) {
String responseMessage;

switch (messageText) {
Expand All @@ -121,15 +126,19 @@ protected String handleCommands(String messageText, long userID) {
break;
case "/genre": case "Genre":
responseMessage = getReply("genre");
commandWaiter.put(userID, GENRE);
commandWaiter.put(chatId, GENRE);
break;
case "/year": case "Year":
responseMessage = getReply("year");
commandWaiter.put(userID, YEAR);
commandWaiter.put(chatId, YEAR);
break;
case "/setage": case "Set Age":
responseMessage = getReply("set age");
commandWaiter.put(userID, SETAGE);
commandWaiter.put(chatId, SETAGE);
break;
case "/subscribe": case "Subscribe":
responseMessage = getReply("subscribe");
commandWaiter.put(chatId, SUBSCRIBE);
break;
case "/help": case "Help":
responseMessage = getReply("help");
Expand All @@ -153,8 +162,12 @@ private ReplyKeyboardMarkup createCommandKeyboard() {
row2.add("Set Age");
row2.add("Help");

KeyboardRow row3 = new KeyboardRow();
row3.add("Subscribe");

keyboard.add(row1);
keyboard.add(row2);
keyboard.add(row3);

keyboardMarkup.setKeyboard(keyboard);
keyboardMarkup.setResizeKeyboard(true);
Expand All @@ -170,8 +183,8 @@ private void updateGenreIndexInDatabase(long chatId) {

protected String handleGenre(String messageText, long chatId) {
if (isCommand(messageText)) {
commandWaiter.put(userID, NONE);
return handleCommands(messageText, userID);
commandWaiter.put(chatId, NONE);
return handleCommands(messageText, chatId);
}

String responseMessage;
Expand Down Expand Up @@ -207,7 +220,7 @@ protected String handleGenre(String messageText, long chatId) {
} else {
responseMessage = "Извините, я не нашел фильмов для жанра " + messageText;
}
commandWaiter.put(userID, NONE);
commandWaiter.put(chatId, NONE);
} catch (IllegalArgumentException e) {
responseMessage = "Извините, я не знаю такого жанра. Попробуйте другой";
}
Expand All @@ -223,8 +236,8 @@ private void updateYearIndexInDatabase(long chatId) {
protected String handleYear(String messageText, long chatId) {

if (isCommand(messageText)) {
commandWaiter.put(userID, NONE);
return handleCommands(messageText, userID);
commandWaiter.put(chatId, NONE);
return handleCommands(messageText, chatId);
}

String responseMessage;
Expand Down Expand Up @@ -265,18 +278,26 @@ protected String handleYear(String messageText, long chatId) {
} else {
responseMessage = "Извините, я не нашел фильмов за " + userYear + " год";
}
commandWaiter.put(userID, NONE);
commandWaiter.put(chatId, NONE);
} catch (NumberFormatException e) {
responseMessage = "Пожалуйста, введите корректный год!";
}

return responseMessage;
}

protected String handleAge(String messageText, long userID) {
protected void handleSubscribe(long chatId) {
database.updateSubscribe(chatId, true);
}
protected void handleUnsubscribe(long chatId) {
database.updateSubscribe(chatId, false);
}


protected String handleAge(String messageText, long chatId) {
if (isCommand(messageText)) {
commandWaiter.put(userID, NONE);
return handleCommands(messageText, userID);
commandWaiter.put(chatId, NONE);
return handleCommands(messageText, chatId);
}

String responseMessage;
Expand All @@ -286,14 +307,78 @@ protected String handleAge(String messageText, long userID) {

if (userAge >= 0 && userAge <= 100) {
responseMessage = "Спасибо! Учтем ваш ответ";
commandWaiter.put(userID, NONE);
commandWaiter.put(chatId, NONE);
database.updateUserAge(chatId, userAge);

} else {
responseMessage = "Пожалуйста, введите корректное число (от 0 до 100)";
}
} catch (NumberFormatException e) {
responseMessage = "Пожалуйста, введите число";
}
// handleGetAge(chatId);
return responseMessage;
}

public void startBroadcasting() {
scheduler.scheduleAtFixedRate(()-> {
List<Long> subscribedUsers = database.getSubscribedUsers();
for (Long chatId : subscribedUsers) {
sendMessage(chatId, "Подписчику");
}
},0,1, TimeUnit.MINUTES);
}
private void sendMessage(long chatId, String text) {
SendMessage message=SendMessage.builder()
.chatId(chatId)
.text(text)
.build();
try {
telegramClient.execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public String handleSubscription(String messageText, long chatId) {
if (isCommand(messageText)) {
commandWaiter.put(chatId, NONE);
return handleCommands(messageText, chatId);
}

String responseMessage;

try {
int userInput = Integer.parseInt(messageText);

if (userInput == 1) {
handleSubscribe(chatId);
responseMessage = "Вы успешно подписались на рассылку!";
} else if (userInput == 0) {
handleUnsubscribe(chatId);
responseMessage = "Вы успешно отписались от рассылки.";
} else {
responseMessage = "Пожалуйста, введите 1 для подписки или 0 для отписки.";
}
} catch (NumberFormatException e) {
responseMessage = "Пожалуйста, введите число (1 для подписки, 0 для отписки).";
}

return responseMessage;
}

// protected void broadcastMessage(String message) {
// List<Long> users = database.getSubscribedUsers();
// for (Long chatId : users) {
// new SendMessage(chatId, message);
// }
// }
// protected void handleGetAge( long chatId) {
// Integer userAge = database.getUserAge(chatId);
// if (userAge != null) {
// System.out.println("возраст "+ userAge);
// }
// else {
// System.out.println("не нашли возраст");
// }
// }
}
3 changes: 2 additions & 1 deletion src/main/java/org/oopproject/utils/CommandWaiter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ public enum CommandWaiter {
NONE,
GENRE,
YEAR,
SETAGE;
SETAGE,
SUBSCRIBE;
}
1 change: 1 addition & 0 deletions src/main/java/org/oopproject/utils/Replies.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class Replies {
/setage - Установить возрастное ограничение""");
replies.put("year", "Введите год, и я найду фильмы, выпущенные в этом году");
replies.put("set age", "Введите ваш полный возраст");
replies.put("subscribe", "Введите 1, чтобы подписаться на рассылку, или 0, чтобы отписаться");
replies.put("unknown", "Команда не распознана. Попробуйте /help для получения списка команд");
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/oopproject/utils/Validators.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ public class Validators {
"/genre", "Genre",
"/year", "Year",
"/help", "Help",
"/setage", "Set Age"
"/setage", "Set Age",
"/subscribe", "Subscribe"
);

public static boolean isCommand(String text) {
Expand Down