Skip to content

Commit

Permalink
Merge pull request #7 from almax07082005/dev_mode
Browse files Browse the repository at this point in the history
Dev mode
  • Loading branch information
almax07082005 authored Nov 16, 2024
2 parents 6862349 + 5be4d41 commit c0aa997
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 38 deletions.
1 change: 1 addition & 0 deletions .github/workflows/CD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ jobs:
echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}>>.env
echo MAIN_TOKEN=${{ secrets.MAIN_TOKEN }}>>.env
echo LOGGER_TOKEN=${{ secrets.LOGGER_TOKEN }}>>.env
echo DEV_TOKEN=${{ secrets.DEV_TOKEN }}>>.env
echo GUIDE=${{ secrets.GUIDE }}>>.env
echo DOCKER_TAG=${{ vars.DOCKER_TAG }}>>.env
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ This telegram bot intends to promote information about cardiology.
## Instructions

#### !!CHANGE DOCKER_TAG GITHUB VARIABLE FOR NEW PRODUCTION VERSION!!
#### !!WHEN DEVELOPING TURN OFF LOGGING TO MAIN CHANNEL!!
#### !!MAKE THE FOLLOWING FOR DEV MODE!!
Change ```telegram.is-dev-mode``` in ```application.yaml``` to ```true```.

### To debug docker container

Expand Down
2 changes: 0 additions & 2 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ services:
tty: true
env_file: ./.env
container_name: 'cardio-db'
restart: always
environment:
- 'POSTGRES_DB=cardio-db'
- 'POSTGRES_USER=${POSTGRES_USER}'
Expand All @@ -20,7 +19,6 @@ services:
image: 'cardio-bot:${DOCKER_TAG}'
container_name: 'cardio-bot'
env_file: ./.env
restart: always
tty: true
depends_on:
- cardio-db
Expand Down
13 changes: 11 additions & 2 deletions src/main/java/com/example/cardiotelegrambot/config/BotConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,23 @@
public class BotConfig {

@Value("${telegram.bot.main-token}")
private String token;
private String mainToken;

@Value("${telegram.bot.dev-token}")
private String devToken;

@Value("${telegram.bot.logger-token}")
private String tokenLogger;

@Value("${telegram.is-dev-mode}")
private Boolean isDevMode;

@Bean("mainBotBean")
public TelegramBot newTelegramBot() {
return new TelegramBot(token);
if (isDevMode) {
return new TelegramBot(devToken);
}
return new TelegramBot(mainToken);
}

@Bean("loggerBotBean")
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/com/example/cardiotelegrambot/config/LogConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ private enum LogType {
@Value("${telegram.logger.error}")
private Integer errorId;

@Value("${telegram.is-dev-mode}")
private Boolean isDevMode;

@Value("${telegram.logger.dev-chat-id}")
private Long devChatId;

private final TelegramBot loggerBot;

@Autowired
Expand All @@ -46,6 +52,13 @@ private void sendMessage(LogType logType, String message, Integer messageThreadI
message
);

if (isDevMode) {
loggerBot.execute(new SendMessage(
devChatId,
finalMessage
));
return;
}
loggerBot.execute(new SendMessage(
chatId,
finalMessage
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@ public class LoggerBotService {
private final Logger logger;
private final LoggerCommand command;
private final LoggerButton button;
private final LoggerCommand loggerCommand;

@Autowired
public LoggerBotService(@Qualifier("loggerBotBean") TelegramBot bot, Logger logger, LoggerCommand command, LoggerButton button, LoggerCommand loggerCommand) {
public LoggerBotService(@Qualifier("loggerBotBean") TelegramBot bot,
Logger logger,
LoggerCommand command,
LoggerButton button) {
this.bot = bot;
this.logger = logger;
this.command = command;
this.button = button;
this.loggerCommand = loggerCommand;
}

public void startBot() {
Expand All @@ -51,13 +52,27 @@ public void startBot() {
}

private void executeButton(Update update) {
button
.deleteLastMessage()
.getButton(LoggerButtons.valueOf(update
.callbackQuery()
.data()
))
.run();
Long chatId = update
.callbackQuery()
.from()
.id();

try {
button
.isAdmin(chatId)
.deleteLastMessage()
.getButton(LoggerButtons.valueOf(update
.callbackQuery()
.data()
))
.run();
} catch (NotAdminException exception) {
SendMessage message = new SendMessage(
chatId,
exception.getMessage()
);
bot.execute(message);
}
}

private void executeCommand(Update update) {
Expand All @@ -73,7 +88,6 @@ private void executeCommand(Update update) {
update.message().chat().id(),
exception.getMessage()
);
message.replyMarkup(loggerCommand.getInlineKeyboardMarkupForMainMenu());
bot.execute(message);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package com.example.cardiotelegrambot.service.bot.logger;

import com.example.cardiotelegrambot.config.enums.logger.LoggerButtons;
import com.example.cardiotelegrambot.exceptions.NotAdminException;
import com.example.cardiotelegrambot.service.database.ReferralService;
import com.example.cardiotelegrambot.service.database.UserService;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.request.DeleteMessage;
import com.pengrad.telegrambot.request.SendDocument;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import jakarta.annotation.PostConstruct;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -35,6 +37,14 @@ public class LoggerButton {

@Value("${telegram.logger.id}")
private Long adminChatId;

@Value("${telegram.logger.dev-chat-id}")
private Long devChatId;

@Value("${telegram.is-dev-mode}")
private Boolean isDevMode;

private Long chatId;

@Autowired
public LoggerButton(@Qualifier("loggerBotBean") TelegramBot bot, LoggerCommand loggerCommand, UserService userService, ReferralService referralService) {
Expand All @@ -50,10 +60,23 @@ public LoggerButton(@Qualifier("loggerBotBean") TelegramBot bot, LoggerCommand l
this.referralService = referralService;
}

@PostConstruct
public void init() {
chatId = isDevMode ? devChatId : adminChatId;
}

public LoggerButton isAdmin(Long chatId) throws NotAdminException {
if (!chatId.equals(this.chatId)) {
throw new NotAdminException();
}

return this;
}

public LoggerButton deleteLastMessage() {
try {
bot.execute(new DeleteMessage(
adminChatId,
chatId,
messageId
));
} catch (NullPointerException ignored) {}
Expand All @@ -68,7 +91,7 @@ public Runnable getButton(LoggerButtons button) {
private void getWinners() {
userService.storeUsersToCSV();
SendDocument document = new SendDocument(
adminChatId,
chatId,
new File(tableFilename)
);
document.replyMarkup(loggerCommand.getInlineKeyboardMarkupForMainMenu());
Expand All @@ -80,7 +103,7 @@ private void getWinners() {
private void startReferral() {
referralService.startReferral();
SendMessage message = new SendMessage(
adminChatId,
chatId,
"Реферальная программа запущена успешно."
);
message.replyMarkup(loggerCommand.getInlineKeyboardMarkupForMainMenu());
Expand All @@ -92,7 +115,7 @@ private void startReferral() {
private void finishReferral() {
referralService.finishReferral();
SendMessage message = new SendMessage(
adminChatId,
chatId,
"Реферальная программа завершена успешно."
);
message.replyMarkup(loggerCommand.getInlineKeyboardMarkupForMainMenu());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -32,6 +33,13 @@ public class LoggerCommand {
@Value("${telegram.logger.id}")
private Long adminChatId;

@Value("${telegram.logger.dev-chat-id}")
private Long devChatId;

@Value("${telegram.is-dev-mode}")
private Boolean isDevMode;

private Long chatId;
private final Map<LoggerCommands, Runnable> mapCommands;
private Long userChatId;

Expand All @@ -46,6 +54,11 @@ public LoggerCommand(@Qualifier("loggerBotBean") TelegramBot bot, ReferralServic
mapCommands.put(LoggerCommands.check, this::check);
}

@PostConstruct
public void init() {
chatId = isDevMode ? devChatId : adminChatId;
}

public Runnable getCommand(String command) {
try {
Pair<LoggerCommands, Long> pair = LoggerCommands.fromString(command);
Expand All @@ -62,7 +75,7 @@ public LoggerCommand setByUpdate(Update update) throws NotAdminException {
.chat()
.id();

if (!chatId.equals(adminChatId)) {
if (!chatId.equals(this.chatId)) {
throw new NotAdminException();
}

Expand All @@ -71,9 +84,9 @@ public LoggerCommand setByUpdate(Update update) throws NotAdminException {

public void start() {
SendMessage message = new SendMessage(
adminChatId,
chatId,
String.format("""
Привет, братанчик! Тебе пишет твой верный слуга, бот для админов (в этом канале я заправляю, как ты уже понял). Выбери нужную кнопку внизу!
Привет, братанчик! Тебе пишет твой верный слуга, бот для админов (в этом канале я заправляю, как ты уже понял). Выбери нужную кнопку внизу! Также ты можешь ввести команду /check <chat id юзера>, и ты узнаешь подписан ли этот человек на твой канал.
Сейчас реферальная программа %s.
Expand All @@ -94,15 +107,15 @@ private void check() {
.setByVariables(userChatId)
.isSubscribed();
message = new SendMessage(
adminChatId,
chatId,
String.format("""
Пользователь %s подписан на твой канал.
""", userChatId
)
);
} catch (NotMemberException | NullPointerException exception) {
message = new SendMessage(
adminChatId,
chatId,
String.format("""
Пользователь %s НЕ подписан на твой канал.
""", userChatId
Expand Down Expand Up @@ -134,8 +147,8 @@ public InlineKeyboardMarkup getInlineKeyboardMarkupForMainMenu() {

private void notACommand() {
SendMessage message = new SendMessage(
adminChatId,
"Братан, ты какую-то херню написал. Лучше просто нажми одну из доступных кнопок - не ошибешься. Либо напиши команду 'start'."
chatId,
"Братан, ты какую-то херню написал. Лучше просто нажми одну из доступных кнопок - не ошибешься. Либо напиши команду /start."
);
message.replyMarkup(getInlineKeyboardMarkupForMainMenu());
bot.execute(message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BotService {

Expand All @@ -20,25 +17,21 @@ public class BotService {
private final Command command;
private final Logger logger;

// TODO temporary solution
private final List<Long> blocked;

@Autowired
public BotService(@Qualifier("mainBotBean") TelegramBot bot, Button button, Command command, Logger logger) {
public BotService(@Qualifier("mainBotBean") TelegramBot bot,
Button button,
Command command,
Logger logger) {
this.bot = bot;
this.button = button;
this.command = command;
this.logger = logger;

this.blocked = new ArrayList<>();
this.blocked.add(5733496893L);
}

public void startBot() {
bot.setUpdatesListener(updates -> {
try {
for (Update update : updates) {
if (blocked.contains(update.message().chat().id())) continue;
if (update.callbackQuery() != null) executeButton(update);
else if (update.message() != null) executeCommand(update);
}
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ spring:
table: "winners.csv"

telegram:
is-dev-mode: "false"
guide:
file: "${GUIDE}"
bot:
main-token: "${MAIN_TOKEN}"
logger-token: "${LOGGER_TOKEN}"
dev-token: "${DEV_TOKEN}"
logger:
dev-chat-id: "1233629516"
id: "-1002118949277"
info: "62"
warn: "64"
Expand Down

0 comments on commit c0aa997

Please sign in to comment.