Refactor. Ability to run once

This commit is contained in:
Victor 2020-09-28 23:02:30 +03:00
parent 55743fbdda
commit 16e5f38a26
2 changed files with 42 additions and 26 deletions

View File

@ -9,6 +9,7 @@ import com.pengrad.telegrambot.model.PhotoSize;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.GetFile;
import com.pengrad.telegrambot.request.GetUpdates;
import com.pengrad.telegrambot.request.SendMessage;
import java.awt.image.BufferedImage;
import java.io.IOException;
@ -41,12 +42,17 @@ public class BotHandler {
public void run() {
bot.setUpdatesListener(updates -> {
final List<Message> channelPosts = updates.stream()
.map(Update::channelPost)
.filter(Objects::nonNull)
.filter(msg -> msg.photo() != null)
.collect(Collectors.toList());
processUpdates(updates);
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
}
public void runOnce() {
processUpdates(bot.execute(new GetUpdates()).updates());
}
private void processUpdates(List<Update> updates) {
final List<Message> channelPosts = getChannelPostsWithPhotos(updates);
final var similarImagesInfos = new ArrayList<SimilarImagesInfo>();
for (var post : channelPosts) {
final PhotoSize photo = getSmallestPhoto(post.photo());
@ -66,8 +72,14 @@ public class BotHandler {
if (!similarImagesInfos.isEmpty()) {
sendReport(similarImagesInfos);
}
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
}
private List<Message> getChannelPostsWithPhotos(List<Update> updates) {
return updates.stream()
.map(Update::channelPost)
.filter(Objects::nonNull)
.filter(msg -> msg.photo() != null)
.collect(Collectors.toList());
}
private void sendReport(List<SimilarImagesInfo> infos) {

View File

@ -10,8 +10,12 @@ public class Main {
final ImageIndexer indexer = new ImageIndexer();
final var handler = new BotHandler(botToken, indexer);
handler.setAdminId(longProp("ADMIN_ID").orElse(0L));
if (args.length == 1 && args[0].equalsIgnoreCase("once")) {
handler.runOnce();
} else {
handler.run();
}
}
private static Optional<String> stringProp(String name) {
return Optional.ofNullable(System.getenv(name))