├── .gitignore ├── FortuneWheel ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── example │ │ └── telegrambot │ │ └── App.java │ └── resources │ └── log4j2.xml ├── README.md ├── base.iml ├── base ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── example │ │ └── telegrambot │ │ ├── ability │ │ └── Stickers.java │ │ ├── bot │ │ └── Bot.java │ │ ├── command │ │ ├── Command.java │ │ ├── CommandElement.java │ │ └── impl │ │ │ └── CommandProvider.java │ │ ├── handler │ │ ├── AbstractHandler.java │ │ ├── DefaultHandler.java │ │ ├── EmojiHandler.java │ │ ├── HandlerService.java │ │ ├── SystemHandler.java │ │ └── impl │ │ │ └── HandlerImpl.java │ │ ├── parser │ │ ├── AnalyzeResult.java │ │ ├── MessageType.java │ │ ├── ParsedCommand.java │ │ ├── Parser.java │ │ ├── ParserService.java │ │ └── impl │ │ │ └── ParserImpl.java │ │ └── service │ │ ├── Constructed.java │ │ ├── MessageReceiver.java │ │ ├── MessageSender.java │ │ ├── MsgService.java │ │ └── QueueProvider.java │ └── test │ └── java │ └── com │ └── example │ └── telegrambot │ ├── AppTest.java │ ├── UpdateMock.java │ ├── command │ ├── CommandMock.java │ └── impl │ │ └── CommandProviderTest.java │ ├── handler │ └── impl │ │ └── HandlerImplTest.java │ ├── parser │ ├── ParserTest.java │ └── impl │ │ └── ParserImplTest.java │ └── service │ ├── MsgServiceTest.java │ └── MsgServiceUpdateTest.java ├── pom.xml └── sample-bot ├── pom.xml └── src └── main ├── java └── com │ └── example │ └── telegrambot │ ├── App.java │ ├── StartCommand.java │ └── StartHandler.java └── resources └── log4j2.xml /.gitignore: -------------------------------------------------------------------------------- 1 | # exclude binary files 2 | # extensions that come with pre-compiled /WEB-INF/classes directory will have local overrides 3 | *.class 4 | target/ 5 | classes/ 6 | 7 | #Idea 8 | .idea/ 9 | *.iml 10 | 11 | # Log file 12 | *.log 13 | 14 | # BlueJ files 15 | *.ctxt 16 | 17 | # Mobile Tools for Java (J2ME) 18 | .mtj.tmp/ 19 | 20 | # Package Files # 21 | *.jar 22 | *.war 23 | *.nar 24 | *.ear 25 | *.zip 26 | *.tar.gz 27 | *.rar 28 | 29 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 30 | hs_err_pid* 31 | -------------------------------------------------------------------------------- /FortuneWheel/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | telegramBotBase 9 | com.example.telegrambot 10 | 1.0-SNAPSHOT 11 | 12 | 13 | com.example.telegrambot 14 | FortuneWheel 15 | 1.0 16 | jar 17 | Fortune-wheel 18 | 19 | 20 | 8 21 | 8 22 | 23 | 24 | 25 | 26 | com.example.telegrambot 27 | base 28 | 1.0 29 | compile 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /FortuneWheel/src/main/java/com/example/telegrambot/App.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import com.example.telegrambot.bot.Bot; 4 | import com.example.telegrambot.parser.Parser; 5 | import com.example.telegrambot.service.MessageReceiver; 6 | import com.example.telegrambot.service.MessageSender; 7 | import com.example.telegrambot.service.MsgService; 8 | import com.example.telegrambot.service.QueueProvider; 9 | import org.apache.logging.log4j.LogManager; 10 | import org.apache.logging.log4j.Logger; 11 | import org.telegram.telegrambots.ApiContextInitializer; 12 | import org.telegram.telegrambots.api.methods.send.SendMessage; 13 | import org.telegram.telegrambots.generics.BotSession; 14 | 15 | public class App { 16 | private static final Logger log = LogManager.getLogger(App.class); 17 | private static final int PRIORITY_FOR_SENDER = 1; 18 | private static final int PRIORITY_FOR_RECEIVER = 3; 19 | private static final String BOT_ADMIN = "321644283"; 20 | 21 | public static void main(String[] args) { 22 | ApiContextInitializer.init(); 23 | String botName = System.getenv("test_bot_name"); 24 | String botToken = System.getenv("test_bot_token"); 25 | 26 | MsgService msgService = new MsgService(); 27 | QueueProvider queueProvider = new QueueProvider(); 28 | msgService.setQueueProvider(queueProvider); 29 | Parser parser = new Parser(botName); 30 | 31 | Bot test_habr_bot = new Bot(botName, botToken); 32 | test_habr_bot.setMsgService(msgService); 33 | 34 | MessageReceiver messageReceiver = new MessageReceiver(test_habr_bot, queueProvider); 35 | MessageSender messageSender = new MessageSender(test_habr_bot, queueProvider.getSendQueue()); 36 | 37 | BotSession connect = test_habr_bot.connect(); 38 | log.info("StartBotSession. Bot started. " + connect.toString()); 39 | 40 | Thread receiver = new Thread(messageReceiver); 41 | receiver.setDaemon(true); 42 | receiver.setName("MsgReciever"); 43 | receiver.setPriority(PRIORITY_FOR_RECEIVER); 44 | receiver.start(); 45 | 46 | Thread sender = new Thread(messageSender); 47 | sender.setDaemon(true); 48 | sender.setName("MsgSender"); 49 | sender.setPriority(PRIORITY_FOR_SENDER); 50 | sender.start(); 51 | 52 | sendStartReport(test_habr_bot); 53 | } 54 | 55 | private static void sendStartReport(Bot bot) { 56 | SendMessage sendMessage = new SendMessage(); 57 | sendMessage.setChatId(BOT_ADMIN); 58 | sendMessage.setText("Запустился"); 59 | bot.sendQueue.add(sendMessage); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /FortuneWheel/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TelegramBotBase 2 | 3 | Base for working Telegram Bot 4 | 5 | ## App.java 6 | Starts the bot on the specified parameters "bot name" and "token" 7 | 8 | ## Class Bot.java 9 | - Override basic methods of TelegramLongPollingBot. 10 | - implement command botConnect. Register selected bot in TelegramAPI 11 | - When receiving update only logged the event is not taking any action. 12 | 13 | ##Part2 14 | 15 | ### Handlers and Command 16 | - add special class for Command 17 | - add Parser for Command 18 | - add Handlers for Command 19 | 20 | ### Threads 21 | - Sender Thread 22 | - Receiver Thread 23 | - Sample of the operate command in a separate thread. Notify command and class -------------------------------------------------------------------------------- /base.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /base/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.example.telegrambot 8 | telegramBotBase 9 | 1.0-SNAPSHOT 10 | 11 | com.example.telegrambot 12 | base 13 | 1.0 14 | jar 15 | base 16 | 17 | 18 | 19 | UTF-8 20 | 21 | 22 | 23 | 24 | 25 | org.openjfx 26 | javafx-controls 27 | 17.0.1 28 | 29 | 30 | 31 | com.vdurmont 32 | emoji-java 33 | ${com.vdurmont.emoji-java.version} 34 | 35 | 36 | 37 | org.telegram 38 | telegrambots 39 | ${org.telegram.telegrambots.version} 40 | 41 | 42 | 43 | 44 | org.projectlombok 45 | lombok 46 | ${org.projectlombok.lombok.version} 47 | provided 48 | 49 | 50 | 51 | 52 | org.apache.logging.log4j 53 | log4j-api 54 | ${org.apache.logging.log4j.version} 55 | 56 | 57 | 58 | org.apache.logging.log4j 59 | log4j-core 60 | ${org.apache.logging.log4j.version} 61 | 62 | 63 | 64 | org.mockito 65 | mockito-core 66 | ${org.mockito.version} 67 | 68 | 69 | 70 | junit 71 | junit 72 | ${junit.version} 73 | test 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/ability/Stickers.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.ability; 2 | 3 | import org.telegram.telegrambots.api.methods.send.SendSticker; 4 | 5 | public enum Stickers { 6 | FUNNY_JIM_CARREY("CAADBQADiQMAAukKyAPZH7wCI2BwFxYE"), 7 | ; 8 | 9 | String stickerId; 10 | 11 | Stickers(String stickerId) { 12 | this.stickerId = stickerId; 13 | } 14 | 15 | public SendSticker getSendSticker(String chatId) { 16 | if ("".equals(chatId)) throw new IllegalArgumentException("ChatId cant be null"); 17 | SendSticker sendSticker = getSendSticker(); 18 | sendSticker.setChatId(chatId); 19 | return sendSticker; 20 | } 21 | 22 | public SendSticker getSendSticker() { 23 | SendSticker sendSticker = new SendSticker(); 24 | sendSticker.setSticker(stickerId); 25 | return sendSticker; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/bot/Bot.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.bot; 2 | 3 | import com.example.telegrambot.service.Constructed; 4 | import com.example.telegrambot.service.MsgService; 5 | import com.google.common.base.Strings; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | import org.apache.logging.log4j.LogManager; 9 | import org.apache.logging.log4j.Logger; 10 | import org.telegram.telegrambots.TelegramBotsApi; 11 | import org.telegram.telegrambots.api.objects.Update; 12 | import org.telegram.telegrambots.bots.TelegramLongPollingBot; 13 | import org.telegram.telegrambots.exceptions.TelegramApiRequestException; 14 | import org.telegram.telegrambots.generics.BotSession; 15 | 16 | import java.util.concurrent.BlockingQueue; 17 | import java.util.concurrent.LinkedBlockingQueue; 18 | 19 | @NoArgsConstructor 20 | public class Bot extends TelegramLongPollingBot implements Constructed { 21 | private static final Logger log = LogManager.getLogger(Bot.class); 22 | private final int RECONNECT_PAUSE = 10000; 23 | @Setter 24 | MsgService msgService; 25 | @Setter 26 | private String botName; 27 | 28 | @Setter 29 | private String botToken; 30 | 31 | @Override 32 | public final boolean isConstructed() { 33 | return !Strings.isNullOrEmpty(botName) && 34 | !Strings.isNullOrEmpty(botToken) && 35 | msgService != null; 36 | } 37 | 38 | public final BlockingQueue sendQueue = new LinkedBlockingQueue<>(); 39 | 40 | public Bot(String botName, String botToken) { 41 | this.botName = botName; 42 | this.botToken = botToken; 43 | log.info("Bot name: " + botName); 44 | } 45 | 46 | @Override 47 | public void onUpdateReceived(Update update) { 48 | msgService.acceptMessage(update); 49 | } 50 | 51 | @Override 52 | public String getBotUsername() { 53 | log.debug("Bot name: " + botName); 54 | return botName; 55 | } 56 | 57 | @Override 58 | public String getBotToken() { 59 | log.debug("Bot token: " + botToken); 60 | return botToken; 61 | } 62 | 63 | public BotSession connect() { 64 | TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); 65 | BotSession botSession = null; 66 | try { 67 | botSession = telegramBotsApi.registerBot(this); 68 | log.info("[STARTED] TelegramAPI. Bot Connected. Bot class: " + this); 69 | } catch (TelegramApiRequestException e) { 70 | log.error("Cant Connect. Pause " + RECONNECT_PAUSE / 1000 + "sec and try again. Error: " + e.getMessage()); 71 | try { 72 | Thread.sleep(RECONNECT_PAUSE); 73 | } catch (InterruptedException e1) { 74 | e1.printStackTrace(); 75 | return null; 76 | } 77 | connect(); 78 | } 79 | return botSession; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/command/Command.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.command; 2 | 3 | public enum Command { 4 | NONE, NOTFORME, 5 | 6 | NOTIFY, 7 | START, HELP, ID, 8 | TEXT_CONTAIN_EMOJI, 9 | STICKER, 10 | 11 | // for tests 12 | TESTDESCRIPTION, 13 | } 14 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/command/CommandElement.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.command; 2 | 3 | public interface CommandElement { 4 | String command(); 5 | 6 | boolean isInTextCommand(); 7 | } 8 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/command/impl/CommandProvider.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.command.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | 5 | public enum CommandProvider implements CommandElement { 6 | START, HELP, 7 | INTEXTCOMMAND("in text command",true); 8 | ; 9 | String command; 10 | boolean inText; 11 | 12 | CommandProvider() { 13 | command = this.toString().toLowerCase(); 14 | } 15 | 16 | CommandProvider(String command, boolean inText) { 17 | this.inText = inText; 18 | this.command = command; 19 | } 20 | 21 | @Override 22 | public String command() { 23 | return command; 24 | } 25 | 26 | @Override 27 | public boolean isInTextCommand() { 28 | return inText; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/AbstractHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler; 2 | 3 | import com.example.telegrambot.bot.Bot; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import com.example.telegrambot.parser.ParsedCommand; 6 | import com.example.telegrambot.service.MsgService; 7 | import lombok.Setter; 8 | import org.telegram.telegrambots.api.objects.Update; 9 | 10 | public abstract class AbstractHandler { 11 | @Setter 12 | protected Bot bot; 13 | @Setter 14 | protected MsgService msgService; 15 | 16 | 17 | public final boolean isConstructed() { 18 | return bot != null && 19 | msgService != null; 20 | 21 | } 22 | 23 | public abstract String operate(String chatId, ParsedCommand parsedCommand, Update update); 24 | 25 | public abstract String operate(AnalyzeResult analyzeResult); 26 | } 27 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/DefaultHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler; 2 | 3 | import com.example.telegrambot.parser.AnalyzeResult; 4 | import com.example.telegrambot.parser.ParsedCommand; 5 | import org.apache.logging.log4j.LogManager; 6 | import org.apache.logging.log4j.Logger; 7 | import org.telegram.telegrambots.api.objects.Update; 8 | 9 | public class DefaultHandler extends AbstractHandler { 10 | private static final Logger log = LogManager.getLogger(DefaultHandler.class); 11 | 12 | @Override 13 | public String operate(String chatId, ParsedCommand parsedCommand, Update update) { 14 | return ""; 15 | } 16 | 17 | @Override 18 | public String operate(AnalyzeResult analyzeResult) { 19 | return ""; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/EmojiHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler; 2 | 3 | import com.example.telegrambot.parser.AnalyzeResult; 4 | import com.example.telegrambot.parser.ParsedCommand; 5 | import com.vdurmont.emoji.Emoji; 6 | import com.vdurmont.emoji.EmojiManager; 7 | import com.vdurmont.emoji.EmojiParser; 8 | import org.apache.logging.log4j.LogManager; 9 | import org.apache.logging.log4j.Logger; 10 | import org.telegram.telegrambots.api.objects.Update; 11 | 12 | import java.util.HashSet; 13 | import java.util.Set; 14 | 15 | public class EmojiHandler extends AbstractHandler { 16 | private static final Logger log = LogManager.getLogger(EmojiHandler.class); 17 | 18 | @Override 19 | public String operate(String chatId, ParsedCommand parsedCommand, Update update) { 20 | String text = parsedCommand.getText(); 21 | StringBuilder result = new StringBuilder(); 22 | Set emojisInTextUnique = new HashSet<>(EmojiParser.extractEmojis(text)); 23 | if (emojisInTextUnique.size() > 0) result.append("Parsed emojies from message:").append("\n"); 24 | for (String emojiUnicode : emojisInTextUnique) { 25 | Emoji byUnicode = EmojiManager.getByUnicode(emojiUnicode); 26 | log.debug(byUnicode.toString()); 27 | String emoji = byUnicode.getUnicode() + " " + 28 | byUnicode.getAliases() + 29 | " " + byUnicode.getDescription(); 30 | result.append(emoji).append("\n"); 31 | } 32 | return result.toString(); 33 | } 34 | 35 | @Override 36 | public String operate(AnalyzeResult analyzeResult) { 37 | return null; 38 | } 39 | } -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/HandlerService.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.service.Constructed; 5 | 6 | public interface HandlerService extends Constructed { 7 | AbstractHandler getHandler(CommandElement command); 8 | 9 | @Override 10 | boolean isConstructed(); 11 | } 12 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/SystemHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler; 2 | 3 | import com.example.telegrambot.command.Command; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import com.example.telegrambot.parser.ParsedCommand; 6 | import org.apache.logging.log4j.LogManager; 7 | import org.apache.logging.log4j.Logger; 8 | import org.telegram.telegrambots.api.methods.send.SendMessage; 9 | import org.telegram.telegrambots.api.objects.Update; 10 | 11 | public class SystemHandler extends AbstractHandler { 12 | private static final Logger log = LogManager.getLogger(SystemHandler.class); 13 | private final String END_LINE = "\n"; 14 | 15 | @Override 16 | public String operate(String chatId, ParsedCommand parsedCommand, Update update) { 17 | Command command = parsedCommand.getCommand(); 18 | 19 | switch (command) { 20 | case START: 21 | bot.sendQueue.add(getMessageStart(chatId)); 22 | break; 23 | case HELP: 24 | bot.sendQueue.add(getMessageHelp(chatId)); 25 | break; 26 | case ID: 27 | return "Your telegramID: " + update.getMessage().getFrom().getId(); 28 | case STICKER: 29 | return "StickerID: " + parsedCommand.getText(); 30 | } 31 | return ""; 32 | } 33 | 34 | @Override 35 | public String operate(AnalyzeResult analyzeResult) { 36 | return null; 37 | } 38 | 39 | private SendMessage getMessageHelp(String chatID) { 40 | SendMessage sendMessage = new SendMessage(); 41 | sendMessage.setChatId(chatID); 42 | sendMessage.enableMarkdown(true); 43 | 44 | StringBuilder text = new StringBuilder(); 45 | text.append("*This is help message*").append(END_LINE).append(END_LINE); 46 | text.append("[/start](/start) - show start message").append(END_LINE); 47 | text.append("[/help](/help) - show help message").append(END_LINE); 48 | text.append("[/id](/id) - know your ID in telegram ").append(END_LINE); 49 | text.append("/*notify* _time-in-sec_ - receive notification from me after the specified time").append(END_LINE); 50 | 51 | sendMessage.setText(text.toString()); 52 | return sendMessage; 53 | } 54 | 55 | private SendMessage getMessageStart(String chatID) { 56 | SendMessage sendMessage = new SendMessage(); 57 | sendMessage.setChatId(chatID); 58 | sendMessage.enableMarkdown(true); 59 | StringBuilder text = new StringBuilder(); 60 | text.append("Hello. I'm *").append(bot.getBotUsername()).append("*").append(END_LINE); 61 | text.append("I created specifically for resource habr.ru").append(END_LINE); 62 | text.append("All that I can do - you can see calling the command [/help](/help)"); 63 | sendMessage.setText(text.toString()); 64 | return sendMessage; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/handler/impl/HandlerImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.handler.AbstractHandler; 5 | import com.example.telegrambot.handler.HandlerService; 6 | 7 | import javax.validation.constraints.NotNull; 8 | import java.util.Map; 9 | 10 | public class HandlerImpl implements HandlerService { 11 | 12 | private final Map> links; 13 | 14 | public HandlerImpl(@NotNull Map> links) { 15 | this.links = links; 16 | } 17 | 18 | @Override 19 | public boolean isConstructed() { 20 | return links != null && links.size() != 0; 21 | } 22 | 23 | 24 | @Override 25 | public AbstractHandler getHandler(@NotNull CommandElement command) { 26 | if (links.containsKey(command)) { 27 | Class handlerClass = links.get(command); 28 | try { 29 | return handlerClass.newInstance(); 30 | } catch (InstantiationException | IllegalAccessException e) { 31 | throw new RuntimeException(e); 32 | } 33 | } else { 34 | throw new IllegalArgumentException("Handler not found for command{" + command.toString()); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/AnalyzeResult.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | import org.telegram.telegrambots.api.objects.Update; 7 | 8 | import java.util.List; 9 | 10 | @Getter 11 | public class AnalyzeResult { 12 | 13 | private Update update; 14 | @Setter 15 | private MessageType messageType; 16 | 17 | @Setter 18 | private List commands; 19 | 20 | public AnalyzeResult(Update update) { 21 | this.update = update; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | public enum MessageType { 4 | MESSAGE, 5 | } 6 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/ParsedCommand.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | import com.example.telegrambot.command.Command; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | @Getter 10 | @Setter 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class ParsedCommand { 14 | Command command = Command.NONE; 15 | String text=""; 16 | } 17 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/Parser.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | import com.example.telegrambot.command.Command; 4 | import javafx.util.Pair; 5 | import org.apache.logging.log4j.LogManager; 6 | import org.apache.logging.log4j.Logger; 7 | 8 | public class Parser { 9 | private static final Logger log = LogManager.getLogger(Parser.class); 10 | private final String PREFIX_FOR_COMMAND = "/"; 11 | private final String DELIMITER_COMMAND_BOTNAME = "@"; 12 | private String botName; 13 | 14 | public Parser(String botName) { 15 | this.botName = botName; 16 | } 17 | 18 | public ParsedCommand getParsedCommand(String text) { 19 | String trimText = ""; 20 | if (text != null) trimText = text.trim(); 21 | ParsedCommand result = new ParsedCommand(Command.NONE, trimText); 22 | 23 | if ("".equals(trimText)) return result; 24 | Pair commandAndText = getDelimitedCommandFromText(trimText); 25 | if (isCommand(commandAndText.getKey())) { 26 | if (isCommandForMe(commandAndText.getKey())) { 27 | String commandForParse = cutCommandFromFullText(commandAndText.getKey()); 28 | Command commandFromText = getCommandFromText(commandForParse); 29 | result.setText(commandAndText.getValue()); 30 | result.setCommand(commandFromText); 31 | } else { 32 | result.setCommand(Command.NOTFORME); 33 | result.setText(commandAndText.getValue()); 34 | } 35 | 36 | } 37 | return result; 38 | } 39 | 40 | private String cutCommandFromFullText(String text) { 41 | return text.contains(DELIMITER_COMMAND_BOTNAME) ? 42 | text.substring(1, text.indexOf(DELIMITER_COMMAND_BOTNAME)) : 43 | text.substring(1); 44 | } 45 | 46 | private Command getCommandFromText(String text) { 47 | String upperCaseText = text.toUpperCase().trim(); 48 | Command command = Command.NONE; 49 | try { 50 | command = Command.valueOf(upperCaseText); 51 | } catch (IllegalArgumentException e) { 52 | log.debug("Can't parse command: " + text); 53 | } 54 | return command; 55 | } 56 | 57 | private Pair getDelimitedCommandFromText(String trimText) { 58 | Pair commandText; 59 | 60 | if (trimText.contains(" ") || trimText.contains("\n")) { 61 | int indexOfSpace = trimText.indexOf(" "); 62 | int indexOfNewLine = trimText.indexOf("\n"); 63 | int indexOfCommandEnd; 64 | if (indexOfNewLine != -1 && indexOfSpace != -1) 65 | indexOfCommandEnd = indexOfNewLine < indexOfSpace ? indexOfNewLine : indexOfSpace; 66 | else if (indexOfNewLine != -1) indexOfCommandEnd = indexOfNewLine; 67 | else indexOfCommandEnd = indexOfSpace; 68 | 69 | commandText = new Pair<>(trimText.substring(0, indexOfCommandEnd), trimText.substring(indexOfCommandEnd + 1)); 70 | } else commandText = new Pair<>(trimText, ""); 71 | return commandText; 72 | } 73 | 74 | private boolean isCommandForMe(String command) { 75 | if (command.contains(DELIMITER_COMMAND_BOTNAME)) { 76 | String botNameForEqual = command.substring(command.indexOf(DELIMITER_COMMAND_BOTNAME) + 1); 77 | return botName.equals(botNameForEqual); 78 | } 79 | return true; 80 | } 81 | 82 | private boolean isCommand(String text) { 83 | return text.startsWith(PREFIX_FOR_COMMAND); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/ParserService.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.service.Constructed; 5 | import org.telegram.telegrambots.api.objects.Update; 6 | 7 | import java.util.List; 8 | 9 | public interface ParserService extends Constructed { 10 | void setBotName(String botName); 11 | 12 | void setCommands(List commands); 13 | 14 | AnalyzeResult getUpdateAnalyse(Update update); 15 | 16 | @Override 17 | boolean isConstructed(); 18 | } 19 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/parser/impl/ParserImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import com.example.telegrambot.parser.MessageType; 6 | import com.example.telegrambot.parser.ParserService; 7 | import com.example.telegrambot.service.MsgService; 8 | import com.google.common.base.Strings; 9 | import org.apache.logging.log4j.LogManager; 10 | import org.apache.logging.log4j.Logger; 11 | import org.telegram.telegrambots.api.objects.Update; 12 | 13 | import java.util.ArrayList; 14 | import java.util.Collections; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | public class ParserImpl implements ParserService { 19 | private static final Logger log = LogManager.getLogger(ParserService.class); 20 | private final String DELIMITER_COMMAND_BOTNAME = "@"; 21 | private final MsgService msgService = new MsgService(); 22 | 23 | private String botName; 24 | private List commands; 25 | 26 | @Override 27 | public boolean isConstructed() { 28 | if (Strings.isNullOrEmpty(botName)) return false; 29 | return commands != null && commands.size() != 0; 30 | } 31 | 32 | @Override 33 | public void setBotName(String botName) { 34 | this.botName = botName; 35 | } 36 | 37 | @Override 38 | public void setCommands(List commands) { 39 | this.commands = commands; 40 | } 41 | 42 | @Override 43 | public AnalyzeResult getUpdateAnalyse(Update update) { 44 | AnalyzeResult result = prepareClearAnalyzeResult(update); 45 | 46 | try { 47 | result.setMessageType(getMessageType(update)); 48 | 49 | switch (result.getMessageType()) { 50 | case MESSAGE: 51 | String messageText = msgService.getMessageText(result); 52 | List detectedCommands = getCommandsFromText(messageText); 53 | result.setCommands(detectedCommands); 54 | break; 55 | } 56 | } catch (Exception e) { 57 | log.error("Something goes wrong:{" + e.getMessage() + "} " + update.toString(), e); 58 | } 59 | 60 | return result; 61 | } 62 | 63 | private List getCommandsFromText(String text) { 64 | List result = new ArrayList<>(); 65 | 66 | String preparedText = prepareText(text); 67 | if (isCommand(preparedText)) { 68 | Map.Entry commandAndText = msgService.parseBotCommandAndTextFromFullText(preparedText); 69 | if (isCommandForMe(commandAndText.getKey())) { 70 | String command = cutCommandFromFullText(commandAndText.getKey()); 71 | commands.stream() 72 | .filter(element -> !element.isInTextCommand()) 73 | .forEach(element -> { 74 | if (getNormalize(element.command()).equals(getNormalize(command))) result.add(element); 75 | }); 76 | } 77 | } else { 78 | commands.stream() 79 | .filter(CommandElement::isInTextCommand) 80 | .forEach(element -> { 81 | if (preparedText.equals(element.command()) || msgService.contains(element.command(), preparedText)) { 82 | result.add(element); 83 | } 84 | }); 85 | } 86 | return result; 87 | } 88 | 89 | private static String getNormalize(String element) { 90 | return element.toLowerCase(); 91 | } 92 | 93 | private String prepareText(String text) { 94 | return text 95 | .trim() 96 | .toLowerCase(); 97 | } 98 | 99 | private String cutCommandFromFullText(String text) { 100 | return text.contains(DELIMITER_COMMAND_BOTNAME) ? 101 | text.substring(1, text.indexOf(DELIMITER_COMMAND_BOTNAME)) : 102 | text.substring(1); 103 | } 104 | 105 | private boolean isCommand(String text) { 106 | return text.startsWith(MsgService.PREFIX_FOR_COMMAND); 107 | } 108 | 109 | private boolean isCommandForMe(String text) { 110 | if (text.contains(DELIMITER_COMMAND_BOTNAME)) { 111 | String botNameForEqual = text.substring(text.indexOf(DELIMITER_COMMAND_BOTNAME) + 1); 112 | return botName.equals(botNameForEqual); 113 | } 114 | return true; 115 | } 116 | 117 | private AnalyzeResult prepareClearAnalyzeResult(Update update) { 118 | AnalyzeResult result = new AnalyzeResult(update); 119 | result.setCommands(Collections.EMPTY_LIST); 120 | return result; 121 | } 122 | 123 | private MessageType getMessageType(Update update) { 124 | return msgService.getMessageType(update); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/service/Constructed.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | public interface Constructed { 4 | boolean isConstructed(); 5 | } 6 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/service/MessageReceiver.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import com.example.telegrambot.bot.Bot; 4 | import com.example.telegrambot.handler.AbstractHandler; 5 | import com.example.telegrambot.handler.HandlerService; 6 | import com.example.telegrambot.parser.AnalyzeResult; 7 | import com.example.telegrambot.parser.ParserService; 8 | import lombok.Setter; 9 | import org.apache.logging.log4j.LogManager; 10 | import org.apache.logging.log4j.Logger; 11 | import org.telegram.telegrambots.api.objects.Update; 12 | 13 | import java.util.concurrent.BlockingQueue; 14 | 15 | 16 | public class MessageReceiver implements Runnable, Constructed { 17 | private static final Logger log = LogManager.getLogger(MessageReceiver.class); 18 | private final Bot bot; 19 | private QueueProvider queueProvider; 20 | 21 | @Setter 22 | private ParserService parserService; 23 | 24 | @Setter 25 | private HandlerService handlerService; 26 | 27 | @Setter 28 | private MsgService msgService; 29 | 30 | public MessageReceiver(Bot bot, QueueProvider queueProvider) { 31 | this.bot = bot; 32 | this.queueProvider = queueProvider; 33 | } 34 | 35 | @Override 36 | public boolean isConstructed() { 37 | return bot != null && 38 | queueProvider != null && 39 | parserService != null && 40 | handlerService != null && 41 | msgService != null; 42 | } 43 | 44 | @Override 45 | public void run() { 46 | log.info("[STARTED] MsgReceiver. Bot class: " + bot); 47 | BlockingQueue receiveQueue = queueProvider.getReceiveQueue(); 48 | while (true) { 49 | try { 50 | Object object = receiveQueue.take(); 51 | log.debug("New object for analyze in queue " + object); 52 | analyze(object); 53 | } catch (InterruptedException e) { 54 | log.error("Catch interrupt. Exit", e); 55 | return; 56 | } catch (Exception e) { 57 | log.error("Exception in Receiver. ", e); 58 | } 59 | } 60 | } 61 | 62 | private void analyze(Object object) { 63 | if (object instanceof Update) { 64 | Update update = (Update) object; 65 | log.debug("Update received: " + update); 66 | analyzeUpdate(update); 67 | } else log.warn("Cant operate type of object: " + object.toString()); 68 | } 69 | 70 | private void analyzeUpdate(Update update) { 71 | AnalyzeResult analyze = parserService.getUpdateAnalyse(update); 72 | analyze.getCommands().forEach(command -> { 73 | AbstractHandler handler = handlerService.getHandler(command); 74 | handler.setBot(bot); 75 | handler.setMsgService(msgService); 76 | if (handler.isConstructed()) { 77 | // результат работы хендлера никуда отправлять не будем. 78 | handler.operate(analyze); 79 | } else { 80 | handlerNotConstructed(handler); 81 | } 82 | }); 83 | } 84 | 85 | private void handlerNotConstructed(AbstractHandler handler) { 86 | log.error("Not constructed handler: " + handler); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/service/MessageSender.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import com.example.telegrambot.bot.Bot; 4 | import org.apache.logging.log4j.LogManager; 5 | import org.apache.logging.log4j.Logger; 6 | import org.telegram.telegrambots.api.methods.BotApiMethod; 7 | import org.telegram.telegrambots.api.methods.send.SendSticker; 8 | import org.telegram.telegrambots.api.objects.Message; 9 | 10 | import java.util.concurrent.BlockingQueue; 11 | 12 | public class MessageSender implements Runnable, Constructed { 13 | private static final Logger log = LogManager.getLogger(MessageSender.class); 14 | private final Bot bot; 15 | 16 | private final BlockingQueue sendQueue; 17 | 18 | public MessageSender(Bot bot, BlockingQueue sendQueue) { 19 | this.bot = bot; 20 | this.sendQueue = sendQueue; 21 | } 22 | 23 | @Override 24 | public boolean isConstructed() { 25 | return bot != null && 26 | sendQueue != null; 27 | } 28 | 29 | @Override 30 | public void run() { 31 | log.info("[STARTED] MsgSender. Bot class: " + bot); 32 | while (true) { 33 | try { 34 | Object object = sendQueue.take(); 35 | log.debug("Get new msg to send " + object); 36 | send(object); 37 | } catch (InterruptedException e) { 38 | log.error("Take interrupt while operate msg list", e); 39 | return; 40 | } catch (Exception e) { 41 | log.error(e); 42 | } 43 | } 44 | } 45 | 46 | private void send(Object object) { 47 | try { 48 | MessageType messageType = messageType(object); 49 | switch (messageType) { 50 | case EXECUTE: 51 | BotApiMethod message = (BotApiMethod) object; 52 | log.debug("Use Execute for " + object); 53 | bot.execute(message); 54 | break; 55 | case STICKER: 56 | SendSticker sendSticker = (SendSticker) object; 57 | log.debug("Use SendSticker for " + object); 58 | bot.sendSticker(sendSticker); 59 | break; 60 | default: 61 | log.warn("Cant detect type of object. " + object); 62 | } 63 | } catch (Exception e) { 64 | log.error(e.getMessage(), e); 65 | } 66 | } 67 | 68 | private MessageType messageType(Object object) { 69 | if (object instanceof SendSticker) return MessageType.STICKER; 70 | if (object instanceof BotApiMethod) return MessageType.EXECUTE; 71 | return MessageType.NOT_DETECTED; 72 | } 73 | 74 | enum MessageType { 75 | EXECUTE, STICKER, NOT_DETECTED, 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/service/MsgService.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import com.example.telegrambot.parser.AnalyzeResult; 4 | import com.example.telegrambot.parser.MessageType; 5 | import com.google.common.base.Strings; 6 | import lombok.Setter; 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | import org.telegram.telegrambots.api.methods.send.SendMessage; 10 | import org.telegram.telegrambots.api.objects.Message; 11 | import org.telegram.telegrambots.api.objects.Update; 12 | 13 | import java.util.AbstractMap; 14 | import java.util.Map; 15 | import java.util.concurrent.BlockingQueue; 16 | 17 | public class MsgService implements Constructed { 18 | private static final Logger log = LogManager.getLogger(MsgService.class); 19 | public static final String END_LINE = "\n"; 20 | public static final String PREFIX_FOR_COMMAND = "/"; 21 | 22 | @Setter 23 | QueueProvider queueProvider; 24 | 25 | @Override 26 | public boolean isConstructed() { 27 | return queueProvider != null; 28 | } 29 | 30 | public final void acceptMessage(Update update) { 31 | BlockingQueue queue = queueProvider.getReceiveQueue(); 32 | queue.add(update); 33 | log.debug("Receive new Update. Queue size: " + queue.size() + " updateID: " + update.getUpdateId()); 34 | } 35 | 36 | public MessageType getMessageType(Update update) { 37 | if (update.hasMessage()) return MessageType.MESSAGE; 38 | throw new IllegalStateException("Can't detect message type"); 39 | } 40 | 41 | // todo test me 42 | public String getMessageText(AnalyzeResult analyzeResult) { 43 | switch (analyzeResult.getMessageType()) { 44 | case MESSAGE: 45 | Message message = analyzeResult.getUpdate().getMessage(); 46 | if (message.hasText()) return message.getText(); 47 | break; 48 | } 49 | throw new IllegalStateException("Can't get message text"); 50 | } 51 | 52 | //todo Test me 53 | public String getChatId(AnalyzeResult analyzeResult) { 54 | switch (analyzeResult.getMessageType()) { 55 | case MESSAGE: 56 | Message message = analyzeResult.getUpdate().getMessage(); 57 | if (message.hasText()) return Long.toString(message.getChatId()); 58 | break; 59 | } 60 | throw new IllegalStateException("Can't get message id"); 61 | } 62 | 63 | // todo test me 64 | public Map.Entry parseBotCommandAndTextFromFullText(String text) { 65 | Map.Entry commandText; 66 | 67 | if (text.contains(" ") || text.contains(END_LINE)) { 68 | int indexOfSpace = text.indexOf(" "); 69 | int indexOfNewLine = text.indexOf(END_LINE); 70 | int indexOfCommandEnd; 71 | if (indexOfNewLine != -1 && indexOfSpace != -1) 72 | indexOfCommandEnd = Math.min(indexOfNewLine, indexOfSpace); 73 | else if (indexOfNewLine != -1) indexOfCommandEnd = indexOfNewLine; 74 | else indexOfCommandEnd = indexOfSpace; 75 | 76 | commandText = new AbstractMap.SimpleImmutableEntry<>(text.substring(0, indexOfCommandEnd), text.substring(indexOfCommandEnd + 1)); 77 | } else commandText = new AbstractMap.SimpleImmutableEntry<>(text, ""); 78 | return commandText; 79 | } 80 | 81 | public boolean contains(String find, String where) { 82 | if (Strings.isNullOrEmpty(find) || Strings.isNullOrEmpty(where)) return false; 83 | if (find.split("\\w+").length == find.length()) return false; 84 | return transformString(where) 85 | .contains 86 | (transformString(find)); 87 | } 88 | 89 | private String transformString(String where) { 90 | String mask = "!.f&?"; 91 | String[] split = where.split("\\W+"); 92 | StringBuilder stringBuilder = new StringBuilder(); 93 | for (String word : split) { 94 | stringBuilder 95 | .append(mask) 96 | .append(word) 97 | .append(mask); 98 | } 99 | return stringBuilder.toString(); 100 | } 101 | 102 | public void sendMessage(SendMessage message) { 103 | try { 104 | queueProvider.getSendQueue().put(message); 105 | } catch (InterruptedException e) { 106 | throw new RuntimeException(e); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /base/src/main/java/com/example/telegrambot/service/QueueProvider.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import lombok.Getter; 4 | 5 | import java.util.concurrent.BlockingQueue; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | 8 | @Getter 9 | public class QueueProvider implements Constructed { 10 | private final BlockingQueue sendQueue; 11 | private final BlockingQueue receiveQueue; 12 | 13 | public QueueProvider() { 14 | sendQueue = new LinkedBlockingQueue<>(); 15 | receiveQueue = new LinkedBlockingQueue<>(); 16 | } 17 | 18 | @Override 19 | public boolean isConstructed() { 20 | return sendQueue != null && receiveQueue != null; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/UpdateMock.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import org.telegram.telegrambots.api.objects.Message; 4 | import org.telegram.telegrambots.api.objects.Update; 5 | import org.telegram.telegrambots.api.objects.User; 6 | 7 | import static org.mockito.Mockito.mock; 8 | import static org.mockito.Mockito.when; 9 | 10 | public class UpdateMock { 11 | protected Update update; 12 | protected User user; 13 | protected Message message; 14 | 15 | protected void clearSetup() { 16 | update = mock(Update.class); 17 | user = mock(User.class); 18 | message = mock(Message.class); 19 | } 20 | 21 | protected void tuneMessage(User user, String messageText, long chatId) { 22 | when(message.getFrom()).thenReturn(user); 23 | when(message.getText()).thenReturn(messageText); 24 | when(message.hasText()).thenReturn(true); 25 | when(message.getChatId()).thenReturn(chatId); 26 | } 27 | 28 | protected void tuneUser(String username, int userid) { 29 | when(user.getBot()).thenReturn(false); 30 | when(user.getUserName()).thenReturn(username); 31 | when(user.getId()).thenReturn(userid); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/command/CommandMock.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.command; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | 5 | public enum CommandMock implements CommandElement { 6 | 7 | START("start", false), 8 | HELP("help", false), 9 | INTEXT("in text command", true); 10 | 11 | final String command; 12 | final boolean inText; 13 | 14 | CommandMock(String command, boolean inText) { 15 | this.command = command; 16 | this.inText = inText; 17 | } 18 | 19 | @Override 20 | public String command() { 21 | return command; 22 | } 23 | 24 | @Override 25 | public boolean isInTextCommand() { 26 | return inText; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/command/impl/CommandProviderTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.command.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import org.junit.Test; 5 | 6 | import static com.example.telegrambot.command.impl.CommandProvider.*; 7 | import static org.junit.Assert.*; 8 | 9 | public class CommandProviderTest { 10 | CommandElement command; 11 | 12 | @Test 13 | public void commandTest_case_Start() { 14 | command = START; 15 | assertEquals("start", command.command()); 16 | assertFalse(command.isInTextCommand()); 17 | } 18 | 19 | @Test 20 | public void commandTest_case_Help() { 21 | command = HELP; 22 | assertEquals("help", command.command()); 23 | assertFalse(HELP.isInTextCommand()); 24 | } 25 | @Test 26 | public void commandTest_case_InTextCommand() { 27 | command = INTEXTCOMMAND; 28 | assertEquals("in text command", command.command()); 29 | assertTrue(command.isInTextCommand()); 30 | } 31 | } -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/handler/impl/HandlerImplTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.handler.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.handler.AbstractHandler; 5 | import com.example.telegrambot.handler.DefaultHandler; 6 | import com.example.telegrambot.handler.HandlerService; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | import static com.example.telegrambot.command.CommandMock.HELP; 14 | import static com.example.telegrambot.command.CommandMock.START; 15 | import static org.junit.Assert.assertEquals; 16 | import static org.junit.Assert.assertTrue; 17 | 18 | public class HandlerImplTest { 19 | HandlerService handlerService; 20 | 21 | @Before 22 | public void setUp() { 23 | Map> links = new HashMap<>(); 24 | links.put(START, DefaultHandler.class); 25 | handlerService = new HandlerImpl(links); 26 | } 27 | 28 | @Test 29 | public void shouldGetCorrectHHandler_forCommand_Start() { 30 | AbstractHandler handler = handlerService.getHandler(START); 31 | assertEquals(DefaultHandler.class, handler.getClass()); 32 | } 33 | 34 | @Test(expected = IllegalArgumentException.class) 35 | public void shouldThrowException() { 36 | AbstractHandler handler = handlerService.getHandler(HELP); 37 | assertTrue(true); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/parser/ParserTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser; 2 | 3 | import com.example.telegrambot.command.Command; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import static org.junit.Assert.assertEquals; 8 | 9 | public class ParserTest { 10 | private static final String botName = "bot"; 11 | private Parser parser; 12 | 13 | @Before 14 | public void setParser() { 15 | parser = new Parser(botName); 16 | } 17 | 18 | @Test 19 | public void getParsedCommand_TestDescription() { 20 | String text = "/testdescription\ntext"; 21 | ParsedCommand parsedCommandAndText = parser.getParsedCommand(text); 22 | assertEquals(Command.TESTDESCRIPTION, parsedCommandAndText.command); 23 | assertEquals("text", parsedCommandAndText.text); 24 | } 25 | 26 | @Test 27 | public void getParsedCommand_None() { 28 | String text = "just text"; 29 | ParsedCommand parsedCommandAndText = parser.getParsedCommand(text); 30 | assertEquals(Command.NONE, parsedCommandAndText.command); 31 | assertEquals(text, parsedCommandAndText.text); 32 | } 33 | 34 | @Test 35 | public void getParsedCommand_NotForMe() { 36 | String text = "/test@another_Bot just text"; 37 | ParsedCommand parsedCommandAndText = parser.getParsedCommand(text); 38 | assertEquals(Command.NOTFORME, parsedCommandAndText.command); 39 | } 40 | 41 | @Test 42 | public void getParsedCommand_NoneButForMe() { 43 | String text = "/test@" + botName + " just text"; 44 | ParsedCommand parsedCommandAndText = parser.getParsedCommand(text); 45 | assertEquals(Command.NONE, parsedCommandAndText.command); 46 | assertEquals("just text", parsedCommandAndText.text); 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/parser/impl/ParserImplTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.parser.impl; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import com.example.telegrambot.parser.ParserService; 6 | import com.example.telegrambot.service.Constructed; 7 | import com.example.telegrambot.service.MsgService; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.mockito.Mockito; 11 | import org.telegram.telegrambots.api.objects.Message; 12 | import org.telegram.telegrambots.api.objects.Update; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | import static com.example.telegrambot.command.CommandMock.*; 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertTrue; 20 | 21 | public class ParserImplTest { 22 | private static final String BOTNAME = "botname"; 23 | private static final String WRONG_BOTNAME = "wrongBotname"; 24 | Update update; 25 | Message message; 26 | 27 | ParserService parser; 28 | 29 | @Before 30 | public void setup() { 31 | update = Mockito.mock(Update.class); 32 | message = Mockito.mock(Message.class); 33 | Mockito.when(update.hasMessage()).thenReturn(true); 34 | Mockito.when(update.getMessage()).thenReturn(message); 35 | Mockito.when(message.hasText()).thenReturn(true); 36 | 37 | parser = new ParserImpl(); 38 | parser.setBotName(BOTNAME); 39 | parser.setCommands(getCommands()); 40 | } 41 | 42 | @Test 43 | public void shouldBeConstructed() { 44 | assertTrue(((Constructed) parser).isConstructed()); 45 | } 46 | 47 | @Test 48 | public void shouldRecognize_INTEXT_clear_case1() { 49 | mockMessageText("/start"); 50 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 51 | List commands = updateAnalyse.getCommands(); 52 | assertEquals(1, commands.size()); 53 | assertEquals(START, commands.get(0)); 54 | } 55 | 56 | @Test 57 | public void shouldRecognize_START_clear_case1() { 58 | mockMessageText("/start"); 59 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 60 | List commands = updateAnalyse.getCommands(); 61 | assertEquals(1, commands.size()); 62 | assertEquals(START, commands.get(0)); 63 | } 64 | 65 | @Test 66 | public void shouldRecognize_START_clear_case2() { 67 | mockMessageText("/start "); 68 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 69 | List commands = updateAnalyse.getCommands(); 70 | assertEquals(1, commands.size()); 71 | assertEquals(START, commands.get(0)); 72 | } 73 | 74 | @Test 75 | public void shouldRecognize_START_clear_case3() { 76 | mockMessageText("/start\n"); 77 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 78 | List commands = updateAnalyse.getCommands(); 79 | assertEquals(1, commands.size()); 80 | assertEquals(START, commands.get(0)); 81 | } 82 | 83 | @Test 84 | public void shouldRecognize_START_clear_case4() { 85 | mockMessageText("/start \n"); 86 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 87 | List commands = updateAnalyse.getCommands(); 88 | assertEquals(1, commands.size()); 89 | assertEquals(START, commands.get(0)); 90 | } 91 | 92 | @Test 93 | public void shouldRecognize_START_clear_case5() { 94 | mockMessageText("/start sometext"); 95 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 96 | List commands = updateAnalyse.getCommands(); 97 | assertEquals(1, commands.size()); 98 | assertEquals(START, commands.get(0)); 99 | } 100 | 101 | @Test 102 | public void shouldRecognize_START_clear_case6() { 103 | mockMessageText("/start " + INTEXT.command()); 104 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 105 | List commands = updateAnalyse.getCommands(); 106 | assertEquals(1, commands.size()); 107 | assertEquals(START, commands.get(0)); 108 | } 109 | 110 | @Test 111 | public void shouldRecognize_START_clear_case7() { 112 | mockMessageText("/start\n" + INTEXT.command()); 113 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 114 | List commands = updateAnalyse.getCommands(); 115 | assertEquals(1, commands.size()); 116 | assertEquals(START, commands.get(0)); 117 | } 118 | 119 | @Test 120 | public void shouldRecognize_START_clear_case8() { 121 | mockMessageText("/stARt\n"); 122 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 123 | List commands = updateAnalyse.getCommands(); 124 | assertEquals(1, commands.size()); 125 | assertEquals(START, commands.get(0)); 126 | } 127 | 128 | @Test 129 | public void shouldRecognize_START_with_BotName_case1() { 130 | mockMessageText("/start" + "@" + BOTNAME); 131 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 132 | List commands = updateAnalyse.getCommands(); 133 | assertEquals(1, commands.size()); 134 | assertEquals(START, commands.get(0)); 135 | } 136 | 137 | @Test 138 | public void shouldRecognize_START_with_BotName_case2() { 139 | mockMessageText("/start" + "@" + BOTNAME + " "); 140 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 141 | List commands = updateAnalyse.getCommands(); 142 | assertEquals(1, commands.size()); 143 | assertEquals(START, commands.get(0)); 144 | } 145 | 146 | @Test 147 | public void shouldRecognize_START_with_BotName_case3() { 148 | mockMessageText("/start" + "@" + BOTNAME + "\n"); 149 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 150 | List commands = updateAnalyse.getCommands(); 151 | assertEquals(1, commands.size()); 152 | assertEquals(START, commands.get(0)); 153 | } 154 | 155 | @Test 156 | public void shouldRecognize_START_with_BotName_case4() { 157 | mockMessageText("/start" + "@" + BOTNAME + " \n"); 158 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 159 | List commands = updateAnalyse.getCommands(); 160 | assertEquals(1, commands.size()); 161 | assertEquals(START, commands.get(0)); 162 | } 163 | 164 | @Test 165 | public void shouldRecognize_START_with_BotName_case5() { 166 | mockMessageText("/start" + "@" + BOTNAME + " sometext"); 167 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 168 | List commands = updateAnalyse.getCommands(); 169 | assertEquals(1, commands.size()); 170 | assertEquals(START, commands.get(0)); 171 | } 172 | 173 | @Test 174 | public void shouldNotRecognize_START_with_WrongBotName_case1() { 175 | mockMessageText("/start" + "@" + WRONG_BOTNAME); 176 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 177 | List commands = updateAnalyse.getCommands(); 178 | assertEquals(0, commands.size()); 179 | } 180 | 181 | @Test 182 | public void shouldNotRecognize_START_with_WrongBotName_case2() { 183 | mockMessageText("/start" + "@" + WRONG_BOTNAME + " " + INTEXT.command()); 184 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 185 | List commands = updateAnalyse.getCommands(); 186 | assertEquals(0, commands.size()); 187 | } 188 | 189 | @Test 190 | public void shouldRecognize_INTEXT_standalone() { 191 | mockMessageText(INTEXT.command()); 192 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 193 | List commands = updateAnalyse.getCommands(); 194 | assertEquals(1, commands.size()); 195 | assertEquals(INTEXT, commands.get(0)); 196 | } 197 | 198 | @Test 199 | public void shouldRecognize_INTEXT_beetwen_noize_text_with_spaces() { 200 | mockMessageText("noize " + INTEXT.command() + " noize"); 201 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 202 | List commands = updateAnalyse.getCommands(); 203 | assertEquals(1, commands.size()); 204 | assertEquals(INTEXT, commands.get(0)); 205 | } 206 | 207 | @Test 208 | public void shouldRecognize_INTEXT_beetwen_noize_text_with_spaces_case2() { 209 | mockMessageText("noize " + INTEXT.command() + "? noize"); 210 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 211 | List commands = updateAnalyse.getCommands(); 212 | assertEquals(1, commands.size()); 213 | assertEquals(INTEXT, commands.get(0)); 214 | } 215 | 216 | @Test 217 | public void shouldNotRecognize_INTEXT_started_with_commandPrefix() { 218 | mockMessageText(MsgService.PREFIX_FOR_COMMAND + INTEXT.command()); 219 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 220 | List commands = updateAnalyse.getCommands(); 221 | assertEquals(0, commands.size()); 222 | } 223 | 224 | @Test 225 | public void shouldNotRecognize_INTEXT_beetwen_noize_text_without_spaces() { 226 | mockMessageText("noize" + INTEXT.command() + "noize"); 227 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 228 | List commands = updateAnalyse.getCommands(); 229 | assertEquals(0, commands.size()); 230 | } 231 | 232 | @Test 233 | public void shouldNotRecognize_INTEXT_with_WrongBotName_case2() { 234 | mockMessageText("/start" + "@" + WRONG_BOTNAME + " " + INTEXT.command()); 235 | AnalyzeResult updateAnalyse = parser.getUpdateAnalyse(update); 236 | List commands = updateAnalyse.getCommands(); 237 | assertEquals(0, commands.size()); 238 | } 239 | 240 | private List getCommands() { 241 | List list = new ArrayList<>(); 242 | list.add(START); 243 | list.add(HELP); 244 | list.add(INTEXT); 245 | return list; 246 | } 247 | 248 | private void mockMessageText(String text) { 249 | Mockito.when(message.getText()).thenReturn(text); 250 | } 251 | 252 | } -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/service/MsgServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.mockito.Mockito; 6 | import org.telegram.telegrambots.api.methods.send.SendMessage; 7 | import org.telegram.telegrambots.api.objects.Update; 8 | 9 | import static org.junit.Assert.assertEquals; 10 | 11 | public class MsgServiceTest { 12 | MsgService msgService; 13 | QueueProvider queueProvider; 14 | 15 | @Before 16 | public void setup() { 17 | msgService = new MsgService(); 18 | queueProvider = new QueueProvider(); 19 | msgService.setQueueProvider(queueProvider); 20 | } 21 | 22 | @Test 23 | public void shouldPutNewMessageToSendQueue() { 24 | // should be 0 size in send queue when start 25 | assertEquals(0, queueProvider.getSendQueue().size()); 26 | 27 | // when call sendMessage 28 | SendMessage message = new SendMessage(); 29 | msgService.sendMessage(message); 30 | 31 | // then queue should contain it 32 | assertEquals(1, queueProvider.getSendQueue().size()); 33 | assertEquals(message, queueProvider.getSendQueue().peek()); 34 | } 35 | 36 | @Test 37 | public void shouldPutNewUpdateToReceiveQueue() { 38 | // should be 0 size in send queue when start 39 | assertEquals(0, queueProvider.getReceiveQueue().size()); 40 | 41 | // when call sendMessage 42 | Update updateMock = Mockito.mock(Update.class); 43 | msgService.acceptMessage(updateMock); 44 | 45 | // then queue should contain it 46 | assertEquals(1, queueProvider.getReceiveQueue().size()); 47 | } 48 | 49 | @Test 50 | public void shouldContainsAStringWithDelimeters_case1() { 51 | assertEquals(true, msgService.contains("instr", "in big instr string")); 52 | } 53 | 54 | @Test 55 | public void shouldContainsAStringWithDelimeters_case2() { 56 | assertEquals(true, msgService.contains("instr", "instr in big string")); 57 | } 58 | 59 | @Test 60 | public void shouldContainsAStringWithDelimeters_case3() { 61 | assertEquals(true, msgService.contains("instr", "in big string instr")); 62 | } 63 | 64 | @Test 65 | public void shouldContainsAStringWithDelimeters_case4() { 66 | assertEquals(true, msgService.contains("instr", "in big instr, string")); 67 | } 68 | 69 | @Test 70 | public void shouldContainsAStringWithDelimeters_case5() { 71 | assertEquals(true, msgService.contains("long instr text", "in big long instr text. string")); 72 | } 73 | 74 | @Test 75 | public void shouldNotContainsAStringWithDelimeters_case1() { 76 | assertEquals(false, msgService.contains("instr", "in biginstr, string")); 77 | } 78 | 79 | @Test 80 | public void shouldNotContainsAStringWithDelimeters_case2() { 81 | assertEquals(false, msgService.contains("instr", "in big inst r string")); 82 | } 83 | 84 | @Test 85 | public void shouldNotContainsAStringWithDelimeters_case3() { 86 | assertEquals(false, msgService.contains(" ", "in big inst r string")); 87 | } 88 | 89 | @Test 90 | public void shouldNotContainsAStringWithDelimeters_case3a() { 91 | assertEquals(false, msgService.contains(".", "in big inst r string")); 92 | } 93 | 94 | @Test 95 | public void shouldNotContainsAStringWithDelimeters_case4() { 96 | assertEquals(false, msgService.contains(null, "in big inst r string")); 97 | } 98 | 99 | @Test 100 | public void shouldNotContainsAStringWithDelimeters_case5() { 101 | assertEquals(false, msgService.contains(null, null)); 102 | } 103 | 104 | @Test 105 | public void shouldNotContainsAStringWithDelimeters_case6() { 106 | assertEquals(false, msgService.contains("str", null)); 107 | } 108 | 109 | @Test 110 | public void shouldNotContainsAStringWithDelimeters_case7() { 111 | assertEquals(false, msgService.contains("", "in big inst r string")); 112 | } 113 | } -------------------------------------------------------------------------------- /base/src/test/java/com/example/telegrambot/service/MsgServiceUpdateTest.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot.service; 2 | 3 | import com.example.telegrambot.UpdateMock; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import static com.example.telegrambot.parser.MessageType.MESSAGE; 10 | import static org.mockito.Mockito.when; 11 | 12 | public class MsgServiceUpdateTest extends UpdateMock { 13 | protected static final String MESSAGE_TEXT = "Message text"; 14 | protected static final long CHAT_ID_MESSAGE = 1000001l; 15 | MsgService msgService; 16 | AnalyzeResult analyzeResult; 17 | 18 | @Before 19 | public void setup() { 20 | clearSetup(); 21 | 22 | msgService = new MsgService(); 23 | analyzeResult = new AnalyzeResult(update); 24 | 25 | tuneMessage(user, MESSAGE_TEXT, CHAT_ID_MESSAGE); 26 | when(update.getMessage()).thenReturn(message); 27 | } 28 | 29 | 30 | // todo need more tests 31 | @Test 32 | public void shouldGetChatId_whenType_MESSAGE() { 33 | // when 34 | analyzeResult.setMessageType(MESSAGE); 35 | 36 | // then 37 | Assert.assertEquals(Long.toString(CHAT_ID_MESSAGE), msgService.getChatId(analyzeResult)); 38 | } 39 | 40 | @Test 41 | public void shouldGetMessageText_whenType_MESSAGE() { 42 | // when 43 | analyzeResult.setMessageType(MESSAGE); 44 | 45 | // then 46 | Assert.assertEquals(MESSAGE_TEXT, msgService.getMessageText(analyzeResult)); 47 | } 48 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.example.telegrambot 6 | telegramBotBase 7 | 1.0-SNAPSHOT 8 | 9 | base 10 | FortuneWheel 11 | sample-bot 12 | 13 | pom 14 | 15 | telegramBotBase 16 | 17 | 18 | 1.18.20 19 | 2.17.2 20 | 3.5 21 | 2.24.0 22 | 4.13.1 23 | 3.3.0 24 | UTF-8 25 | 26 | 27 | 28 | 29 | 30 | 31 | org.apache.maven.plugins 32 | maven-compiler-plugin 33 | 3.8.0 34 | 35 | 1.8 36 | 1.8 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /sample-bot/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.example.telegrambot 8 | telegramBotBase 9 | 1.0-SNAPSHOT 10 | 11 | com.example.telegrambot 12 | sample-bot 13 | 1.0 14 | jar 15 | sample-bot 16 | 17 | 18 | 19 | com.example.telegrambot 20 | base 21 | 1.0 22 | compile 23 | 24 | 25 | 26 | org.telegram 27 | telegrambots 28 | ${org.telegram.telegrambots.version} 29 | 30 | 31 | 32 | com.vdurmont 33 | emoji-java 34 | ${com.vdurmont.emoji-java.version} 35 | 36 | 37 | 38 | 39 | org.projectlombok 40 | lombok 41 | ${org.projectlombok.lombok.version} 42 | provided 43 | 44 | 45 | 46 | 47 | org.apache.logging.log4j 48 | log4j-api 49 | ${org.apache.logging.log4j.version} 50 | 51 | 52 | 53 | org.apache.logging.log4j 54 | log4j-core 55 | ${org.apache.logging.log4j.version} 56 | 57 | 58 | 59 | org.mockito 60 | mockito-core 61 | ${org.mockito.version} 62 | 63 | 64 | 65 | junit 66 | junit 67 | ${junit.version} 68 | test 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /sample-bot/src/main/java/com/example/telegrambot/App.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import com.example.telegrambot.bot.Bot; 4 | import com.example.telegrambot.command.CommandElement; 5 | import com.example.telegrambot.handler.AbstractHandler; 6 | import com.example.telegrambot.handler.HandlerService; 7 | import com.example.telegrambot.handler.impl.HandlerImpl; 8 | import com.example.telegrambot.parser.ParserService; 9 | import com.example.telegrambot.parser.impl.ParserImpl; 10 | import com.example.telegrambot.service.*; 11 | import org.apache.logging.log4j.LogManager; 12 | import org.apache.logging.log4j.Logger; 13 | import org.telegram.telegrambots.ApiContextInitializer; 14 | import org.telegram.telegrambots.api.methods.send.SendMessage; 15 | import org.telegram.telegrambots.generics.BotSession; 16 | 17 | import java.util.ArrayList; 18 | import java.util.HashMap; 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | public class App { 23 | private static final Logger log = LogManager.getLogger(App.class); 24 | private static final int PRIORITY_FOR_SENDER = 1; 25 | private static final int PRIORITY_FOR_RECEIVER = 3; 26 | private static final String BOT_ADMIN = "321644283"; 27 | 28 | public static void main(String[] args) { 29 | ApiContextInitializer.init(); 30 | String botName = System.getenv("test_bot_name"); 31 | String botToken = System.getenv("test_bot_token"); 32 | 33 | List checkList = new ArrayList<>(); 34 | 35 | QueueProvider queueProvider = new QueueProvider(); 36 | checkList.add(queueProvider); 37 | 38 | MsgService msgService = new MsgService(); 39 | checkList.add(msgService); 40 | msgService.setQueueProvider(queueProvider); 41 | 42 | Map> links = new HashMap<>(); 43 | links.put(new StartCommand(), StartHandler.class); 44 | HandlerService handlerService = new HandlerImpl(links); 45 | checkList.add(handlerService); 46 | 47 | ParserService parser = new ParserImpl(); 48 | parser.setBotName(botName); 49 | parser.setCommands(new ArrayList<>(links.keySet())); 50 | checkList.add(parser); 51 | 52 | Bot test_habr_bot = new Bot(botName, botToken); 53 | checkList.add(test_habr_bot); 54 | test_habr_bot.setMsgService(msgService); 55 | 56 | 57 | MessageReceiver messageReceiver = new MessageReceiver(test_habr_bot, queueProvider); 58 | checkList.add(messageReceiver); 59 | messageReceiver.setHandlerService(handlerService); 60 | messageReceiver.setParserService(parser); 61 | messageReceiver.setMsgService(msgService); 62 | 63 | MessageSender messageSender = new MessageSender(test_habr_bot, queueProvider.getSendQueue()); 64 | checkList.add(messageSender); 65 | 66 | checkElementsBeforeStart(checkList); 67 | 68 | BotSession connect = test_habr_bot.connect(); 69 | log.info("StartBotSession. Bot started. " + connect.toString()); 70 | 71 | Thread receiver = new Thread(messageReceiver); 72 | receiver.setDaemon(true); 73 | receiver.setName("MsgReceiver"); 74 | receiver.setPriority(PRIORITY_FOR_RECEIVER); 75 | receiver.start(); 76 | 77 | Thread sender = new Thread(messageSender); 78 | sender.setDaemon(true); 79 | sender.setName("MsgSender"); 80 | sender.setPriority(PRIORITY_FOR_SENDER); 81 | sender.start(); 82 | 83 | sendStartReport(msgService); 84 | } 85 | 86 | private static void checkElementsBeforeStart(List checkList) { 87 | checkList.forEach(element -> { 88 | if (element.isConstructed()) { 89 | log.info(element + " Constructed"); 90 | } else { 91 | throw new IllegalArgumentException(element + " Not Constructed"); 92 | } 93 | }); 94 | } 95 | 96 | private static void sendStartReport(MsgService msgService) { 97 | SendMessage sendMessage = new SendMessage(); 98 | sendMessage.setChatId(BOT_ADMIN); 99 | sendMessage.setText("Запустился"); 100 | msgService.sendMessage(sendMessage); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /sample-bot/src/main/java/com/example/telegrambot/StartCommand.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import com.example.telegrambot.command.CommandElement; 4 | 5 | public class StartCommand implements CommandElement { 6 | @Override 7 | public String command() { 8 | return "START"; 9 | } 10 | 11 | @Override 12 | public boolean isInTextCommand() { 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /sample-bot/src/main/java/com/example/telegrambot/StartHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.telegrambot; 2 | 3 | import com.example.telegrambot.handler.AbstractHandler; 4 | import com.example.telegrambot.parser.AnalyzeResult; 5 | import com.example.telegrambot.parser.ParsedCommand; 6 | import org.telegram.telegrambots.api.methods.send.SendMessage; 7 | import org.telegram.telegrambots.api.objects.Update; 8 | 9 | import static com.example.telegrambot.service.MsgService.END_LINE; 10 | 11 | public class StartHandler extends AbstractHandler { 12 | @Override 13 | public String operate(String chatId, ParsedCommand parsedCommand, Update update) { 14 | return null; 15 | } 16 | 17 | @Override 18 | public String operate(AnalyzeResult analyzeResult) { 19 | String chatId = msgService.getChatId(analyzeResult); 20 | SendMessage message = getMessageStart(chatId); 21 | msgService.sendMessage(message); 22 | return null; 23 | } 24 | 25 | private SendMessage getMessageStart(String chatID) { 26 | SendMessage sendMessage = new SendMessage(); 27 | sendMessage.setChatId(chatID); 28 | sendMessage.enableMarkdown(true); 29 | StringBuilder text = new StringBuilder(); 30 | text.append("Hello. I'm *").append(bot.getBotUsername()).append("*").append(END_LINE); 31 | text.append("I'm just example").append(END_LINE); 32 | text.append("All that I can do - you can see calling the command [/help](/help)"); 33 | sendMessage.setText(text.toString()); 34 | return sendMessage; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /sample-bot/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | --------------------------------------------------------------------------------