Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TELEGRAM] Added NotificationService and Telegram Bot #11

Merged
merged 5 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<maven.checkstyle.plugin.configLocation>checkstyle.xml</maven.checkstyle.plugin.configLocation>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<telegram.version>6.5.0</telegram.version>
</properties>
<dependencies>
<dependency>
Expand Down Expand Up @@ -82,6 +83,11 @@
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>${telegram.version}</version>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.project.carsharingapp.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class TelegramBotConfig {
@Value("${bot.name}")
private String botName;

@Value("${bot.token}")
private String token;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.project.carsharingapp.config;

import com.project.carsharingapp.service.NotificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

@Component
@RequiredArgsConstructor
public class TelegramBotInitializer {
private final NotificationService notificationService;

@EventListener({ContextRefreshedEvent.class})
public void init() throws TelegramApiException {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotsApi.registerBot(notificationService);
}

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.project.carsharingapp.repository;

import com.project.carsharingapp.model.User;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.project.carsharingapp.service;

import com.project.carsharingapp.config.TelegramBotConfig;
import com.project.carsharingapp.model.User;
import com.project.carsharingapp.repository.UserRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
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;

@Component
@RequiredArgsConstructor
public class NotificationService extends TelegramLongPollingBot {
private final TelegramBotConfig config;
private final UserRepository userRepository;

@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
String messageText = update.getMessage().getText();
Long chatId = update.getMessage().getChatId();
switch (messageText) {
case "/start":
startCommandReceived(chatId, update.getMessage().getChat().getFirstName());
break;
default:
break;
}
if (!messageText.startsWith("/")) {
saveUserChatId(chatId, update.getMessage().getText());
}
}
}

private void saveUserChatId(Long chatId, String text) {
Optional<User> optionalUser = userRepository.findByEmail(text);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
user.setTelegramChatId(chatId);
userRepository.save(user);
sendMessage(chatId, "Success");
} else {
sendMessage(chatId, "can`t find user");
}
}

@Override
public String getBotUsername() {
return config.getBotName();
}

@Override
public String getBotToken() {
return config.getToken();
}

public void sendNotification(Long userId, String message) {
//need security
Long chatId = 0L;
sendMessage(chatId, message);
}

private void startCommandReceived(Long chatId, String firstName) {
String answer = "Hi, " + firstName + ", nice to meet you! \n"
+ "Enter your username to get started:";
sendMessage(chatId, answer);

}

private void sendMessage(Long chatId, String textMessage) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chatId);
sendMessage.setText(textMessage);

try {
execute(sendMessage);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}

}
5 changes: 4 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
spring.datasource.url=jdbc:mysql://localhost:3306/car_sharing_db?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

server.servlet.context-path=/api
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.open-in-view=false

bot.name=SharingCarBot
bot.token=6631383610:AAExM59fyeZyshmxsmupqUrAV9TcitH30vk
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ databaseChangeLog:
- column:
name: telegram_chat_id
type: bigint
constraints:
nullable: false
- column:
name: is_deleted
type: boolean
Expand Down
3 changes: 3 additions & 0 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

bot.name=SharingCarBot
bot.token=6631383610:AAExM59fyeZyshmxsmupqUrAV9TcitH30vk
Loading