Переработка получения событий от телеграма для поддержки микросервисной архитектуры
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Struchkov Mark 2023-03-26 17:42:44 +03:00
parent b657d588bb
commit 40fd76590f
Signed by: upagge
GPG Key ID: D3018BE7BA428CA6
25 changed files with 215 additions and 332 deletions

12
pom.xml
View File

@ -38,7 +38,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<godfather.core.ver>0.0.54</godfather.core.ver> <godfather.core.ver>0.0.55-SNAPSHOT</godfather.core.ver>
<!-- https://mvnrepository.com/artifact/org.telegram/telegrambots --> <!-- https://mvnrepository.com/artifact/org.telegram/telegrambots -->
<telegrambots.ver>6.3.0</telegrambots.ver> <telegrambots.ver>6.3.0</telegrambots.ver>
@ -46,7 +46,7 @@
<!-- https://mvnrepository.com/artifact/io.smallrye.reactive/smallrye-mutiny-vertx-core --> <!-- https://mvnrepository.com/artifact/io.smallrye.reactive/smallrye-mutiny-vertx-core -->
<smallrye.mutiny.vertx.core.version>2.30.1</smallrye.mutiny.vertx.core.version> <smallrye.mutiny.vertx.core.version>2.30.1</smallrye.mutiny.vertx.core.version>
<haiti.version>2.6.0</haiti.version> <haiti.version>2.7.2</haiti.version>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin.maven.compiler.ver>3.10.1</plugin.maven.compiler.ver> <plugin.maven.compiler.ver>3.10.1</plugin.maven.compiler.ver>
@ -267,6 +267,14 @@
<artifactId>smallrye-mutiny-vertx-core</artifactId> <artifactId>smallrye-mutiny-vertx-core</artifactId>
<version>${smallrye.mutiny.vertx.core.version}</version> <version>${smallrye.mutiny.vertx.core.version}</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>

View File

@ -84,7 +84,7 @@ public final class MessageChatMailConvert {
return picture; return picture;
}).toList(); }).toList();
attachment.setPictureSizes(pictures); attachment.setPictures(pictures);
return Optional.of(attachment); return Optional.of(attachment);
} }

View File

@ -83,7 +83,7 @@ public final class MessageMailConvert {
return picture; return picture;
}).toList(); }).toList();
attachment.setPictureSizes(pictures); attachment.setPictures(pictures);
return Optional.of(attachment); return Optional.of(attachment);
} }

View File

@ -1,7 +1,8 @@
package dev.struchkov.godfather.telegram.quarkus.consumer; package dev.struchkov.godfather.telegram.quarkus.consumer;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.main.domain.content.Mail; import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.quarkus.context.service.EventHandler; import dev.struchkov.godfather.quarkus.context.service.EventDispatching;
import dev.struchkov.godfather.telegram.domain.event.Subscribe; import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe; import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert; import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert;
@ -10,7 +11,6 @@ import dev.struchkov.godfather.telegram.main.consumer.SubscribeConvert;
import dev.struchkov.godfather.telegram.main.consumer.UnsubscribeConvert; import dev.struchkov.godfather.telegram.main.consumer.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor; import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect; import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.Uni;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
@ -22,11 +22,6 @@ import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery; import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/** /**
* TODO: Добавить описание класса. * TODO: Добавить описание класса.
@ -35,10 +30,10 @@ import static dev.struchkov.haiti.utils.Checker.checkNotNull;
*/ */
public class EventDistributorService implements EventDistributor { public class EventDistributorService implements EventDistributor {
private final Map<String, List<EventHandler>> eventHandlerMap; private final EventDispatching eventDispatching;
public EventDistributorService(TelegramConnect telegramConnect, List<EventHandler> eventProviders) { public EventDistributorService(TelegramConnect telegramConnect, EventDispatching eventDispatching) {
this.eventHandlerMap = eventProviders.stream().collect(Collectors.groupingBy(EventHandler::getEventType)); this.eventDispatching = eventDispatching;
telegramConnect.initEventDistributor(this); telegramConnect.initEventDistributor(this);
} }
@ -54,77 +49,33 @@ public class EventDistributorService implements EventDistributor {
// запросы к боту из чатов: https://core.telegram.org/bots/inline // запросы к боту из чатов: https://core.telegram.org/bots/inline
if (update.hasInlineQuery()) { if (update.hasInlineQuery()) {
final Optional<List<EventHandler>> optHandlers = getHandler(inlineQuery.getClass().getSimpleName()); return Uni.createFrom().item(new EventContainer<>(InlineQuery.class, inlineQuery));
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(inlineQuery)
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
if (update.hasPreCheckoutQuery()) { if (update.hasPreCheckoutQuery()) {
final Optional<List<EventHandler>> optHandlers = getHandler(preCheckoutQuery.getClass().getName()); return Uni.createFrom().item(new EventContainer<>(PreCheckoutQuery.class, preCheckoutQuery));
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(preCheckoutQuery)
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
if (update.hasMessage()) { if (update.hasMessage()) {
final Optional<List<EventHandler>> optHandlers = getHandler(Mail.class.getName()); return Uni.createFrom().item(new EventContainer<>(Mail.class, MessageMailConvert.apply(message)));
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(MessageMailConvert.apply(message))
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
if (update.hasCallbackQuery()) { if (update.hasCallbackQuery()) {
final Optional<List<EventHandler>> optHandlers = getHandler(Mail.class.getName()); return Uni.createFrom().item(new EventContainer<>(Mail.class, CallbackQueryConvert.apply(callbackQuery)));
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(CallbackQueryConvert.apply(callbackQuery))
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
if (update.hasMyChatMember()) { if (update.hasMyChatMember()) {
final ChatMemberUpdated chatMember = update.getMyChatMember(); final ChatMemberUpdated chatMember = update.getMyChatMember();
if ("kicked".equals(chatMember.getNewChatMember().getStatus())) { if ("kicked".equals(chatMember.getNewChatMember().getStatus())) {
return Uni.createFrom().item(new EventContainer<>(Unsubscribe.class, UnsubscribeConvert.apply(chatMember)));
final Optional<List<EventHandler>> optHandlers = getHandler(Unsubscribe.class.getName());
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(UnsubscribeConvert.apply(chatMember))
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
if ("member".equals(chatMember.getNewChatMember().getStatus())) { if ("member".equals(chatMember.getNewChatMember().getStatus())) {
final Optional<List<EventHandler>> optHandlers = getHandler(Subscribe.class.getName()); return Uni.createFrom().item(new EventContainer<>(Subscribe.class, SubscribeConvert.apply(chatMember)));
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(SubscribeConvert.apply(chatMember))
).concatenate().collect().asList().replaceWithVoid();
}
return Uni.createFrom().voidItem();
} }
} }
return Uni.createFrom().nullItem();
return Uni.createFrom().voidItem();
} }
); ).onItem().ifNotNull().transformToUni(eventDispatching::dispatch);
} }
private boolean isEvent(Message message) { private boolean isEvent(Message message) {
@ -148,8 +99,4 @@ public class EventDistributorService implements EventDistributor {
} }
} }
private Optional<List<EventHandler>> getHandler(String type) {
return Optional.ofNullable(eventHandlerMap.get(type));
}
} }

View File

@ -1,8 +1,9 @@
package dev.struchkov.godfather.telegram.simple.consumer; package dev.struchkov.godfather.telegram.simple.consumer;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.main.domain.content.ChatMail; import dev.struchkov.godfather.main.domain.content.ChatMail;
import dev.struchkov.godfather.main.domain.content.Mail; import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.simple.context.service.EventHandler; import dev.struchkov.godfather.simple.context.service.EventDispatching;
import dev.struchkov.godfather.telegram.domain.event.Subscribe; import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe; import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert; import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert;
@ -18,13 +19,11 @@ import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery; import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery; import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotBlank; import static dev.struchkov.haiti.utils.Checker.checkNotBlank;
import static dev.struchkov.haiti.utils.Checker.checkNotNull; import static dev.struchkov.haiti.utils.Checker.checkNotNull;
@ -36,10 +35,10 @@ import static dev.struchkov.haiti.utils.Checker.checkNotNull;
*/ */
public class EventDistributorService implements EventDistributor { public class EventDistributorService implements EventDistributor {
private final Map<String, List<EventHandler>> eventProviderMap; private final EventDispatching eventDispatching;
public EventDistributorService(TelegramConnect telegramConnect, List<EventHandler> eventProviders) { public EventDistributorService(TelegramConnect telegramConnect, EventDispatching eventDispatching) {
this.eventProviderMap = eventProviders.stream().collect(Collectors.groupingBy(EventHandler::getEventType)); this.eventDispatching = eventDispatching;
telegramConnect.initEventDistributor(this); telegramConnect.initEventDistributor(this);
} }
@ -51,12 +50,16 @@ public class EventDistributorService implements EventDistributor {
final InlineQuery inlineQuery = update.getInlineQuery(); final InlineQuery inlineQuery = update.getInlineQuery();
if (update.hasInlineQuery()) { if (update.hasInlineQuery()) {
getHandler(inlineQuery.getClass().getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(inlineQuery))); eventDispatching.dispatch(new EventContainer<>(InlineQuery.class, inlineQuery));
return; return;
} }
if (update.hasChosenInlineQuery()) {
eventDispatching.dispatch(new EventContainer<>(ChosenInlineQuery.class, update.getChosenInlineQuery()));
}
if (update.hasPreCheckoutQuery()) { if (update.hasPreCheckoutQuery()) {
getHandler(preCheckoutQuery.getClass().getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(preCheckoutQuery))); eventDispatching.dispatch(new EventContainer<>(PreCheckoutQuery.class, preCheckoutQuery));
return; return;
} }
@ -71,11 +74,13 @@ public class EventDistributorService implements EventDistributor {
if (update.hasMyChatMember()) { if (update.hasMyChatMember()) {
final ChatMemberUpdated chatMember = update.getMyChatMember(); final ChatMemberUpdated chatMember = update.getMyChatMember();
if ("kicked".equals(chatMember.getNewChatMember().getStatus())) { if ("kicked".equals(chatMember.getNewChatMember().getStatus())) {
getHandler(Unsubscribe.class.getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(UnsubscribeConvert.apply(chatMember)))); final Unsubscribe unsubscribe = UnsubscribeConvert.apply(chatMember);
eventDispatching.dispatch(new EventContainer<>(Unsubscribe.class, unsubscribe));
return; return;
} }
if ("member".equals(chatMember.getNewChatMember().getStatus())) { if ("member".equals(chatMember.getNewChatMember().getStatus())) {
getHandler(Subscribe.class.getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(SubscribeConvert.apply(chatMember)))); final Subscribe subscribe = SubscribeConvert.apply(chatMember);
eventDispatching.dispatch(new EventContainer<>(Subscribe.class, subscribe));
return; return;
} }
} }
@ -84,7 +89,6 @@ public class EventDistributorService implements EventDistributor {
private void processionCallback(CallbackQuery callbackQuery) { private void processionCallback(CallbackQuery callbackQuery) {
final Message message = callbackQuery.getMessage(); final Message message = callbackQuery.getMessage();
if (checkNotBlank(callbackQuery.getInlineMessageId())) { if (checkNotBlank(callbackQuery.getInlineMessageId())) {
return; return;
} }
if (checkNotNull(message)) { if (checkNotNull(message)) {
@ -93,7 +97,7 @@ public class EventDistributorService implements EventDistributor {
} else { } else {
final Mail mail = CallbackQueryConvert.apply(callbackQuery); final Mail mail = CallbackQueryConvert.apply(callbackQuery);
getHandler(Mail.class.getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(mail))); eventDispatching.dispatch(new EventContainer<>(Mail.class, mail));
} }
} }
} }
@ -102,10 +106,10 @@ public class EventDistributorService implements EventDistributor {
final Long fromId = message.getChat().getId(); final Long fromId = message.getChat().getId();
if (fromId < 0) { if (fromId < 0) {
final ChatMail chatMail = MessageChatMailConvert.apply(message); final ChatMail chatMail = MessageChatMailConvert.apply(message);
getHandler(ChatMail.class.getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(chatMail))); eventDispatching.dispatch(new EventContainer<>(ChatMail.class, chatMail));
} else { } else {
final Mail mail = MessageMailConvert.apply(message); final Mail mail = MessageMailConvert.apply(message);
getHandler(Mail.class.getSimpleName()).ifPresent(handlers -> handlers.forEach(handler -> handler.handle(mail))); eventDispatching.dispatch(new EventContainer<>(Mail.class, mail));
} }
} }
@ -130,8 +134,4 @@ public class EventDistributorService implements EventDistributor {
} }
} }
private Optional<List<EventHandler>> getHandler(String type) {
return Optional.ofNullable(eventProviderMap.get(type));
}
} }

View File

@ -22,7 +22,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>dev.struchkov.godfather</groupId> <groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context-simple</artifactId> <artifactId>bot-context-main</artifactId>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -10,4 +10,6 @@ public interface TelegramSending extends SendingService {
Uni<SentBox> sendNotSave(@NotNull BoxAnswer boxAnswer); Uni<SentBox> sendNotSave(@NotNull BoxAnswer boxAnswer);
Uni<Void> replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer);
} }

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<artifactId>telegram-context</artifactId> <artifactId>telegram-context</artifactId>
@ -17,12 +18,12 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather</groupId>
<artifactId>telegram-context-main</artifactId> <artifactId>bot-context-simple</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain-simple</artifactId> <artifactId>telegram-context-main</artifactId>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -1,9 +1,8 @@
package dev.struchkov.godfather.telegram.simple.context.service; package dev.struchkov.godfather.telegram.simple.context.service;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.Update;
import javax.validation.constraints.NotNull;
public interface EventDistributor { public interface EventDistributor {
void processing(@NotNull Update update); void processing(@NotNull Update update);

View File

@ -1,9 +1,8 @@
package dev.struchkov.godfather.telegram.simple.context.service; package dev.struchkov.godfather.telegram.simple.context.service;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.bots.AbsSender;
import javax.validation.constraints.NotNull;
/** /**
* TODO: Добавить описание интерфейса. * TODO: Добавить описание интерфейса.
* *

View File

@ -3,12 +3,13 @@ package dev.struchkov.godfather.telegram.simple.context.service;
import dev.struchkov.godfather.simple.context.service.SendingService; import dev.struchkov.godfather.simple.context.service.SendingService;
import dev.struchkov.godfather.simple.domain.BoxAnswer; import dev.struchkov.godfather.simple.domain.BoxAnswer;
import dev.struchkov.godfather.simple.domain.SentBox; import dev.struchkov.godfather.simple.domain.SentBox;
import org.jetbrains.annotations.NotNull;
import java.util.Optional; import java.util.Optional;
public interface TelegramSending extends SendingService { public interface TelegramSending extends SendingService {
Optional<SentBox> sendNotSave(@NotNull BoxAnswer boxAnswer); Optional<SentBox> sendNotSave(BoxAnswer boxAnswer);
void replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer);
} }

View File

@ -16,6 +16,10 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core-quarkus</artifactId>
</dependency>
<dependency> <dependency>
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context-quarkus</artifactId> <artifactId>telegram-context-quarkus</artifactId>
@ -25,10 +29,6 @@
<groupId>dev.struchkov.godfather.telegram</groupId> <groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core-main</artifactId> <artifactId>telegram-core-main</artifactId>
</dependency> </dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core-quarkus</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,12 +1,12 @@
package dev.struchkov.godfather.telegram.quarkus.core.handler; package dev.struchkov.godfather.telegram.quarkus.core.handler;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.quarkus.context.service.EventHandler; import dev.struchkov.godfather.quarkus.context.service.EventHandler;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect; import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.Uni;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery; import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery;
import org.telegram.telegrambots.meta.api.methods.AnswerShippingQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery; import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
@ -21,9 +21,10 @@ public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
private final TelegramConnect telegramConnect; private final TelegramConnect telegramConnect;
@Override @Override
public Uni<Void> handle(PreCheckoutQuery event) { public Uni<Void> handle(EventContainer<PreCheckoutQuery> event) {
final PreCheckoutQuery preCheckoutQuery = event.getObject();
final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery(); final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery();
answerPreCheckoutQuery.setPreCheckoutQueryId(event.getId()); answerPreCheckoutQuery.setPreCheckoutQueryId(preCheckoutQuery.getId());
answerPreCheckoutQuery.setOk(true); answerPreCheckoutQuery.setOk(true);
try { try {
answerPreCheckoutQuery.validate(); answerPreCheckoutQuery.validate();
@ -45,8 +46,8 @@ public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
} }
@Override @Override
public String getEventType() { public Class<PreCheckoutQuery> getEventClass() {
return PreCheckoutQuery.class.getName(); return PreCheckoutQuery.class;
} }
} }

View File

@ -1,5 +1,6 @@
package dev.struchkov.godfather.telegram.simple.core.handler; package dev.struchkov.godfather.telegram.simple.core.handler;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.simple.context.service.EventHandler; import dev.struchkov.godfather.simple.context.service.EventHandler;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect; import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -15,9 +16,10 @@ public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
private final TelegramConnect telegramConnect; private final TelegramConnect telegramConnect;
@Override @Override
public void handle(PreCheckoutQuery event) { public void handle(EventContainer<PreCheckoutQuery> event) {
final PreCheckoutQuery preCheckoutQuery = event.getObject();
final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery(); final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery();
answerPreCheckoutQuery.setPreCheckoutQueryId(event.getId()); answerPreCheckoutQuery.setPreCheckoutQueryId(preCheckoutQuery.getId());
answerPreCheckoutQuery.setOk(true); answerPreCheckoutQuery.setOk(true);
try { try {
answerPreCheckoutQuery.validate(); answerPreCheckoutQuery.validate();
@ -29,8 +31,8 @@ public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
} }
@Override @Override
public String getEventType() { public Class<PreCheckoutQuery> getEventClass() {
return PreCheckoutQuery.class.getSimpleName(); return PreCheckoutQuery.class;
} }
} }

View File

@ -20,6 +20,10 @@
<groupId>dev.struchkov.godfather</groupId> <groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-domain-main</artifactId> <artifactId>bot-domain-main</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,6 +1,10 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
@ -10,6 +14,8 @@ import java.util.Optional;
import static dev.struchkov.haiti.context.exception.NotFoundException.notFoundException; import static dev.struchkov.haiti.context.exception.NotFoundException.notFoundException;
import static dev.struchkov.haiti.utils.Inspector.isNotNull; import static dev.struchkov.haiti.utils.Inspector.isNotNull;
@Getter
@Setter
public class ButtonClickAttachment extends Attachment { public class ButtonClickAttachment extends Attachment {
/** /**
@ -17,14 +23,10 @@ public class ButtonClickAttachment extends Attachment {
*/ */
private String messageId; private String messageId;
private String rawCallBackData; private String rawCallBackData;
private final Map<String, Arg> args = new HashMap<>(); private Map<String, Arg> args = new HashMap<>();
public String getRawCallBackData() { public ButtonClickAttachment() {
return rawCallBackData; super(TelegramAttachmentType.BUTTON_CLICK.name());
}
public void setRawCallBackData(String rawCallBackData) {
this.rawCallBackData = rawCallBackData;
} }
public void addClickArg(String type, String value) { public void addClickArg(String type, String value) {
@ -46,40 +48,14 @@ public class ButtonClickAttachment extends Attachment {
return args.values(); return args.values();
} }
public String getMessageId() { @Getter
return messageId; @Setter
} @NoArgsConstructor
@AllArgsConstructor
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Map<String, Arg> getArgs() {
return args;
}
@Override
public String getType() {
return TelegramAttachmentType.BUTTON_CLICK.name();
}
public static class Arg { public static class Arg {
private final String type; private String type;
private final String value; private String value;
private Arg(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
} }

View File

@ -1,11 +1,15 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
import java.util.Optional; import java.util.Optional;
import static dev.struchkov.haiti.utils.Checker.checkNotNull; import static dev.struchkov.haiti.utils.Checker.checkNotNull;
@Getter
@Setter
public class CommandAttachment extends Attachment { public class CommandAttachment extends Attachment {
private String value; private String value;
@ -13,34 +17,14 @@ public class CommandAttachment extends Attachment {
private String arg; private String arg;
private String rawValue; private String rawValue;
public void setValue(String value) { public CommandAttachment() {
this.value = value; super(TelegramAttachmentType.COMMAND.name());
}
public void setCommandType(String commandType) {
this.commandType = commandType;
}
public void setArg(String arg) {
this.arg = arg;
}
public void setRawValue(String rawValue) {
this.rawValue = rawValue;
}
public String getValue() {
return value;
} }
public Optional<String> getArg() { public Optional<String> getArg() {
return Optional.ofNullable(arg); return Optional.ofNullable(arg);
} }
public String getCommandType() {
return commandType;
}
public boolean isCommandType(String type) { public boolean isCommandType(String type) {
if (checkNotNull(type)) { if (checkNotNull(type)) {
return type.equals(commandType); return type.equals(commandType);
@ -48,12 +32,4 @@ public class CommandAttachment extends Attachment {
return false; return false;
} }
public String getRawValue() {
return rawValue;
}
@Override
public String getType() {
return TelegramAttachmentType.COMMAND.name();
}
} }

View File

@ -1,7 +1,11 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ContactAttachment extends Attachment { public class ContactAttachment extends Attachment {
private String phoneNumber; private String phoneNumber;
@ -15,57 +19,8 @@ public class ContactAttachment extends Attachment {
*/ */
private boolean owner; private boolean owner;
public String getPhoneNumber() { public ContactAttachment() {
return phoneNumber; super(TelegramAttachmentType.CONTACT.name());
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public boolean isOwner() {
return owner;
}
public void setOwner(boolean owner) {
this.owner = owner;
}
public String getVCard() {
return vCard;
}
public void setVCard(String vCard) {
this.vCard = vCard;
}
@Override
public String getType() {
return TelegramAttachmentType.CONTACT.name();
} }
} }

View File

@ -1,7 +1,11 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class DocumentAttachment extends Attachment { public class DocumentAttachment extends Attachment {
private String fileId; private String fileId;
@ -9,41 +13,8 @@ public class DocumentAttachment extends Attachment {
private String fileName; private String fileName;
private String mimeType; private String mimeType;
public String getFileId() { public DocumentAttachment() {
return fileId; super(TelegramAttachmentType.DOCUMENT.name());
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Override
public String getType() {
return TelegramAttachmentType.DOCUMENT.name();
} }
} }

View File

@ -3,28 +3,24 @@ package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.haiti.utils.Parser; import dev.struchkov.haiti.utils.Parser;
import dev.struchkov.haiti.utils.container.CompositeUrl; import dev.struchkov.haiti.utils.container.CompositeUrl;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LinkAttachment extends Attachment { public class LinkAttachment extends Attachment {
private String url; private String url;
public LinkAttachment() {
super(TelegramAttachmentType.LINK.name());
}
public LinkAttachment(String url) { public LinkAttachment(String url) {
super(TelegramAttachmentType.LINK.name());
this.url = url; this.url = url;
} }
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
@Override
public String getType() {
return TelegramAttachmentType.LINK.name();
}
public CompositeUrl split() { public CompositeUrl split() {
return Parser.url(url); return Parser.url(url);
} }

View File

@ -1,5 +1,10 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Picture { public class Picture {
private String fileId; private String fileId;
@ -8,44 +13,4 @@ public class Picture {
private Integer weight; private Integer weight;
private Integer height; private Integer height;
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFileUniqueId() {
return fileUniqueId;
}
public void setFileUniqueId(String fileUniqueId) {
this.fileUniqueId = fileUniqueId;
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
} }

View File

@ -1,21 +1,21 @@
package dev.struchkov.godfather.telegram.domain.attachment; package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment; import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Getter
@Setter
public class PictureGroupAttachment extends Attachment { public class PictureGroupAttachment extends Attachment {
private List<Picture> pictures; private List<Picture> pictures;
public void setPictureSizes(List<Picture> pictures) { public PictureGroupAttachment() {
this.pictures = pictures; super(TelegramAttachmentType.PICTURE.name());
}
public List<Picture> getPictureSizes() {
return pictures;
} }
public Optional<Picture> getLargePicture() { public Optional<Picture> getLargePicture() {
@ -23,9 +23,4 @@ public class PictureGroupAttachment extends Attachment {
.max(Comparator.comparingInt(Picture::getFileSize)); .max(Comparator.comparingInt(Picture::getFileSize));
} }
@Override
public String getType() {
return TelegramAttachmentType.PICTURE.name();
}
} }

View File

@ -0,0 +1,45 @@
package dev.struchkov.godfather.telegram.domain.deser;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.ContactAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.LinkAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.PictureGroupAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.TelegramAttachmentType;
import dev.struchkov.haiti.utils.ObjectUtils;
import java.io.IOException;
public class TelegramAttachmentDeserializer extends StdDeserializer<Attachment> {
public TelegramAttachmentDeserializer() {
this(null);
}
public TelegramAttachmentDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Attachment deserialize(JsonParser parser, DeserializationContext context) throws IOException {
final JsonNode node = parser.getCodec().readTree(parser);
final String typeAttachmentString = node.get("type").asText();
final TelegramAttachmentType type = ObjectUtils.createEnum(typeAttachmentString, TelegramAttachmentType.class)
.orElseThrow(() -> new IllegalArgumentException("Неизвестный тип вложения: " + typeAttachmentString));
return switch (type) {
case BUTTON_CLICK -> parser.getCodec().treeToValue(node, ButtonClickAttachment.class);
case DOCUMENT -> parser.getCodec().treeToValue(node, DocumentAttachment.class);
case CONTACT -> parser.getCodec().treeToValue(node, ContactAttachment.class);
case PICTURE -> parser.getCodec().treeToValue(node, PictureGroupAttachment.class);
case LINK -> parser.getCodec().treeToValue(node, LinkAttachment.class);
case COMMAND -> parser.getCodec().treeToValue(node, CommandAttachment.class);
};
}
}

View File

@ -93,6 +93,30 @@ public class TelegramSender implements TelegramSending {
return sendBoxAnswer(boxAnswer, false); return sendBoxAnswer(boxAnswer, false);
} }
@Override
public Uni<Void> replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer) {
return Uni.createFrom().voidItem()
.onItem().transformToUni(
v -> {
final EditMessageText editMessageText = new EditMessageText();
editMessageText.setInlineMessageId(inlineMessageId);
editMessageText.enableMarkdown(true);
editMessageText.setText(boxAnswer.getMessage());
editMessageText.setReplyMarkup(convertInlineKeyBoard((InlineKeyBoard) boxAnswer.getKeyBoard()));
return Uni.createFrom().completionStage(executeAsync(editMessageText))
.onFailure(TelegramApiRequestException.class).call(
ex -> {
final TelegramApiRequestException exception = (TelegramApiRequestException) ex;
final String apiResponse = exception.getApiResponse();
log.error(apiResponse, exception);
return Uni.createFrom().voidItem();
}
).replaceWithVoid();
}
);
}
private Uni<SentBox> sendBoxAnswer(@NotNull BoxAnswer boxAnswer, boolean saveMessageId) { private Uni<SentBox> sendBoxAnswer(@NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
return Uni.createFrom().voidItem() return Uni.createFrom().voidItem()
.onItem().transformToUni( .onItem().transformToUni(

View File

@ -91,6 +91,22 @@ public class TelegramSender implements TelegramSending {
return sendBoxAnswer(boxAnswer, false); return sendBoxAnswer(boxAnswer, false);
} }
@Override
public void replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer) {
final EditMessageText editMessageText = new EditMessageText();
editMessageText.setInlineMessageId(inlineMessageId);
editMessageText.enableMarkdown(true);
editMessageText.setText(boxAnswer.getMessage());
editMessageText.setReplyMarkup(convertInlineKeyBoard((InlineKeyBoard) boxAnswer.getKeyBoard()));
try {
absSender.execute(editMessageText);
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {
log.error(e.getMessage(), e);
}
}
private Optional<SentBox> sendBoxAnswer(BoxAnswer boxAnswer, boolean saveMessageId) { private Optional<SentBox> sendBoxAnswer(BoxAnswer boxAnswer, boolean saveMessageId) {
final String recipientTelegramId = boxAnswer.getRecipientPersonId(); final String recipientTelegramId = boxAnswer.getRecipientPersonId();
isNotNull(recipientTelegramId); isNotNull(recipientTelegramId);