Conversation
Transfers ConsoleBot code to Telegram
| @@ -1,10 +0,0 @@ | |||
| package Console; | |||
|
|
|||
| public class SimpleRequestHandler implements RequestHandler | |||
There was a problem hiding this comment.
Почему избавились от абстракции обработчика запроса пользователя? Сейчас почти вся логика обработки сообщения из метода бота onUpdateReceived должен быть перенесён в эту абстракцию. Если в будущем изменится API телеграма, то твой код при обновлении библиотеки просто перестанет работать
|
|
||
| public interface RequestHandler | ||
| { | ||
| Response handle(Request request); |
There was a problem hiding this comment.
Единственное, нужно будет поменять метод интерфейса сделать метод handler вот такой сигнатуры:
void handle(Request request, ResponseReplier replier);
| import org.telegram.telegrambots.meta.exceptions.TelegramApiException; | ||
| import org.telegram.telegrambots.updatesreceivers.DefaultBotSession; | ||
|
|
||
| public class Main |
There was a problem hiding this comment.
Main можно вынести в корневой пакет, так как он не является частью ядра, он стартует всё приложение
| @@ -0,0 +1,10 @@ | |||
| package userData; | |||
|
|
|||
| public interface IUser | |||
There was a problem hiding this comment.
Вообще, в Java нотации не принято именовать интерфейсы с I
| 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); |
There was a problem hiding this comment.
Может лучше тогда сразу посчитать через сколько миллисекунд нужно запустить таск и не будить его каждую секунду до нужной даты?)
| Memo reminder = new Memo(message.getText().substring(idx + 1), date); | ||
| remindManager.addMemoToUser(message.getChatId(), reminder); | ||
|
|
||
| Thread thread = new Thread(() -> { |
There was a problem hiding this comment.
Сейчас можно убить твоё приложение написав порядка нескольки тысяч запросов) Потому что у тебя на каждый запрос создаётся отдельный системный поток, в котором для каждого используется Timer, который под капотом создаёт новый поток. И всё это для того, чтобы каждую секунду проверять нужно ли пользователю ответить упоминанием)
Полагаю, что вместо всего этого можно просто прямо на уровне обработчика объявить поле с Timer и просто в нём создавать новый таск тогда, когда это действительно нужно
| @Override | ||
| public String getBotToken() | ||
| { | ||
| return System.getenv("BOT_TOKEN"); |
There was a problem hiding this comment.
Неплохо было бы это складывать в переменную в конструкторе, чтобы каждый раз не тянуть из окружения
| RequestReader reader = new BotRequestReader(); | ||
| ResponseReplier replier = new BotResponseReplier(); | ||
| RequestHandler requestHandler = new SimpleRequestHandler(); |
There was a problem hiding this comment.
Нет необходимости создать каждый раз новый объект, достаточно создать их единожды в конструкторе
| @@ -0,0 +1,16 @@ | |||
| package requests; | |||
|
|
|||
| public class Bucket | |||
There was a problem hiding this comment.
Почему не использовать ранее написанные Request и Response?
| import java.util.Timer; | ||
| import java.util.TimerTask; | ||
|
|
||
| public class SimpleRequestHandler implements RequestHandler |
There was a problem hiding this comment.
Это уже не очень Simple обработчик)
| import org.telegram.telegrambots.meta.api.objects.Update; | ||
| import org.telegram.telegrambots.meta.exceptions.TelegramApiException; | ||
|
|
||
| public class RemindBot extends TelegramLongPollingBot |
There was a problem hiding this comment.
Глобально необходим использовать такие интерфейсы:
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)
Transfers ConsoleBot code to Telegram