Can you help me please? I am writing a telegram bot that will send a reminder about the start of the lecture at the university five minutes before the start of the lecture. This is the logic that should be: when a user writes his group, I make a request to the API https://nure-dev.pp.ua/api/groups to get the group identifier, then using this group I get the identifier (groupId), which should go to https://nure-dev.pp.ua/api/schedule?type=group&id= + groupId + &start_time=1695365795&end_time=1695408995 and then follow the full API link https://nure-dev.pp. ua/api/schedule?type=group&id= + groupId + &start_time=1695365795&end_time=1695408995 and then from this API you will receive a schedule and logic with a reminder. I use Spring Boot.
Example:
/start
Hello, Vlad! This telegram bot will notify you about the beginning of the lecture. To find out more, write /all
/all
everything you need
/setgroup
Enter your group (Example: KNT-23-3)
KNT-23-3
Group successfully installed: KNT-23-3
/remind
And this tag /remind doesn't work. I don't receive reminders about the start of the lecture in five minutes. What should I do?
My base code:
`class UniversityApiService`
@Component
public class UniversityApiService {
private final RestTemplate restTemplate;
private static final String GROUPS_API_URL = "https://nure-dev.pp.ua/api/groups";
private static final String TIME_PARAMETERS = "&start_time=1695365795&end_time=1697621662";
private final ObjectMapper objectMapper;
public UniversityApiService(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.restTemplate = restTemplate;
this.objectMapper=objectMapper;
}
public List<UniversityGroup> getGroups() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<?> entity = new HttpEntity<>(headers);
ResponseEntity<?> responseEntity;
try {
responseEntity = restTemplate.exchange(
GROUPS_API_URL,
HttpMethod.GET,
entity,
String.class // Change the response type to String
);
} catch (HttpStatusCodeException e) {
MediaType contentType = e.getResponseHeaders().getContentType();
if (contentType != null) {
System.out.println("Response Content Type: " + contentType.toString());
}
if (contentType != null && contentType.includes(MediaType.TEXT_PLAIN)) {
// Handle plain text response
String plainTextResponse = e.getResponseBodyAsString();
try {
// Use ObjectMapper to deserialize the plain text response into a list of UniversityGroup objects
List<UniversityGroup> universityGroups = objectMapper.readValue(plainTextResponse, new TypeReference<List<UniversityGroup>>() {});
return universityGroups;
} catch (IOException ex) {
// Handle deserialization error
ex.printStackTrace();
return Collections.emptyList();
}
} else {
// Handle other exceptions
throw e;
}
}
// can also add a check for JSON content type here and parse it accordingly
//
return Collections.emptyList();
}
public String getGroupIdByName(String groupName) {
List<UniversityGroup> groups = getGroups();
if (groups != null) {
for (UniversityGroup group : groups) {
if (group.getName().equalsIgnoreCase(groupName)) {
return group.getId();
}
}
}
return null;
}
public UniversitySchedule getNextLectureForGroup(String groupId) {
ResponseEntity<?> responseEntity;
try {
responseEntity = restTemplate.exchange(
"https://nure-dev.pp.ua/api/schedule?type=group&id=" + groupId + TIME_PARAMETERS,
HttpMethod.GET,
null,
String.class // Change the response type to String
);
} catch (HttpStatusCodeException e) {
MediaType contentType = e.getResponseHeaders().getContentType();
if (contentType != null) {
System.out.println("Response Content Type: " + contentType.toString());
}
if (contentType != null && contentType.includes(MediaType.TEXT_PLAIN)) {
// Handle plain text response
String plainTextResponse = e.getResponseBodyAsString();
try {
// Use ObjectMapper to deserialize the plain text response into a UniversitySchedule object
UniversitySchedule universitySchedule = objectMapper.readValue(plainTextResponse, UniversitySchedule.class);
return universitySchedule;
} catch (IOException ex) {
// Handle deserialization error
ex.printStackTrace();
}
} else {
// Handle other exceptions
throw e;
}
}
return null;
}
}
`class TelegramBot`
@Component
public class TelegramBot extends TelegramLongPollingBot {
private final BotConfig config;
private String userGroup;
private final ChatIdHolder chatIdHolder;
private final UniversityApiService universityApiService;
@Autowired
public TelegramBot(BotConfig config, UniversityApiService universityApiService, ChatIdHolder chatIdHolder){
this.config=config;
this.universityApiService= universityApiService;
this.chatIdHolder=chatIdHolder;
}
@Override
public String getBotUsername() {
return config.getBotName();
}
@Override
public String getBotToken() {
return config.getToken();
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()){
String messageText = update.getMessage().getText();
long chatId= update.getMessage().getChatId();
chatIdHolder.setChatId(chatId);
if (messageText.startsWith("/start")){
startCommandReceived(chatId,update.getMessage().getChat().getFirstName());
}else if(messageText.startsWith("/all")){
startAllCommands(chatId);
}else if(messageText.startsWith("/setgroup")){
sendMessage(chatId, "Введіть вашу группу (Приклад: КНТ-23-3) ");
}else if(messageText.startsWith("/remind")){
if (userGroup != null) {
processUserGroup(userGroup);
} else {
sendMessage(chatId, "Спочатку встановіть групу, використовуючи /setgroup.");
}
}else if (countCapitalLetters(messageText) < 2){
sendMessage(chatId, "Вибачте, я не відповідаю на такі питання. Будь ласка, ознайомтеся з /all");
}else if (countCapitalLetters(messageText) > 2) { // More than two capital letters
sendMessage(chatId, "Група успішно установлена: " + messageText);
userGroup = messageText; // Update userGroup
}
}
}
private int countCapitalLetters(String text) {
int count = 0;
for (char c : text.toCharArray()) {
if (Character.isUpperCase(c)) {
count++;
}
}
return count;
}
//настройка отправки сообщений
private void sendMessage(long chatId, String textToSend){
SendMessage message=new SendMessage();
message.setChatId(String.valueOf(chatId));
message.setText(textToSend);
try{
execute(message);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
public void sendLectureReminder(long chatId,String remiderText){
SendMessage message2= new SendMessage();
message2.setChatId(String.valueOf(chatId));
message2.setText(remiderText);
}
public void processUserGroup(String groupName) {
// Step 1: Get the group ID by group name
String groupId = universityApiService.getGroupIdByName(groupName);
if (groupId != null) {
// Step 2: Get the next lecture for the group
UniversitySchedule nextLecture = universityApiService.getNextLectureForGroup(groupId);
if (nextLecture != null) {
// Step 3: Calculate the reminder time (5 minutes before the lecture)
long lectureStartTime = nextLecture.getStart_time();
long reminderTime = lectureStartTime - (5 * 60);
// Step 4: Convert the reminder time to a human-readable format (if needed)
String reminderTimeFormatted = unixTimestampToDateTime(reminderTime);
// Step 5: Create the reminder text
String reminderText = "Your next lecture is at " + reminderTimeFormatted +
". Lecture: " + nextLecture.getSubject().getTitle();
// Step 6: Send the reminder
long chatId = chatIdHolder.getChatId();
sendLectureReminder(chatId, reminderText);
}
}
}
private String unixTimestampToDateTime(long unixTimestamp) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(unixTimestamp * 1000);
return dateFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void startCommandReceived(long chatId, String name){
String answer= "Привіт, " +name+ "! Цей телеграм бот буде сповіщати про початок лекцій.Щоб дізнатися більше напишіть /all ";
sendMessage(chatId, answer);
}
private void startAllCommands(long chatId){
String allCommands= "все що треба";
sendMessage(chatId, allCommands);
}
public String getUserGroup(){
return userGroup;
}
public void setUserGroup(String userGroup){
}
}
class ChatIdHolder
@Component
@Data
public class ChatIdHolder {
private long chatId;
}
class UniversityGroup(UniversityScedule similare)
@Data
public class UniversityGroup {
private String id;
private String name;
}