Добавил поддержку команд

This commit is contained in:
Struchkov Mark 2022-07-30 10:31:31 +03:00
parent 54e1fad49b
commit 98bed43267
44 changed files with 646 additions and 153 deletions

40
pom.xml
View File

@ -3,13 +3,18 @@
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>
<groupId>dev.struchkov.godfather</groupId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.23</version>
<version>0.0.26</version>
<packaging>pom</packaging>
<modules>
<module>telegram-core</module>
<module>telegram-sender</module>
<module>telegram-domain</module>
<module>telegram-consumer</module>
<module>telegram-context</module>
<module>telegram</module>
</modules>
<name>Telegram Bot</name>
@ -33,9 +38,11 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<godfather.core.ver>0.0.18</godfather.core.ver>
<godfather.core.ver>0.0.22</godfather.core.ver>
<telegrambots.ver>6.1.0</telegrambots.ver>
<haiti.version>1.3.0</haiti.version>
<plugin.maven.compiler.ver>3.10.1</plugin.maven.compiler.ver>
<plugin.nexus.staging.ver>1.6.13</plugin.nexus.staging.ver>
<plugin.maven.source.ver>3.2.1</plugin.maven.source.ver>
@ -45,12 +52,39 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context</artifactId>
<version>${godfather.core.ver}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core</artifactId>
<version>${godfather.core.ver}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.haiti</groupId>
<artifactId>haiti-utils</artifactId>
<version>${haiti.version}</version>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>

33
telegram-consumer/pom.xml Normal file
View File

@ -0,0 +1,33 @@
<?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">
<parent>
<artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.26</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>telegram-consumer</artifactId>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
</project>

View File

@ -1,18 +1,22 @@
package dev.struchkov.godfather.telegram.listen;
import dev.struchkov.godfather.context.domain.content.Mail;
import dev.struchkov.godfather.context.service.EventProvider;
import dev.struchkov.godfather.telegram.TelegramConnect;
import dev.struchkov.godfather.context.service.EventHandler;
import dev.struchkov.godfather.telegram.TelegramConnectBot;
import dev.struchkov.godfather.telegram.context.EventDistributor;
import dev.struchkov.godfather.telegram.convert.CallbackQueryConvert;
import dev.struchkov.godfather.telegram.convert.CommandConvert;
import dev.struchkov.godfather.telegram.convert.MessageMailConvert;
import dev.struchkov.godfather.telegram.convert.SubscribeConvert;
import dev.struchkov.godfather.telegram.convert.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.domain.event.Command;
import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
@ -21,6 +25,8 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotEmpty;
/**
* TODO: Добавить описание класса.
*
@ -28,11 +34,11 @@ import java.util.stream.Collectors;
*/
public class EventDistributorService implements EventDistributor {
private final Map<String, List<EventProvider>> eventProviderMap;
private final Map<String, List<EventHandler>> eventProviderMap;
public EventDistributorService(TelegramConnect telegramConnect, List<EventProvider> eventProviders) {
this.eventProviderMap = eventProviders.stream().collect(Collectors.groupingBy(EventProvider::getEventType));
telegramConnect.initEventDistributor(this);
public EventDistributorService(TelegramConnectBot telegramConnectBot, List<EventHandler> eventProviders) {
this.eventProviderMap = eventProviders.stream().collect(Collectors.groupingBy(EventHandler::getEventType));
telegramConnectBot.initEventDistributor(this);
}
@Override
@ -40,24 +46,34 @@ public class EventDistributorService implements EventDistributor {
if (update.getMessage() != null) {
final Message message = update.getMessage();
if (!isEvent(message)) {
getEventProvider(Mail.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.sendEvent(MessageMailConvert.apply(message))));
if (isCommand(message)) {
getHandler(Command.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(CommandConvert.apply(message))));
return;
} else {
getHandler(Mail.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(MessageMailConvert.apply(message))));
return;
}
}
}
if (update.getCallbackQuery() != null) {
final CallbackQuery callbackQuery = update.getCallbackQuery();
getEventProvider(Mail.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.sendEvent(CallbackQueryConvert.apply(callbackQuery))));
getHandler(Mail.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(CallbackQueryConvert.apply(callbackQuery))));
return;
}
if (update.getMyChatMember() != null) {
final ChatMemberUpdated chatMember = update.getMyChatMember();
if ("kicked".equals(chatMember.getNewChatMember().getStatus())) {
getEventProvider(Unsubscribe.TYPE)
.ifPresent(providers -> providers.forEach(provider -> provider.sendEvent(UnsubscribeConvert.apply(chatMember))));
getHandler(Unsubscribe.TYPE)
.ifPresent(providers -> providers.forEach(provider -> provider.handle(UnsubscribeConvert.apply(chatMember))));
return;
}
if ("member".equals(chatMember.getNewChatMember().getStatus())) {
getEventProvider(Subscribe.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.sendEvent(SubscribeConvert.apply(chatMember))));
getHandler(Subscribe.TYPE)
.ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(SubscribeConvert.apply(chatMember))));
return;
}
}
}
@ -83,7 +99,15 @@ public class EventDistributorService implements EventDistributor {
}
}
private Optional<List<EventProvider>> getEventProvider(String type) {
private boolean isCommand(Message message) {
final List<MessageEntity> entities = message.getEntities();
if (checkNotEmpty(entities)) {
return "bot_command".equals(entities.get(0).getType());
}
return false;
}
private Optional<List<EventHandler>> getHandler(String type) {
return Optional.ofNullable(eventProviderMap.get(type));
}

31
telegram-context/pom.xml Normal file
View File

@ -0,0 +1,31 @@
<?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">
<parent>
<artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.26</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>telegram-context</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context</artifactId>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
</dependency>
</dependencies>
</project>

View File

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

View File

@ -0,0 +1,13 @@
package dev.struchkov.godfather.telegram.context;
import java.util.Optional;
public interface SenderStorageService {
Optional<Integer> getLastSendMessage(Long telegramId);
void saveLastSendMessage(Long telegramId, Integer messageId);
void removeLastSendMessage(Long telegramId);
}

View File

@ -0,0 +1,18 @@
package dev.struchkov.godfather.telegram.context;
import org.telegram.telegrambots.meta.bots.AbsSender;
import javax.validation.constraints.NotNull;
/**
* TODO: Добавить описание интерфейса.
*
* @author upagge [12.02.2020]
*/
public interface TelegramBot {
AbsSender getAdsSender();
void initEventDistributor(@NotNull EventDistributor eventDistributor);
}

View File

@ -0,0 +1,11 @@
package dev.struchkov.godfather.telegram.context;
import org.telegram.telegrambots.meta.bots.AbsSender;
public interface TelegramConnect {
AbsSender getAbsSender();
String getToken();
}

View File

@ -0,0 +1,11 @@
package dev.struchkov.godfather.telegram.context;
import dev.struchkov.godfather.context.domain.BoxAnswer;
import dev.struchkov.godfather.context.service.sender.Sending;
import org.jetbrains.annotations.NotNull;
public interface TelegramSending extends Sending {
void sendNotSave(@NotNull Long personId, @NotNull BoxAnswer boxAnswer);
}

View File

@ -3,9 +3,9 @@
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>
<parent>
<groupId>dev.struchkov.godfather</groupId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.23</version>
<version>0.0.26</version>
</parent>
<artifactId>telegram-core</artifactId>
@ -14,6 +14,15 @@
<description>Allows you to create bots for Telegram</description>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core</artifactId>

View File

@ -1,18 +0,0 @@
package dev.struchkov.godfather.telegram;
import dev.struchkov.godfather.telegram.listen.EventDistributorService;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.bots.AbsSender;
/**
* TODO: Добавить описание интерфейса.
*
* @author upagge [12.02.2020]
*/
public interface TelegramBot {
AbsSender getAdsSender();
void initEventDistributor(@NotNull EventDistributorService eventDistributor);
}

View File

@ -1,8 +1,11 @@
package dev.struchkov.godfather.telegram;
import dev.struchkov.godfather.telegram.config.ProxyConfig;
import dev.struchkov.godfather.telegram.config.TelegramPollingConfig;
import dev.struchkov.godfather.telegram.listen.EventDistributorService;
import dev.struchkov.godfather.telegram.context.EventDistributor;
import dev.struchkov.godfather.telegram.context.TelegramBot;
import dev.struchkov.godfather.telegram.context.TelegramConnect;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig.Type;
import dev.struchkov.godfather.telegram.domain.config.TelegramConnectConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.bots.DefaultBotOptions;
@ -19,16 +22,16 @@ import java.net.PasswordAuthentication;
*
* @author upagge [30.01.2020]
*/
public class TelegramConnect {
public class TelegramConnectBot implements TelegramConnect {
private static final Logger log = LoggerFactory.getLogger(TelegramConnect.class);
private static final Logger log = LoggerFactory.getLogger(TelegramConnectBot.class);
private TelegramBot telegramBot;
private final TelegramPollingConfig telegramPollingConfig;
private final TelegramConnectConfig telegramConnectConfig;
public TelegramConnect(TelegramPollingConfig telegramPollingConfig) {
this.telegramPollingConfig = telegramPollingConfig;
initLongPolling(telegramPollingConfig);
public TelegramConnectBot(TelegramConnectConfig telegramConnectConfig) {
this.telegramConnectConfig = telegramConnectConfig;
initLongPolling(telegramConnectConfig);
}
// public TelegramConnect(TelegramWebHookConfig telegramWebHookConfig) {
@ -46,9 +49,9 @@ public class TelegramConnect {
// }
// }
private void initLongPolling(TelegramPollingConfig telegramPollingConfig) {
private void initLongPolling(TelegramConnectConfig telegramConnectConfig) {
final ProxyConfig proxyConfig = telegramPollingConfig.getProxyConfig();
final ProxyConfig proxyConfig = telegramConnectConfig.getProxyConfig();
if (proxyConfig != null && proxyConfig.getPassword() != null) {
try {
Authenticator.setDefault(new Authenticator() {
@ -77,14 +80,13 @@ public class TelegramConnect {
botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
final TelegramPollingBot bot = new TelegramPollingBot(telegramPollingConfig, botOptions);
final TelegramPollingBot bot = new TelegramPollingBot(telegramConnectConfig, botOptions);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
} else {
final TelegramPollingBot bot = new TelegramPollingBot(telegramPollingConfig);
final TelegramPollingBot bot = new TelegramPollingBot(telegramConnectConfig);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
@ -94,7 +96,7 @@ public class TelegramConnect {
}
}
private DefaultBotOptions.ProxyType convertProxyType(ProxyConfig.Type type) {
private DefaultBotOptions.ProxyType convertProxyType(Type type) {
switch (type) {
case SOCKS5:
return DefaultBotOptions.ProxyType.SOCKS5;
@ -107,16 +109,17 @@ public class TelegramConnect {
}
}
public AbsSender getAdsSender() {
return telegramBot.getAdsSender();
}
public void initEventDistributor(EventDistributorService eventDistributor) {
public void initEventDistributor(EventDistributor eventDistributor) {
telegramBot.initEventDistributor(eventDistributor);
}
public String getToken() {
return telegramPollingConfig.getBotToken();
return telegramConnectConfig.getBotToken();
}
@Override
public AbsSender getAbsSender() {
return telegramBot.getAdsSender();
}
}

View File

@ -0,0 +1,34 @@
package dev.struchkov.godfather.telegram;
import dev.struchkov.godfather.telegram.context.TelegramConnect;
import dev.struchkov.godfather.telegram.domain.config.TelegramConnectConfig;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.bots.AbsSender;
public class TelegramDefaultConnect implements TelegramConnect {
private final String botToken;
private final AbsSender absSender;
public TelegramDefaultConnect(TelegramConnectConfig telegramConnectConfig) {
this.botToken = telegramConnectConfig.getBotToken();
this.absSender = new DefaultAbsSender(new DefaultBotOptions()) {
@Override
public String getBotToken() {
return botToken;
}
};
}
@Override
public AbsSender getAbsSender() {
return absSender;
}
@Override
public String getToken() {
return botToken;
}
}

View File

@ -1,8 +1,8 @@
package dev.struchkov.godfather.telegram;
import dev.struchkov.godfather.telegram.config.TelegramPollingConfig;
import dev.struchkov.godfather.telegram.listen.EventDistributor;
import dev.struchkov.godfather.telegram.listen.EventDistributorService;
import dev.struchkov.godfather.telegram.context.EventDistributor;
import dev.struchkov.godfather.telegram.context.TelegramBot;
import dev.struchkov.godfather.telegram.domain.config.TelegramConnectConfig;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
@ -16,16 +16,16 @@ import org.telegram.telegrambots.meta.bots.AbsSender;
*/
public class TelegramPollingBot extends TelegramLongPollingBot implements TelegramBot {
private final TelegramPollingConfig telegramPollingConfig;
private final TelegramConnectConfig telegramConnectConfig;
private EventDistributor eventDistributor;
public TelegramPollingBot(TelegramPollingConfig telegramPollingConfig, DefaultBotOptions defaultBotOptions) {
public TelegramPollingBot(TelegramConnectConfig telegramConnectConfig, DefaultBotOptions defaultBotOptions) {
super(defaultBotOptions);
this.telegramPollingConfig = telegramPollingConfig;
this.telegramConnectConfig = telegramConnectConfig;
}
public TelegramPollingBot(TelegramPollingConfig telegramPollingConfig) {
this.telegramPollingConfig = telegramPollingConfig;
public TelegramPollingBot(TelegramConnectConfig telegramConnectConfig) {
this.telegramConnectConfig = telegramConnectConfig;
}
@Override
@ -37,12 +37,12 @@ public class TelegramPollingBot extends TelegramLongPollingBot implements Telegr
@Override
public String getBotUsername() {
return telegramPollingConfig.getBotUsername();
return telegramConnectConfig.getBotUsername();
}
@Override
public String getBotToken() {
return telegramPollingConfig.getBotToken();
return telegramConnectConfig.getBotToken();
}
@Override
@ -51,7 +51,7 @@ public class TelegramPollingBot extends TelegramLongPollingBot implements Telegr
}
@Override
public void initEventDistributor(@NotNull EventDistributorService eventDistributor) {
public void initEventDistributor(@NotNull EventDistributor eventDistributor) {
this.eventDistributor = eventDistributor;
}

View File

@ -0,0 +1,50 @@
package dev.struchkov.godfather.telegram.convert;
import dev.struchkov.godfather.telegram.domain.event.Command;
import dev.struchkov.haiti.utils.Strings;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import java.util.List;
import static dev.struchkov.haiti.context.exception.ConvertException.convertException;
import static dev.struchkov.haiti.utils.Checker.checkNotEmpty;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
import static dev.struchkov.haiti.utils.Inspector.isNotEmpty;
import static dev.struchkov.haiti.utils.Inspector.isTrue;
public class CommandConvert {
private CommandConvert() {
utilityClass();
}
public static Command apply(Message message) {
final List<MessageEntity> entities = message.getEntities();
isNotEmpty(entities, convertException("Ошибка преобразования сообщения в команду. В сообщении не обнаружена команда."));
final MessageEntity messageEntity = entities.get(0);
isTrue("bot_command".equals(messageEntity.getType()), convertException("Ошибка преобразования сообщения в команду. В сообщении не обнаружена команда."));
final String commandValue = messageEntity.getText();
String commandArg = message.getText().replace(commandValue, "");
if (checkNotEmpty(commandArg)) {
commandArg = commandArg.substring(1);
}
final Command command = new Command();
command.setValue(commandValue);
command.setCommandType(commandValue.replace("/", ""));
command.setArg(Strings.EMPTY.equals(commandArg) ? null : commandArg);
command.setRawValue(message.getText());
final Chat chat = message.getChat();
command.setFirstName(chat.getFirstName());
command.setLastName(chat.getLastName());
command.setPersonId(chat.getId());
return command;
}
}

View File

@ -105,7 +105,7 @@ public final class MessageMailConvert {
attachment.setFileId(document.getFileId());
attachment.setFileSize(document.getFileSize());
attachment.setFileName(document.getFileName());
attachment.setFileType(document.getMimeType());
attachment.setMimeType(document.getMimeType());
return Optional.of(attachment);
}
return Optional.empty();

View File

@ -1,14 +0,0 @@
package dev.struchkov.godfather.telegram.domain.event;
import dev.struchkov.godfather.context.domain.event.Event;
public class Command implements Event {
public static final String TYPE = "CMD";
@Override
public String getType() {
return TYPE;
}
}

View File

@ -1,6 +1,6 @@
package dev.struchkov.godfather.telegram.service;
import dev.struchkov.godfather.telegram.TelegramConnect;
import dev.struchkov.godfather.telegram.context.TelegramConnect;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.files.ByteContainer;
@ -35,7 +35,7 @@ public class AttachmentServiceImpl {
private String folderPathForFiles;
public AttachmentServiceImpl(TelegramConnect telegramConnect) {
this.absSender = telegramConnect.getAdsSender();
this.absSender = telegramConnect.getAbsSender();
this.botToken = telegramConnect.getToken();
}
@ -54,14 +54,13 @@ public class AttachmentServiceImpl {
log.error(e.getMessage());
}
}
}
public FileContainer uploadFile(@NotNull DocumentAttachment documentAttachment) {
isNotNull(documentAttachment);
try {
final File file = downloadFile(documentAttachment);
return new FileContainer(documentAttachment.getFileName(), file);
return new FileContainer(documentAttachment.getFileName(), documentAttachment.getMimeType(), file);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
@ -72,7 +71,7 @@ public class AttachmentServiceImpl {
isNotNull(documentAttachment);
try {
final byte[] bytes = downloadBytes(documentAttachment);
return new ByteContainer(documentAttachment.getFileName(), bytes);
return new ByteContainer(documentAttachment.getFileName(), documentAttachment.getMimeType(), bytes);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
@ -83,7 +82,7 @@ public class AttachmentServiceImpl {
isNotNull(picture);
try {
final byte[] bytes = downloadBytes(picture);
return new ByteContainer(null, bytes);
return new ByteContainer(null, "image/jpeg", bytes);
} catch (Exception e) {
log.error(e.getMessage(), e);
}

View File

@ -0,0 +1,32 @@
package dev.struchkov.godfather.telegram.service;
import dev.struchkov.godfather.telegram.context.SenderStorageService;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dev.struchkov.haiti.utils.Inspector.isNotNull;
public class SenderMapStorageService implements SenderStorageService {
private final Map<Long, Integer> lastMessageId = new HashMap<>();
@Override
public Optional<Integer> getLastSendMessage(Long telegramId) {
return Optional.ofNullable(lastMessageId.get(telegramId));
}
@Override
public void saveLastSendMessage(@NotNull Long telegramId, @NotNull Integer messageId) {
isNotNull(telegramId);
lastMessageId.put(telegramId, messageId);
}
@Override
public void removeLastSendMessage(Long telegramId) {
lastMessageId.remove(telegramId);
}
}

View File

@ -1,18 +0,0 @@
package dev.struchkov.godfather.telegram.service.provider;
import dev.struchkov.godfather.context.service.EventProvider;
import dev.struchkov.godfather.telegram.domain.event.Command;
public class CommandProvider implements EventProvider<Command> {
@Override
public void sendEvent(Command event) {
}
@Override
public String getEventType() {
return Command.TYPE;
}
}

31
telegram-domain/pom.xml Normal file
View File

@ -0,0 +1,31 @@
<?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">
<parent>
<artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.26</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>telegram-domain</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context</artifactId>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -7,7 +7,7 @@ public class DocumentAttachment extends Attachment {
private String fileId;
private Long fileSize;
private String fileName;
private String fileType;
private String mimeType;
public String getFileId() {
return fileId;
@ -33,12 +33,12 @@ public class DocumentAttachment extends Attachment {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
public String getMimeType() {
return mimeType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Override

View File

@ -1,4 +1,4 @@
package dev.struchkov.godfather.telegram.config;
package dev.struchkov.godfather.telegram.domain.config;
/**
* TODO: Добавить описание класса.

View File

@ -1,23 +1,23 @@
package dev.struchkov.godfather.telegram.config;
package dev.struchkov.godfather.telegram.domain.config;
/**
* TODO: Добавить описание класса.
*
* @author upagge [18.08.2019]
*/
public class TelegramPollingConfig {
public class TelegramConnectConfig {
private String botUsername;
private String botToken;
private ProxyConfig proxyConfig;
public TelegramPollingConfig(String botUsername, String botToken) {
public TelegramConnectConfig(String botUsername, String botToken) {
this.botUsername = botUsername;
this.botToken = botToken;
}
public TelegramPollingConfig() {
public TelegramConnectConfig() {
}
public void setBotUsername(String botUsername) {

View File

@ -0,0 +1,80 @@
package dev.struchkov.godfather.telegram.domain.event;
import dev.struchkov.godfather.context.domain.event.Event;
import java.util.Optional;
public class Command implements Event {
public static final String TYPE = "CMD";
private String value;
private String commandType;
private String arg;
private String rawValue;
private String firstName;
private String lastName;
private Long personId;
public void setValue(String value) {
this.value = value;
}
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 void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
public String getValue() {
return value;
}
public Optional<String> getArg() {
return Optional.ofNullable(arg);
}
public String getCommandType() {
return commandType;
}
public String getRawValue() {
return rawValue;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Long getPersonId() {
return personId;
}
@Override
public String getEventType() {
return TYPE;
}
}

View File

@ -46,7 +46,7 @@ public class Subscribe implements Event {
}
@Override
public String getType() {
public String getEventType() {
return TYPE;
}

View File

@ -46,7 +46,7 @@ public class Unsubscribe implements Event {
}
@Override
public String getType() {
public String getEventType() {
return TYPE;
}

View File

@ -2,13 +2,15 @@ package dev.struchkov.godfather.telegram.domain.files;
public class ByteContainer {
public static final ByteContainer EMPTY = new ByteContainer(null, null);
public static final ByteContainer EMPTY = new ByteContainer(null, null, null);
private final String fileName;
private final String mimeType;
private final byte[] bytes;
public ByteContainer(String fileName, byte[] bytes) {
public ByteContainer(String fileName, String mimeType, byte[] bytes) {
this.fileName = fileName;
this.mimeType = mimeType;
this.bytes = bytes;
}
@ -24,6 +26,10 @@ public class ByteContainer {
return bytes;
}
public String getMimeType() {
return mimeType;
}
public boolean isNotEmpty() {
return bytes != null && bytes.length > 0;
}

View File

@ -9,16 +9,18 @@ import java.nio.file.Files;
public class FileContainer {
public static final FileContainer EMPTY = new FileContainer(null, null);
public static final FileContainer EMPTY = new FileContainer(null, null, null);
private static final Logger log = LoggerFactory.getLogger(FileContainer.class);
private final String fileName;
private final File file;
private final String mimeType;
public FileContainer(String fileName, File file) {
public FileContainer(String fileName, String mimeType, File file) {
this.fileName = fileName;
this.file = file;
this.mimeType = mimeType;
}
public static FileContainer empty() {
@ -33,6 +35,10 @@ public class FileContainer {
return file;
}
public String getMimeType() {
return mimeType;
}
public boolean isNotEmpty() {
return file != null;
}

View File

@ -3,6 +3,7 @@ package dev.struchkov.godfather.telegram.domain.keyboard;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoard;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoardButton;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoardLine;
import dev.struchkov.godfather.context.domain.keyboard.simple.SimpleKeyBoardLine;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,6 +1,7 @@
package dev.struchkov.godfather.telegram.domain.keyboard.button;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoardButton;
import org.jetbrains.annotations.NotNull;
/**
* Запрашивает у пользователя его контактный номер.
@ -11,10 +12,14 @@ public class ContactButton implements KeyBoardButton {
private final String label;
public ContactButton(String label) {
private ContactButton(String label) {
this.label = label;
}
public static ContactButton contactButton(@NotNull String label) {
return new ContactButton(label);
}
public String getLabel() {
return label;
}

View File

@ -1,20 +1,21 @@
package dev.struchkov.godfather.telegram.domain.keyboard.button;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoardButton;
import org.jetbrains.annotations.NotNull;
public class UrlButton implements KeyBoardButton {
public static final String TYPE = "URL";
private String label;
private String url;
private final String label;
private final String url;
public UrlButton(String label, String url) {
this.label = label;
this.url = url;
}
public static UrlButton buttonUrl(String label, String url) {
public static UrlButton urlButton(@NotNull String label, @NotNull String url) {
return new UrlButton(label, url);
}

View File

@ -1,6 +1,7 @@
package dev.struchkov.godfather.telegram.domain.keyboard.button;
import dev.struchkov.godfather.context.domain.keyboard.KeyBoardButton;
import org.jetbrains.annotations.NotNull;
public class WebAppButton implements KeyBoardButton {
@ -9,12 +10,12 @@ public class WebAppButton implements KeyBoardButton {
private final String label;
private final String url;
public WebAppButton(String label, String url) {
private WebAppButton(String label, String url) {
this.label = label;
this.url = url;
}
public static WebAppButton buttonWebApp(String label, String url) {
public static WebAppButton webAppButton(@NotNull String label, @NotNull String url) {
return new WebAppButton(label, url);
}

45
telegram-sender/pom.xml Normal file
View File

@ -0,0 +1,45 @@
<?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">
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.26</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>telegram-sender</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.haiti</groupId>
<artifactId>haiti-utils</artifactId>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -2,9 +2,11 @@ package dev.struchkov.godfather.telegram.service;
import dev.struchkov.godfather.context.domain.BoxAnswer;
import dev.struchkov.godfather.context.service.sender.SendType;
import dev.struchkov.godfather.context.service.sender.Sending;
import dev.struchkov.godfather.telegram.TelegramConnect;
import dev.struchkov.godfather.telegram.context.SenderStorageService;
import dev.struchkov.godfather.telegram.context.TelegramConnect;
import dev.struchkov.godfather.telegram.context.TelegramSending;
import dev.struchkov.godfather.telegram.domain.keyboard.InlineKeyBoard;
import dev.struchkov.godfather.telegram.utils.KeyBoardConvert;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -15,61 +17,82 @@ import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static dev.struchkov.godfather.telegram.utils.KeyBoardConvert.convertInlineKeyBoard;
import static dev.struchkov.godfather.telegram.utils.KeyBoardConvert.convertKeyBoard;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
import static dev.struchkov.haiti.utils.Inspector.isNotNull;
public class TelegramSender implements Sending {
public class TelegramSender implements TelegramSending {
private static final Logger log = LoggerFactory.getLogger(TelegramSender.class);
private static final String ERROR_REPLACE_MESSAGE = "Bad Request: message to edit not found";
private final AbsSender absSender;
private final Map<Long, Integer> lastMessageId = new HashMap<>();
private SendPreProcessing sendPreProcessing;
private SenderStorageService senderStorageService;
public TelegramSender(TelegramConnect telegramConnect) {
this.absSender = telegramConnect.getAdsSender();
this.absSender = telegramConnect.getAbsSender();
}
public TelegramSender(TelegramConnect telegramConnect, SenderStorageService senderStorageService) {
this.absSender = telegramConnect.getAbsSender();
this.senderStorageService = senderStorageService;
}
public void setSendPreProcessing(SendPreProcessing sendPreProcessing) {
this.sendPreProcessing = sendPreProcessing;
}
public void setSenderRepository(SenderStorageService senderStorageService) {
this.senderStorageService = senderStorageService;
}
public void send(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) {
sendBoxAnswer(telegramId, boxAnswer, true);
}
@Override
public void sendNotSave(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) {
sendBoxAnswer(telegramId, boxAnswer, false);
}
private void sendBoxAnswer(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
isNotNull(telegramId, boxAnswer);
try {
if (boxAnswer.isReplace() && lastMessageId.containsKey(telegramId)) {
replaceMessage(telegramId, boxAnswer);
if (boxAnswer.isReplace() && checkNotNull(senderStorageService)) {
final Optional<Integer> optLastId = senderStorageService.getLastSendMessage(telegramId);
if (optLastId.isPresent()) {
replaceMessage(telegramId, optLastId.get(), boxAnswer);
} else {
sendMessage(telegramId, boxAnswer, saveMessageId);
}
} else {
sendMessage(telegramId, boxAnswer);
sendMessage(telegramId, boxAnswer, saveMessageId);
}
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
if (ERROR_REPLACE_MESSAGE.equals(e.getApiResponse())) {
sendMessage(telegramId, boxAnswer);
sendMessage(telegramId, boxAnswer, saveMessageId);
}
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
}
private void replaceMessage(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) throws TelegramApiException {
private void replaceMessage(@NotNull Long telegramId, @NotNull Integer lastMessageId, @NotNull BoxAnswer boxAnswer) throws TelegramApiException {
final EditMessageText editMessageText = new EditMessageText();
editMessageText.setChatId(String.valueOf(telegramId));
editMessageText.setMessageId(lastMessageId.get(telegramId));
editMessageText.setMessageId(lastMessageId);
editMessageText.enableMarkdown(true);
editMessageText.setText(boxAnswer.getMessage());
editMessageText.setReplyMarkup(convertInlineKeyBoard((InlineKeyBoard) boxAnswer.getKeyBoard()));
editMessageText.setReplyMarkup(KeyBoardConvert.convertInlineKeyBoard((InlineKeyBoard) boxAnswer.getKeyBoard()));
absSender.execute(editMessageText);
}
private void sendMessage(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer) {
private void sendMessage(@NotNull Long telegramId, @NotNull BoxAnswer boxAnswer, boolean saveMessageId) {
final SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(String.valueOf(telegramId));
@ -78,10 +101,12 @@ public class TelegramSender implements Sending {
? sendPreProcessing.pretreatment(boxAnswer.getMessage())
: boxAnswer.getMessage()
);
sendMessage.setReplyMarkup(convertKeyBoard(boxAnswer.getKeyBoard()));
sendMessage.setReplyMarkup(KeyBoardConvert.convertKeyBoard(boxAnswer.getKeyBoard()));
try {
final Message execute = absSender.execute(sendMessage);
lastMessageId.put(telegramId, execute.getMessageId());
if (checkNotNull(senderStorageService) && saveMessageId) {
senderStorageService.saveLastSendMessage(telegramId, execute.getMessageId());
}
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {

View File

@ -24,6 +24,9 @@ import org.telegram.telegrambots.meta.api.objects.webapp.WebAppInfo;
import java.util.List;
import static dev.struchkov.haiti.context.exception.ConvertException.convertException;
import static dev.struchkov.haiti.utils.Inspector.isNull;
public final class KeyBoardConvert {
private KeyBoardConvert() {
@ -130,7 +133,7 @@ public final class KeyBoardConvert {
case SimpleButton.TYPE -> {
final SimpleButton simpleButton = (SimpleButton) keyBoardButton;
button.setText(simpleButton.getLabel());
Inspector.isNull(simpleButton.getCallbackData(), ConvertException.supplier("CallbackData поддерживает только Inline клавитаура"));
isNull(simpleButton.getCallbackData(), convertException("CallbackData поддерживает только Inline клавитаура"));
}
case WebAppButton.TYPE -> {
final WebAppButton webAppButton = (WebAppButton) keyBoardButton;

36
telegram/pom.xml Normal file
View File

@ -0,0 +1,36 @@
<?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">
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.26</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>telegram</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-sender</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>