Skip to content

ConsoleBot -> TelegramBot#3

Open
VolodyaDe wants to merge 7 commits intomainfrom
vova_branch
Open

ConsoleBot -> TelegramBot#3
VolodyaDe wants to merge 7 commits intomainfrom
vova_branch

Conversation

@VolodyaDe
Copy link
Copy Markdown
Owner

Transfers ConsoleBot code to Telegram

Transfers ConsoleBot code to Telegram
@VolodyaDe VolodyaDe closed this Sep 19, 2023
@VolodyaDe VolodyaDe reopened this Sep 19, 2023
@@ -1,10 +0,0 @@
package Console;

public class SimpleRequestHandler implements RequestHandler
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему избавились от абстракции обработчика запроса пользователя? Сейчас почти вся логика обработки сообщения из метода бота onUpdateReceived должен быть перенесён в эту абстракцию. Если в будущем изменится API телеграма, то твой код при обновлении библиотеки просто перестанет работать


public interface RequestHandler
{
Response handle(Request request);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Единственное, нужно будет поменять метод интерфейса сделать метод handler вот такой сигнатуры:
void handle(Request request, ResponseReplier replier);

Comment thread core/Main.java
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

public class Main
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main можно вынести в корневой пакет, так как он не является частью ядра, он стартует всё приложение

Comment thread userData/IUser.java Outdated
@@ -0,0 +1,10 @@
package userData;

public interface IUser
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще, в Java нотации не принято именовать интерфейсы с I

Comment thread core/RemindBot.java Outdated
Comment on lines +58 to +75
Thread thread = new Thread(() -> {
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
private boolean m_bIsRunning = true;

@Override
public void run()
{
if (reminder.dateCompare(new Date()) && m_bIsRunning)
{
response.setText(reminder.getMemoText());
executeResponse(response);
remindManager.removeMemoFromUser(message.getChatId(), reminder);
m_bIsRunning = false;
}
}
}, 0, 1000);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может лучше тогда сразу посчитать через сколько миллисекунд нужно запустить таск и не будить его каждую секунду до нужной даты?)

Comment thread core/RemindBot.java Outdated
Memo reminder = new Memo(message.getText().substring(idx + 1), date);
remindManager.addMemoToUser(message.getChatId(), reminder);

Thread thread = new Thread(() -> {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сейчас можно убить твоё приложение написав порядка нескольки тысяч запросов) Потому что у тебя на каждый запрос создаётся отдельный системный поток, в котором для каждого используется Timer, который под капотом создаёт новый поток. И всё это для того, чтобы каждую секунду проверять нужно ли пользователю ответить упоминанием)
Полагаю, что вместо всего этого можно просто прямо на уровне обработчика объявить поле с Timer и просто в нём создавать новый таск тогда, когда это действительно нужно

Comment thread core/RemindBot.java Outdated
@Override
public String getBotToken()
{
return System.getenv("BOT_TOKEN");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Неплохо было бы это складывать в переменную в конструкторе, чтобы каждый раз не тянуть из окружения

Comment thread core/RemindBot.java Outdated
Comment on lines +15 to +17
RequestReader reader = new BotRequestReader();
ResponseReplier replier = new BotResponseReplier();
RequestHandler requestHandler = new SimpleRequestHandler();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет необходимости создать каждый раз новый объект, достаточно создать их единожды в конструкторе

Comment thread requests/Bucket.java Outdated
@@ -0,0 +1,16 @@
package requests;

public class Bucket
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему не использовать ранее написанные Request и Response?

Comment thread requests/SimpleRequestHandler.java Outdated
import java.util.Timer;
import java.util.TimerTask;

public class SimpleRequestHandler implements RequestHandler
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это уже не очень Simple обработчик)

Comment thread core/RemindBot.java
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

public class RemindBot extends TelegramLongPollingBot
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Глобально необходим использовать такие интерфейсы:

public interface RequestHandler
{
    void handle(Request request, ResponseReplier replier);
}

public interface ResponseReplier
{
    void reply(Response request);
}

public class Request
{
    private final String message;
    private final long userId;

    public Request(String message, long userId) {
        this.message = message;
        this.userId = userId;
    }

    public String getMesssage() {
        return message;
    }

    public long getUserId() {
        return userId;
    }
}

public class Response
{
    private final String message;
    private final long userId;

    public Response(String message, long userId) {
        this.message = message;
        this.userId = userId;
    }

    public String getMesssage() {
        return message;
    }

    public long getUserId() {
        return userId;
    }
}

Теперь в этом классе должен появиться метод с сигнатурой:
private Request prepareRequest(Update update)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants