Skip to content

Commit

Permalink
updated project version and added to RELEASE_NOTES (#17)
Browse files Browse the repository at this point in the history
* updated project version and added to RELEASE_NOTES

* updated project version and added to RELEASE_NOTES
  • Loading branch information
IvanLiVa authored Nov 24, 2023
1 parent 2cb674e commit 981c356
Show file tree
Hide file tree
Showing 23 changed files with 489 additions and 29 deletions.
3 changes: 3 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
JRTB-2: added stub telegram bot
JRTB-0: added SpringBoot skeleton project

## 0.2.0
* impelements command pattern for handling Telegram bot command
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</parent>
<groupId>com.github.JBolivarLi</groupId>
<artifactId>javarush-telegrambot</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>0.2.0-SNAPSHOT</version>
<name>javarush-telegrambot</name>
<description>Telegram bot for Javarush from community to community</description>
<properties>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@
import org.springframework.context.annotation.ComponentScan;



@SpringBootApplication

public class JavarushTelegrambotApplication {

public static void main(String[] args) {
SpringApplication.run(JavarushTelegrambotApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(JavarushTelegrambotApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.bot;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandContainer;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.NO;

@Component
public class JavarushTelegramBot extends TelegramLongPollingBot {
public static String COMMAND_PREFIX = "/";
@Value("${bot.username}")
private String username;

Expand All @@ -22,22 +27,21 @@ public String getBotToken() {
return token;
}


private final CommandContainer commandContainer;
public JavarushTelegramBot() {
this.commandContainer = new CommandContainer(new SendBotMessageServiceImpl(this));
}

public void onUpdateReceived(Update update) {
if(update.hasMessage() && update.getMessage().hasText()) {
String message = update.getMessage().getText().trim();
String chatId = update.getMessage().getChatId().toString();

SendMessage sm = new SendMessage();
sm.setChatId(chatId);
sm.setText(message + "\n" + "fromBolivarBotWithLove");

try {
execute(sm);
} catch (TelegramApiException e) {
//todo add logging to the project.
e.printStackTrace();
if (message.startsWith(COMMAND_PREFIX)){
String commandIdentifier = message.split(" ")[0].toLowerCase();
commandContainer.retrieveCommand(commandIdentifier).execute(update);
} else {
commandContainer.retrieveCommand(NO.getCommandName()).execute(update);
}
}

}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import org.telegram.telegrambots.meta.api.objects.Update;
/**
* Command interface for handling telegram-bot commands.
*/
public interface Command {
void execute(Update update);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageServiceImpl;

import java.util.Map;

import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.*;

public class CommandContainer {
private final Map<String, Command> commandMap;
private final Command unknownCommand;

public CommandContainer(SendBotMessageService sendBotMessageService) {
commandMap = Map.ofEntries(Map.entry(START.getCommandName(), new StartCommand(sendBotMessageService)),
Map.entry(STOP.getCommandName(), new StopCommand(sendBotMessageService)),
Map.entry(HELP.getCommandName(), new HelpCommand(sendBotMessageService)),
Map.entry(NO.getCommandName(), new NoCommand(sendBotMessageService)));

unknownCommand = new UnknownCommand(sendBotMessageService);
}

public Command retrieveCommand(String commandIdentifier) {
return commandMap.getOrDefault(commandIdentifier, unknownCommand);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

public enum CommandName {

START("/start"),
STOP("/stop"),
HELP("/help"),
NO("nocommand");

private final String commandName;

CommandName(String commandName) {
this.commandName = commandName;
}

public String getCommandName() {
return commandName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

import static com.github.JBolivarLi.javarushtelegrambot.bot.command.CommandName.*;


public class HelpCommand implements Command {

private final SendBotMessageService sendBotMessageService;

public static final String HELP_MESSAGE = String.format("✨<b>Дотупные команды</b>✨\n\n"

+ "<b>Начать\\закончить работу с ботом</b>\n"
+ "%s - начать работу со мной\n"
+ "%s - приостановить работу со мной\n\n"
+ "%s - получить помощь в работе со мной\n",
START.getCommandName(), STOP.getCommandName(), HELP.getCommandName());

public HelpCommand(SendBotMessageService sendBotMessageService) {
this.sendBotMessageService = sendBotMessageService;
}

@Override
public void execute(Update update) {
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), HELP_MESSAGE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

public class NoCommand implements Command {

private final SendBotMessageService sendBotMessageService;

public static final String NO_MESSAGE = "Я поддерживаю команды, начинающиеся со слеша(/).\n"
+ "Чтобы посмотреть список команд введите /help";

public NoCommand(SendBotMessageService sendBotMessageService) {
this.sendBotMessageService = sendBotMessageService;
}

@Override
public void execute(Update update) {
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), NO_MESSAGE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

public class StartCommand implements Command {

private final SendBotMessageService sendBotMessageService;

public final static String START_MESSAGE = "Привет. Я JBolivar Telegram Bot. Я помогу тебе быть в курсе последних " +
"статей тех авторов, котрые тебе интересны. Я еще маленький и только учусь.";

// Здесь не добавляем сервис через получение из Application Context.
// Потому что если это сделать так, то будет циклическая зависимость, которая
// ломает работу приложения.
public StartCommand(SendBotMessageService sendBotMessageService) {
this.sendBotMessageService = sendBotMessageService;
}

@Override
public void execute(Update update) {
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), START_MESSAGE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

public class StopCommand implements Command {

private final SendBotMessageService sendBotMessageService;

public static final String STOP_MESSAGE = "Деактивировал все ваши подписки \uD83D\uDE1F.";

public StopCommand(SendBotMessageService sendBotMessageService) {
this.sendBotMessageService = sendBotMessageService;
}

@Override
public void execute(Update update) {
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), STOP_MESSAGE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.command;

import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

public class UnknownCommand implements Command{
public static final String UNKNOWN_MESSAGE = "Не понимаю вас \uD83D\uDE1F, напишите /help чтобы узнать что я понимаю.";

private final SendBotMessageService sendBotMessageService;

public UnknownCommand(SendBotMessageService sendBotMessageService) {
this.sendBotMessageService = sendBotMessageService;
}

@Override
public void execute(Update update) {
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(), UNKNOWN_MESSAGE);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.service;

public interface SendBotMessageService {
/**
* Send message via telegram bot.
*
* @param chatId provided chatId in which messages would be sent.
* @param message provided message to be sent.
*/
void sendMessage(String chatId, String message);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.JBolivarLi.javarushtelegrambot.bot.service;

import com.github.JBolivarLi.javarushtelegrambot.bot.bot.JavarushTelegramBot;
import org.jvnet.hk2.annotations.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

@Service
public class SendBotMessageServiceImpl implements SendBotMessageService{
private final JavarushTelegramBot javarushBot;

@Autowired
public SendBotMessageServiceImpl(JavarushTelegramBot javarushBot) {
this.javarushBot = javarushBot;
}

@Override
public void sendMessage(String chatId, String message) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId);
sendMessage.enableHtml(true);
sendMessage.setText(message);

try {
javarushBot.execute(sendMessage);
} catch (TelegramApiException e) {
//todo add logging to the project.
e.printStackTrace();
}
}
}
48 changes: 48 additions & 0 deletions src/test/java/AbstractCommandTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import com.github.JBolivarLi.javarushtelegrambot.bot.bot.JavarushTelegramBot;
import com.github.JBolivarLi.javarushtelegrambot.bot.command.Command;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageService;
import com.github.JBolivarLi.javarushtelegrambot.bot.service.SendBotMessageServiceImpl;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

/**
* Abstract class for testing {@link Command}s.
*/
abstract class AbstractCommandTest {

protected JavarushTelegramBot javarushBot = Mockito.mock(JavarushTelegramBot.class);
protected SendBotMessageService sendBotMessageService = new SendBotMessageServiceImpl(javarushBot);

abstract String getCommandName();

abstract String getCommandMessage();

abstract Command getCommand();

@Test
public void shouldProperlyExecuteCommand() throws TelegramApiException {
//given
Long chatId = 1234567824356L;

Update update = new Update();
Message message = Mockito.mock(Message.class);
Mockito.when(message.getChatId()).thenReturn(chatId);
Mockito.when(message.getText()).thenReturn(getCommandName());
update.setMessage(message);

SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId.toString());
sendMessage.setText(getCommandMessage());
sendMessage.enableHtml(true);

//when
getCommand().execute(update);

//then
Mockito.verify(javarushBot).execute(sendMessage);
}
}
Loading

0 comments on commit 981c356

Please sign in to comment.