Skip to content

Commit

Permalink
Merge pull request #7 from XD-cods/refactor
Browse files Browse the repository at this point in the history
add github action and refactor any methods
  • Loading branch information
XD-cods authored Jul 10, 2024
2 parents 43f55ad + 44d8709 commit 4d3f3a1
Show file tree
Hide file tree
Showing 23 changed files with 219 additions and 404 deletions.
37 changes: 37 additions & 0 deletions .github/workflows/github-actions.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Build project

on:
push:
branches:
- "*"
pull_request:
branches:
- "*"

jobs:
Explore-GitHub-Actions:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Set up JDK 17 for x64
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'corretto'
architecture: 'x64'

- name: Build & Test
run: mvn -B clean package

- name: Install Docker Compose
run: sudo apt-get update && sudo apt-get install -y docker-compose

- name: Create & run Docker image
run: docker-compose up -d --build

- name: Clean up Docker resources
run: |
docker-compose down
docker system prune -af
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mBuild:
mvn clean -Dmaven.test.skip package -e
run:
java -jar target/knowBot-1.0-SNAPSHOT-jar-with-dependencies.jar
doc:
docker-compose up -d --build
5 changes: 1 addition & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ services:
bot:
build: .
environment:
- SPRING_DATA_MONGODB_URI=${SPRING_DATA_MONGODB_URI}
- TELEGRAM_USER_TOKEN=${TELEGRAM_USER_TOKEN}
- TELEGRAM_ADMIN_TOKEN=${TELEGRAM_ADMIN_TOKEN}
- SPRING_DATA_MONGODB_DATABASE=${SPRING_DATA_MONGODB_DATABASE}
- REDIS_PORT=${REDIS_PORT}
- REDIS_HOSTNAME=${REDIS_HOSTNAME}
- SPRING_DATA_MONGODB_URI=${SPRING_DATA_MONGODB_URI}

grafana:
image: "grafana/grafana-enterprise:10.4.2"
Expand Down
33 changes: 6 additions & 27 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,10 @@
<mongodb-driver-sync.version>4.11.1</mongodb-driver-sync.version>
<jackson-databind.version>2.16.1</jackson-databind.version>
<log4j-core.version>2.17.2</log4j-core.version>
<junit-jupiter-api.version>5.10.2</junit-jupiter-api.version>
<cache2k-base-bom.version>1.6.0.Final</cache2k-base-bom.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
Expand All @@ -51,15 +43,15 @@
<version>${jackson-databind.version}</version>
</dependency>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>2.2.0</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter-api.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.cache2k</groupId>
<artifactId>cache2k-base-bom</artifactId>
<version>1.6.0.Final</version>
<version>${cache2k-base-bom.version}</version>
<type>pom</type>
</dependency>
<dependency>
Expand All @@ -70,19 +62,6 @@
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>org.example.Main</mainClass>
</manifest>
</archive>

</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.7.1</version>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/org/example/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import com.pengrad.telegrambot.TelegramBot;
import org.example.configs.MongoDBConfig;
import org.example.services.QuizService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@PropertySource("classpath:application.properties")
public class Main {
Expand Down
167 changes: 71 additions & 96 deletions src/main/java/org/example/QuizBotListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class QuizBotListener implements UpdatesListener {
Expand All @@ -41,10 +38,14 @@ public class QuizBotListener implements UpdatesListener {
public QuizBotListener(TelegramBot bot, QuizService quizService) {
this.bot = bot;
this.quizService = quizService;
this.sessionCache = Cache2kBuilder.of(Long.class, QuizBotSession.class).expireAfterWrite(120, TimeUnit.SECONDS).addListener((CacheEntryExpiredListener<Long, QuizBotSession>) (cache, entry) -> {
clearLastMessageKeyboard(cache.get(entry.getKey()), entry.getKey());
sendMessage(entry.getKey(), "You've been thinking too long, so you'll have to start over." + " Write /start or /choice.");
}).addListener((CacheEntryCreatedListener<Long, QuizBotSession>) (cache, entry) -> sendMessage(entry.getKey(), UserBotConstants.STARTING_MESSAGE)).build();
this.sessionCache = Cache2kBuilder.of(Long.class, QuizBotSession.class)
.expireAfterWrite(120, TimeUnit.SECONDS)
.addListener((CacheEntryExpiredListener<Long, QuizBotSession>) (cache, entry) -> {
clearLastMessageKeyboard(cache.get(entry.getKey()), entry.getKey());
sendMessage(entry.getKey(), "You've been thinking too long, so you'll have " +
"to start over." + " Write /start or /choice.");
})
.build();
}

@Override
Expand All @@ -60,73 +61,84 @@ public int process(List<Update> updates) throws NullPointerException {
Message message = update.message();
Long userId = message.chat().id();
String messageText = message.text();
QuizBotSession quizBotSession = sessionCache.computeIfAbsent(userId, () -> new QuizBotSession(QuizBotSessionMode.SESSION_CREATED));
//todo start here
QuizBotSession quizBotSession = sessionCache.computeIfAbsent(userId,
() -> new QuizBotSession(QuizBotSessionMode.SESSION_CREATED));
switch (quizBotSession.getBotSessionMode()) {
case TOPIC_CHOICE -> {
if (messageText.equals(UserBotConstants.CANCEL_COMMAND)) {
quizBotSession.setBotSessionMode(QuizBotSessionMode.SESSION_CREATED);
sendMessage(userId, UserBotConstants.STARTING_MESSAGE);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
choiceTopic(messageText, quizBotSession, userId);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
case QUIZ -> {
if (messageText.equals(UserBotConstants.CANCEL_COMMAND)) {
clearLastMessageKeyboard(quizBotSession, userId);
sendStatsCanceledQuiz(userId, quizBotSession);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
sendMessage(userId, "Please finish this quiz");
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}

case QUESTION_COUNT_CHOICE -> {
if (messageText.equals(UserBotConstants.CANCEL_COMMAND)) {
quizBotSession.setBotSessionMode(QuizBotSessionMode.SESSION_CREATED);
sendMessage(userId, UserBotConstants.STARTING_MESSAGE);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
setCountOfQuiz(messageText, userId, quizBotSession);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
}

switch (messageText) {
case UserBotConstants.START_BOT_COMMAND -> {
clearLastMessageKeyboard(quizBotSession, userId);
sendMessage(userId, UserBotConstants.STARTING_MESSAGE);
sessionCache.remove(userId);
sessionCache.put(userId, new QuizBotSession(QuizBotSessionMode.SESSION_CREATED));
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
case UserBotConstants.CHOOSE_TOPIC_COMMAND -> {
UserQuizSession userQuizSession = quizBotSession.getUserQuizSession();
if (userQuizSession != null) {
sendMessage(userId, "Please finish this quiz");
break;
}
sendTopics(userId, quizBotSession);
}
case UserBotConstants.CHOOSE_TOPIC_COMMAND -> sendTopics(userId, quizBotSession);
case UserBotConstants.START_QUIZ_COMMAND -> {
UserQuizSession userQuizSession = quizBotSession.getUserQuizSession();
if (userQuizSession != null) {
sendMessage(userId, "Please finish this quiz");
break;
}
String currentTopicName = quizBotSession.getCurrentTopicName();
if (currentTopicName == null) {
sendMessage(userId, "Topic is not chosen, please use " + UserBotConstants.CHOOSE_TOPIC_COMMAND + " command to choose");
break;
}
if (quizBotSession.getBotSessionMode().equals(QuizBotSessionMode.QUESTION_COUNT_CHOICE)) {
sendMessage(userId, "You are not chosen quiz");
break;
if (currentTopicName.isEmpty()) {
sendMessage(userId, "Pleas choice topic " + UserBotConstants.CHOOSE_TOPIC_COMMAND);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}

userQuizSession = new UserQuizSession(getGeneratedQuiz(currentTopicName, quizBotSession));
int countOfQuestion = quizBotSession.getCountOfQuestion();
QuizQuestions quizQuestions = quizService.findRandomQuestionsByTopicName(currentTopicName, countOfQuestion);
UserQuizSession userQuizSession = new UserQuizSession(quizQuestions);
sendMessage(userId, "Quiz: " + currentTopicName);
quizBotSession.setUserQuizSession(userQuizSession);
sendMessage(userId, "Quiz: " + quizBotSession.getCurrentTopicName());
quizBotSession.setBotSessionMode(QuizBotSessionMode.QUIZ);
sendQuestion(userId, quizBotSession);
quizBotSession.setBotSessionMode(QuizBotSessionMode.QUIZ);
}
case UserBotConstants.CANCEL_COMMAND -> {
UserQuizSession userQuizSession = quizBotSession.getUserQuizSession();
if (userQuizSession == null) {
sendMessage(userId, "You aren't begin quiz");
break;
}
clearLastMessageKeyboard(quizBotSession, userId);
sendStatsCanceledQuiz(userId, quizBotSession);
}
}

if (messageText.matches("^[1-9][0-9]*$")) {
if (quizBotSession.getBotSessionMode().equals(QuizBotSessionMode.QUESTION_COUNT_CHOICE)) {
setCountOfQuiz(messageText, userId, quizBotSession);
}
if (quizBotSession.getBotSessionMode().equals(QuizBotSessionMode.TOPIC_CHOICE)) {
choiceTopic(messageText, quizBotSession, userId);
}
case UserBotConstants.CANCEL_COMMAND -> sendMessage(userId, "Nothing canceled");
default -> sendMessage(userId, "Input a valid command");
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
} catch (Exception e) {
log.error(e.getMessage());
}

return UpdatesListener.CONFIRMED_UPDATES_ALL;
}

private static String getQuizStatText(int quizAmount, int rightAnswerCounter) {
return String.format("❓ <b>Question number:</b> %d" + "\n\n" + "✅ <b>Right answers:</b> %d\\%d" + "\n\n" + "Input " + UserBotConstants.START_QUIZ_COMMAND + " to start quiz or chose quiz another quiz " + UserBotConstants.CHOOSE_TOPIC_COMMAND, quizAmount, rightAnswerCounter, quizAmount);
}

private static String getCanceledQuizStatText(int questionCount, int rightAnswerCounter) {
return String.format("❓<b>You canceled quiz</b>\n" + "\n" + "<b>The questions were:</b> %d\n\n" + "✅ <b>Right answers:</b> %d\\%d\n" + "\n" + "Input " + UserBotConstants.START_QUIZ_COMMAND + " to start quiz or chose quiz another quiz " + UserBotConstants.CHOOSE_TOPIC_COMMAND, questionCount, rightAnswerCounter, questionCount);
}

private void setCountOfQuiz(String messageText, Long userId, QuizBotSession quizBotSession) {
if (!messageText.matches("^[1-9][0-9]*$")) {
sendMessage(userId, "Input a number or input " + UserBotConstants.CANCEL_COMMAND + " for cancel count of question choice");
return;
}
int countOfQuestions = Integer.parseInt(messageText);
if (countOfQuestions > 20 || countOfQuestions < 5) {
sendMessage(userId, "Input valid count of question");
Expand All @@ -136,33 +148,6 @@ private void setCountOfQuiz(String messageText, Long userId, QuizBotSession quiz
quizBotSession.setBotSessionMode(QuizBotSessionMode.SESSION_CREATED);
}

private QuizQuestions getGeneratedQuiz(String currentTopicName, QuizBotSession quizBotSession) {
QuizQuestions quizQuestions = quizService.findByTopicName(currentTopicName);
List<Question> questionList = quizQuestions.getQuestionList();
int countOfQuestion = quizBotSession.getCountOfQuestion();
if (questionList.size() <= countOfQuestion) {
return quizQuestions;
}
QuizQuestions generatedQuizQuestions = new QuizQuestions();
List<Question> generatedQuestionList = new ArrayList<>();
Set<Integer> uniqueNumbers = getUniqueNums(questionList.size() - 1, countOfQuestion);
for (Integer i : uniqueNumbers) {
generatedQuestionList.add(questionList.get(i));
}
generatedQuizQuestions.setQuestionList(generatedQuestionList);
generatedQuizQuestions.setTopicName(quizQuestions.getTopicName());
return generatedQuizQuestions;
}

private Set<Integer> getUniqueNums(int max, int count) {
Set<Integer> uniqueNums = new HashSet<>();
Random random = new Random();
while (count > uniqueNums.size()) {
uniqueNums.add(random.nextInt(max));
}
return uniqueNums;
}

private void sendMessage(Long userId, String s) {
bot.execute(new SendMessage(userId, s));
}
Expand Down Expand Up @@ -289,26 +274,24 @@ private InlineKeyboardMarkup buildInlineKeyboard(int keyboardLength) {
}

private void choiceTopic(String messageText, QuizBotSession quizBotSession, Long userId) {
if (!messageText.matches("^[1-9][0-9]*$")) {
sendMessage(userId, "Input a number or input " + UserBotConstants.CANCEL_COMMAND + " for cancel topic choice");
return;
}
int topicIndex = Integer.parseInt(messageText) - 1;
List<String> allTopicName = quizService.getTopics();
if (allTopicName.isEmpty()) {

quizBotSession.setBotSessionMode(QuizBotSessionMode.SESSION_CREATED);
sendMessage(userId, "Sorry nothing quiz, send " + UserBotConstants.CHOOSE_TOPIC_COMMAND + " for choice quiz");
return;
}
if (topicIndex >= allTopicName.size()) {
sendMessage(userId, "You input over large digital, send me correct digital");
sendTopics(userId, quizBotSession);
return;
} else if (topicIndex < 0) {
sendMessage(userId, "You input so small digital, send me correct digital");
if (topicIndex >= allTopicName.size() || topicIndex < 0) {
sendMessage(userId, "Send me correct digital from 1 to " + allTopicName.size());
sendTopics(userId, quizBotSession);
return;
}
String currentTopicName = allTopicName.get(topicIndex);
quizBotSession.setCurrentTopicName(currentTopicName);
quizBotSession.setCurrentQuiz(quizService.findByTopicName(currentTopicName));
quizBotSession.setBotSessionMode(QuizBotSessionMode.QUESTION_COUNT_CHOICE);
sendMessage(userId, "Input count to your quiz (at 5 to 20)");
}
Expand All @@ -322,14 +305,6 @@ private void clearLastMessageKeyboard(QuizBotSession quizBotSession, Long userId
bot.execute(editMessage);
}

private static String getQuizStatText(int quizAmount, int rightAnswerCounter) {
return String.format("❓ <b>Question number:</b> %d" + "\n\n" + "✅ <b>Right answers:</b> %d\\%d" + "\n\n" + "Input " + UserBotConstants.START_QUIZ_COMMAND + " to start quiz or chose quiz another quiz " + UserBotConstants.CHOOSE_TOPIC_COMMAND, quizAmount, rightAnswerCounter, quizAmount);
}

private static String getCanceledQuizStatText(int questionCount, int rightAnswerCounter) {
return String.format("❓<b>You canceled quiz</b>\n" + "\n" + "<b>The questions were:</b> %d\n\n" + "✅ <b>Right answers:</b> %d\\%d\n" + "\n" + "Input " + UserBotConstants.START_QUIZ_COMMAND + " to start quiz or chose quiz another quiz " + UserBotConstants.CHOOSE_TOPIC_COMMAND, questionCount, rightAnswerCounter, questionCount);
}

private String getAnswerText(UserQuizSession userQuizSession, int userAnswerNum) {
Question question = userQuizSession.getCurrentQuestion();
List<QuestionOption> optionsList = question.getOptionList();
Expand Down
Loading

0 comments on commit 4d3f3a1

Please sign in to comment.