FreelanceBot

Форк
0
165 строк · 6.1 Кб
1
package telegramBot.bot;
2

3

4
import org.telegram.telegrambots.meta.TelegramBotsApi;
5
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
6
import telegramBot.command.*;
7
import telegramBot.entity.Subscription;
8
import telegramBot.entity.User;
9
import telegramBot.enums.Language;
10
import telegramBot.messages.SubscriptionMessage;
11
import telegramBot.service.*;
12

13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.stereotype.Component;
15
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
16
import org.telegram.telegrambots.meta.api.objects.Update;
17
import telegramBot.util.BotUtil;
18
import telegramBot.validation.CommandValidation;
19

20
import java.util.*;
21

22

23
@Component
24
public class TelegramBot extends TelegramLongPollingBot {
25
    private final static Map<String, List<String>> commands = new HashMap<>();
26
    private static final String COMMAND_PREFIX = "/";
27
    private final CommandContainer commandContainer;
28

29
    private final MessageService messageService;
30

31
    @Autowired
32
    private CommandValidation validation;
33

34
    @Autowired
35
    private OrderService orderService;
36

37
    @Autowired
38
    private SubscriptionService subscriptionService;
39

40
    @Autowired
41
    private UserService userService;
42

43
    @Autowired
44
    public TelegramBot(TelegramBotsApi botsApi) throws TelegramApiException {
45
        botsApi.registerBot(this);
46
        this.messageService = new MessageService(this);
47
        this.commandContainer = new CommandContainer(this.messageService);
48
    }
49

50
    @Override
51
    public String getBotUsername() {
52
        return BotUtil.BOT_USERNAME;
53
    }
54

55
    @Override
56
    public String getBotToken() {
57
        return BotUtil.BOT_TOKEN;
58
    }
59

60
    @Override
61
    public void onUpdateReceived(Update update) {
62
        String inputCommand = "", chatId = "";
63
        User user;
64
        if (update.hasMessage() && update.getMessage().hasText()) {
65
            chatId = update.getMessage().getChatId().toString();
66
            user = userService.createOrGet(chatId);
67
            commands.putIfAbsent(chatId, new ArrayList<>());
68
            String message = update.getMessage().getText().trim();
69
            if(message.startsWith(COMMAND_PREFIX)){
70
                inputCommand = message.split(" ")[0].toLowerCase(Locale.ROOT);
71
                Command command = this.commandContainer.retrieveCommand(inputCommand);
72
                if(command instanceof SubscriptionCommand){
73
                    ((SubscriptionCommand) command)
74
                            .setUserService(this.userService)
75
                            .execute(update);
76
                }
77

78
                else if(command instanceof StopCommand){
79
                    ((StopCommand) command)
80
                            .setUserService(this.userService)
81
                            .execute(update);
82
                }
83

84
                else if(command instanceof RestartCommand){
85
                    ((RestartCommand) command)
86
                            .setUserService(this.userService)
87
                            .execute(update);
88
                }
89

90
                else {
91
                    command.execute(update);
92
                    commands.get(chatId).add(inputCommand);
93
                }
94
            }
95
            else {
96
                CommandName lastCommand = lastCommand(chatId);
97
                if(lastCommand.equals(CommandName.ADD)){
98
                    if(validation.addCommand(update)){
99
                        String value = update.getMessage().getText();
100
                        Language language = Language.ignoreCaseValueOf(value);
101
                        Subscription subscription = this.subscriptionService
102
                                .getByLanguage(language);
103
                        this.userService.addSubscription(user, subscription);
104
                        this.messageService.sendResponse(chatId, SubscriptionMessage.
105
                                getMessage(lastCommand));
106
                        clearCommands(chatId);
107
                    }
108
                }
109
                else if(lastCommand.equals(CommandName.REMOVE)){
110
                    if(validation.removeCommand(update)){
111
                        String value = update.getMessage().getText();
112
                        Language language = Language.ignoreCaseValueOf(value);
113
                        Subscription subscription = this.subscriptionService
114
                                .getByLanguage(language);
115
                        this.userService.removeSubscription(user, subscription);
116
                        this.messageService.sendResponse(chatId, SubscriptionMessage.
117
                                getMessage(lastCommand));
118
                        clearCommands(chatId);
119
                    }
120
                }
121
                else if(lastCommand.equals(CommandName.LATEST)){
122
                     if(validation.latestCommand(update)) {
123
                       String latestOrdersMessage = this.messageService
124
                               .getLatestOrdersMessage(update, this.orderService);
125
                       this.messageService.sendResponse(chatId, latestOrdersMessage);
126
                       clearCommands(chatId);
127
                     }
128
                }
129

130
                else if(unknownInput(chatId)){
131
                    this.commandContainer.retrieveCommand(CommandName.
132
                            UNKNOWN.getName()).execute(update);
133
                    clearCommands(chatId);
134
                }
135
            }
136

137
        }
138
    }
139

140

141

142

143

144
    private CommandName lastCommand(String chatId) {
145
        int size = commands.get(chatId).size();
146
        if (size == 0) return CommandName.UNKNOWN;
147
        int lastIndex = size - 1;
148
        String command = commands.get(chatId).get(lastIndex);
149
        return CommandName.commandValueOf(command);
150
    }
151

152
    public boolean unknownInput(String chatId) {
153
        if (commands.get(chatId).isEmpty()) return true;
154
        CommandName lastCommand = lastCommand(chatId);
155
        return !(lastCommand.equals(CommandName.ADD) ||
156
                lastCommand.equals(CommandName.REMOVE) ||
157
                lastCommand.equals(CommandName.LATEST));
158
    }
159

160
    private void clearCommands(String chatId){
161
        commands.get(chatId).clear();
162
    }
163

164

165
}
166

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.