Skip to content

Commit

Permalink
[TG BOT] Add Telegram bot to project. Add dependency, TelegramUserInf…
Browse files Browse the repository at this point in the history
…o model and liquibase script
  • Loading branch information
AntonBabychP1T committed Jan 19, 2024
1 parent c3920aa commit 05a9a48
Show file tree
Hide file tree
Showing 10 changed files with 238 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@
<artifactId>stripe-java</artifactId>
<version>24.11.0</version>
</dependency>
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots-spring-boot-starter</artifactId>
<version>6.9.0</version>
</dependency>
</dependencies>

<build>
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/service/carsharing/config/TelegramBotConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package service.carsharing.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import service.carsharing.telegram.TelegramBotService;

@Configuration
public class TelegramBotConfig {
private final TelegramBotService telegramBotService;

public TelegramBotConfig(TelegramBotService telegramBotService) {
this.telegramBotService = telegramBotService;
}

@Bean
public TelegramBotsApi telegramBotsApi() {
try {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
telegramBotsApi.registerBot(telegramBotService);
return telegramBotsApi;
} catch (TelegramApiException e) {
throw new RuntimeException("Can't create Telegram bot API", e);
}
}
}
25 changes: 25 additions & 0 deletions src/main/java/service/carsharing/model/TelegramUserInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package service.carsharing.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "telegram_user_info")
public class TelegramUserInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private Long chatId;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package service.carsharing.repository;

import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import service.carsharing.model.TelegramUserInfo;

public interface TelegramUserInfoRepository extends JpaRepository<TelegramUserInfo, Long> {
Optional<TelegramUserInfo> findByChatId(Long chatId);

Optional<TelegramUserInfo> findByUserId(Long userId);
}
12 changes: 12 additions & 0 deletions src/main/java/service/carsharing/service/TelegramUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package service.carsharing.service;

import service.carsharing.telegram.TelegramUserState;

public interface TelegramUserService {

void registerNewUser(Long chatId, String username);

TelegramUserState getUserState(Long chatId);

void addUserState(Long chatId, TelegramUserState state);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package service.carsharing.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import service.carsharing.model.TelegramUserInfo;
import service.carsharing.repository.TelegramUserInfoRepository;
import service.carsharing.repository.UserRepository;
import service.carsharing.service.TelegramUserService;
import service.carsharing.telegram.TelegramBotService;
import service.carsharing.telegram.TelegramUserState;

@RequiredArgsConstructor
@Service
public class TelegramUserServiceImpl implements TelegramUserService {
private final TelegramUserInfoRepository telegramUserInfoRepository;
private final UserRepository userRepository;
private final ApplicationContext context;
private final Map<Long, TelegramUserState> userStates = new HashMap<>();

@Override
public void registerNewUser(Long chatId, String username) {
if (!isEmail(username) || userRepository.findByEmail(username).isEmpty()) {
TelegramBotService botService = context.getBean(TelegramBotService.class);
botService.sendMessage(chatId, "Not valid email, please send again");
return;
}
userStates.get(chatId).setAwaitingEmail(false);
TelegramUserInfo telegramUserInfo = new TelegramUserInfo();
telegramUserInfo.setChatId(chatId);
telegramUserInfo.setUser(userRepository.findByEmail(username).get());
telegramUserInfoRepository.save(telegramUserInfo);
}

@Override
public TelegramUserState getUserState(Long chatId) {
return userStates.get(chatId);
}

@Override
public void addUserState(Long chatId, TelegramUserState state) {
userStates.put(chatId, state);
}

private boolean isEmail(String email) {
Pattern p = Pattern.compile("\\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Z]{2,4}\\b",
Pattern.CASE_INSENSITIVE);
return p.matcher(email).find();
}
}
59 changes: 59 additions & 0 deletions src/main/java/service/carsharing/telegram/TelegramBotService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package service.carsharing.telegram;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
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 service.carsharing.service.TelegramUserService;

@RequiredArgsConstructor
@Service
public class TelegramBotService extends TelegramLongPollingBot {
@Value("${TELEGRAM_BOT_TOKEN}")
private String botToken;
@Value("${TELEGRAM_BOT_USERNAME}")
private String botUsername;
private final TelegramUserService telegramUserService;

@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
Long chatId = update.getMessage().getChatId();
TelegramUserState state = telegramUserService.getUserState(chatId);
if (state == null) {
telegramUserService.addUserState(chatId, new TelegramUserState(chatId, true));
sendMessage(chatId, "Enter your email to verify");
} else if (state.isAwaitingEmail()) {
String email = update.getMessage().getText();
telegramUserService.registerNewUser(chatId, email);
} else {
String text = update.getMessage().getText();
}
}
}

@Override
public String getBotToken() {
return botToken;
}

@Override
public String getBotUsername() {
return botUsername;
}

public void sendMessage(Long chatId, String text) {
SendMessage sendMessage = SendMessage.builder()
.chatId(chatId)
.text(text)
.build();
try {
execute(sendMessage);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
}
15 changes: 15 additions & 0 deletions src/main/java/service/carsharing/telegram/TelegramUserState.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package service.carsharing.telegram;

import lombok.Data;

@Data
public class TelegramUserState {
private Long chatId;
private String email;
private boolean awaitingEmail;

public TelegramUserState(Long chatId, boolean awaitingEmail) {
this.chatId = chatId;
this.awaitingEmail = awaitingEmail;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
databaseChangeLog:
- changeSet:
id: create-telegram-user-info-table
author: antonbabych
changes:
- createTable:
tableName: telegram_user_info
columns:
- column:
name: id
type: bigint
autoIncrement: true
constraints:
primaryKey: true
nullable: false
- column:
name: chat_id
type: bigint
constraints:
nullable: false
- column:
name: user_id
type: bigint
constraints:
nullable: false
foreignKeyName: fk_telegram_user_info_users
references: users(id)
4 changes: 3 additions & 1 deletion src/main/resources/db/changelog/db.changelog-master.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ databaseChangeLog:
- include:
file: db/changelog/changes/07-create-rentals-table.yaml
- include:
file: db/changelog/changes/08-create-payments-table.yaml
file: db/changelog/changes/08-create-payments-table.yaml
- include:
file: db/changelog/changes/09-create-telegram-user-info-table.yaml

0 comments on commit 05a9a48

Please sign in to comment.