Skip to content
Open
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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@

# Release Notes

## 0.8.0

*JRTB-10: extended bot statistics for admins.

## 0.7.0

* JRTB-4: added ability to send notifications about new articles
* JRTB-8: added ability to set inactive telegram user
* JRTB-9: added ability to set active user and/or start using it.

## 0.6.0

* JRTB-7 added the ability to delete group subscription

## 0.5.0

* JRTB-5: added ability to subscribe on group
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</parent>
<groupId>com.githab.javarushcommunity</groupId>
<artifactId>javarush-telegrambot</artifactId>
<version>0.5.0-SNAPSHOT</version>
<version>0.8.0-SNAPSHOT</version>
<name>Javarush-Telegrambot</name>
<description>Telegram bot for Javarush from community to community</description>
<url/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;


import org.springframework.scheduling.annotation.EnableScheduling;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;

@EnableScheduling
@SpringBootApplication
@AutoConfigurationPackage

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import com.githab.javarushcommunity.javarush_telegrambot.command.CommandContainer;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClientIml;
import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService;
import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubServiceIml;
import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageImpl;
import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserServiceIml;
import com.githab.javarushcommunity.javarush_telegrambot.service.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.util.List;

import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.NO;


Expand All @@ -26,8 +26,10 @@ public class JavaRushTelegramBot extends TelegramLongPollingBot {

public final String COMMAND_PREFIX="/";

public JavaRushTelegramBot(TelegramUserServiceIml telegramUserServiceIml, GroupSubService groupSubServiceIml, JavaRushGroupClientIml javaRushGroupClient){
this.commandContainer=new CommandContainer(new SendBotMessageImpl(this),telegramUserServiceIml,javaRushGroupClient,groupSubServiceIml);
public JavaRushTelegramBot(TelegramUserServiceIml telegramUserServiceIml, GroupSubService groupSubServiceIml,
JavaRushGroupClientIml javaRushGroupClient, @Value("#{'${bot.admins}'.split('.')}") List<String> admins, StatisticsService statisticsService){
this.commandContainer=new CommandContainer(new SendBotMessageImpl(this),telegramUserServiceIml,
javaRushGroupClient,groupSubServiceIml,admins,statisticsService);

}

Expand All @@ -40,9 +42,9 @@ public void onUpdateReceived(Update update){

if (message.startsWith(COMMAND_PREFIX)) {
String commandIdentifier = message.split(" ")[0].toLowerCase();
commandContainer.retrieveCommand(commandIdentifier).execute(update);
commandContainer.retrieveCommand(commandIdentifier,update.getMessage().getFrom().getUserName()).execute(update);
} else {
commandContainer.retrieveCommand(NO.getCommandName()).execute(update);
commandContainer.retrieveCommand(NO.getCommandName(),update.getMessage().getFrom().getUserName()).execute(update);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.githab.javarushcommunity.javarush_telegrambot.command;

import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;

import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.STAT;

public class AdminHelpCommand implements Command {

public static final String ADMIN_HELP_MESSAGE=String.format("<b> Доступные команды администратора</b>"
+"<b>Получить статистику</b>\n"
+"%s-статистика бота\n",STAT.getCommandName());

private final SendBotMessageService sendBotMessageService;

public AdminHelpCommand (SendBotMessageService sendBotMessageService){
this.sendBotMessageService=sendBotMessageService;
}
@Override
public void execute(Update update){
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),ADMIN_HELP_MESSAGE);
}

}
Original file line number Diff line number Diff line change
@@ -1,30 +1,54 @@
package com.githab.javarushcommunity.javarush_telegrambot.command;

import com.githab.javarushcommunity.javarush_telegrambot.command.annotation.AdminCommand;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.JavaRushGroupClient;
import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService;
import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService;
import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService;
import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService;
import com.google.common.collect.ImmutableMap;
import org.apache.http.conn.params.ConnConnectionParamBean;
import org.glassfish.grizzly.Connection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.*;
import static java.util.Objects.nonNull;

public class CommandContainer {
public final ImmutableMap<String, Command> commandMap ;
public final Command unknownCommand;
public CommandContainer(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService, JavaRushGroupClient javaRushGroupClient, GroupSubService groupSubService) {
private final List<String> admins;
public CommandContainer(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService,
JavaRushGroupClient javaRushGroupClient, GroupSubService groupSubService, List<String> admins, StatisticsService statisticsService) {
commandMap= ImmutableMap.<String, Command>builder().put(START.getCommandName(),new StartCommand(sendBotMessageService,telegramUserService))
.put(HELP.getCommandName(),new HelpCommand(sendBotMessageService))
.put(NO.getCommandName(),new NoCommand(sendBotMessageService))
.put(STOP.getCommandName(),new StopCommand(sendBotMessageService,telegramUserService))
.put(STAT.getCommandName(),new StatCommand(sendBotMessageService,telegramUserService))
.put(STAT.getCommandName(),new StatCommand(sendBotMessageService,statisticsService))
.put(ADD_GROUP_SUB.getCommandName(), new AddGroupSubCommand(sendBotMessageService,javaRushGroupClient,groupSubService))
.put(LIST_GROUP_SUB.getCommandName(),new ListGroupSubCommand(sendBotMessageService,telegramUserService)).build();
.put(LIST_GROUP_SUB.getCommandName(),new ListGroupSubCommand(sendBotMessageService,telegramUserService))
.put(DELETE_GROUP_SUB.getCommandName(),new DeleteGroupSubCommand(sendBotMessageService,telegramUserService,groupSubService))
.put(ADMIN_HELP.getCommandName(),new AdminHelpCommand(sendBotMessageService)).build();
unknownCommand=new UnknownCommand(sendBotMessageService);
this.admins=admins;
}

public Command retrieveCommand(String commandIdentifier,String username) {
Command orDefault = commandMap.getOrDefault(commandIdentifier, unknownCommand);
if (isAdminCommand(orDefault)) {
if (admins.contains(username)) {
return orDefault;
} else {
return unknownCommand;
}

}
return orDefault;
}
public Command retrieveCommand(String commandIdentifier){
return commandMap.getOrDefault(commandIdentifier,unknownCommand);
private boolean isAdminCommand (Command command){
return nonNull(command.getClass().getAnnotation(AdminCommand.class));
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ public enum CommandName {
NO(""),
STAT("/stat"),
ADD_GROUP_SUB("/addgroupsub"),
LIST_GROUP_SUB("/listgroupsub");
LIST_GROUP_SUB("/listgroupsub"),
DELETE_GROUP_SUB("/deletegroupsub"),
ADMIN_HELP("/ahelp");
private final String commandName;
CommandName (String commandName){
this.commandName=commandName;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.githab.javarushcommunity.javarush_telegrambot.command;

import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.GroupSub;
import com.githab.javarushcommunity.javarush_telegrambot.repository.entity.TelegramUser;
import com.githab.javarushcommunity.javarush_telegrambot.service.GroupSubService;
import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService;
import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService;
import jakarta.ws.rs.NotFoundException;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


import static com.githab.javarushcommunity.javarush_telegrambot.command.CommandName.DELETE_GROUP_SUB;
import static org.apache.commons.lang3.StringUtils.SPACE;
import static org.apache.commons.lang3.StringUtils.isNumeric;

public class DeleteGroupSubCommand implements Command{

private final SendBotMessageService sendBotMessageService;
private final TelegramUserService telegramUserService;
private final GroupSubService groupSubService;

public DeleteGroupSubCommand(SendBotMessageService sendBotMessageService,
TelegramUserService telegramUserService, GroupSubService groupSubService) {
this.sendBotMessageService = sendBotMessageService;
this.telegramUserService = telegramUserService;
this.groupSubService = groupSubService;
}



@Override
public void execute(Update update) {
if (update.getMessage().getText().equalsIgnoreCase(DELETE_GROUP_SUB.getCommandName())) {
sendGroupIdList(String.valueOf(update.getMessage().getChatId()));
return;
}
String groupId = update.getMessage().getText().split(SPACE)[1];
String chatId = String.valueOf(update.getMessage().getChatId());

if (isNumeric(groupId)) {
Optional<GroupSub> optionalGroupSub = groupSubService.findById(Integer.valueOf(groupId));
if (optionalGroupSub.isPresent()) {
GroupSub groupSub = optionalGroupSub.get();
TelegramUser telegramUser = telegramUserService.findByChatId(chatId).orElseThrow(NotFoundException::new);
groupSub.getUsers().remove(telegramUser);
groupSubService.save(groupSub);
sendBotMessageService.sendMessage(chatId, String.format("Удалил подписку на группу: %s", groupSub.getTitle()));

} else {
sendBotMessageService.sendMessage(chatId, "Не нашел такой группы =/");
}

} else {
sendBotMessageService.sendMessage(chatId, "неправильный формат ID группы");

}
}
private void sendGroupIdList (String chatId){
String message;
List<GroupSub> groupSubs=telegramUserService.findByChatId(chatId).orElseThrow(NotFoundException::new)
.getGroupSubs();
if (CollectionUtils.isEmpty(groupSubs)){
message="Пока нет подписки на группы";

}else {
message="Чтобы удалить подписку передай - команду вместе с ID \n\n"+
"имя группы - ID группы \n\n"+
"%s";

}
String userGroupSubData=groupSubs.stream().map(group->String.format("%s - %s",group.getTitle(),group.getId()))
.collect(Collectors.joining());
sendBotMessageService.sendMessage(chatId,String.format(message,userGroupSubData));
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,46 @@
package com.githab.javarushcommunity.javarush_telegrambot.command;

import com.githab.javarushcommunity.javarush_telegrambot.command.annotation.AdminCommand;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.StatisticDTO;
import com.githab.javarushcommunity.javarush_telegrambot.service.SendBotMessageService;
import com.githab.javarushcommunity.javarush_telegrambot.service.TelegramUserService;
import com.githab.javarushcommunity.javarush_telegrambot.service.StatisticsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.telegram.telegrambots.meta.api.objects.Update;


import java.util.stream.Collectors;



@AdminCommand
public class StatCommand implements Command{
private final SendBotMessageService sendBotMessageService;
private final TelegramUserService telegramUserService;
private final StatisticsService statisticsService;

public final static String STAT_MESSAGE="✨Подготовил статистику✨\n" +
"- Количество активных пользователей: %s\n" +
"- Количество неактивных пользователей: %s\n" +
"- Среднее количество групп на одного пользователя: %s\n\n" +
"Информация по активным группам:\n" +
"%s";

public final static String STAT_MESSAGE="JavaRush Telegram Bot використовує %s людей.";
@Autowired
public StatCommand(SendBotMessageService sendBotMessageService,TelegramUserService telegramUserService){
public StatCommand(SendBotMessageService sendBotMessageService,StatisticsService statisticsService){
this.sendBotMessageService=sendBotMessageService;
this.telegramUserService=telegramUserService;
this.statisticsService=statisticsService;
}
@Override
public void execute(Update update) {
int activeUserCount=telegramUserService.retrieveAllActiveUser().size();
sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),String.format(STAT_MESSAGE,activeUserCount));
StatisticDTO statisticDTO=statisticsService.countBotStatistic();
String collectedGroups=statisticDTO.getGroupStatDTOs().stream()
.map(it->String.format("%s (id=%s)-%s подписчиков",it.getTitle(),it.getId(),it.getActiveUserCount()))
.collect(Collectors.joining("\n"));

sendBotMessageService.sendMessage(update.getMessage().getChatId().toString(),String.format(STAT_MESSAGE,
statisticDTO.getActiveUserCount(),
statisticDTO.getInactiveUserCount(),
statisticDTO.getAverageGroupCountByUser(),
collectedGroups));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.githab.javarushcommunity.javarush_telegrambot.command.annotation;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)

public @interface AdminCommand {
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public interface JavaRushGroupClient {
Integer getGroupCount(GroupCountRequestArgs countRequestArgs);

GroupDiscussionInfo getGroupById(Integer id);
Integer findLastArticle(Integer groupSub);


}
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
package com.githab.javarushcommunity.javarush_telegrambot.javarushclient;

import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupCountRequestArgs;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupDiscussionInfo;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupInfo;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.GroupRequestArgs;
import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.*;
import kong.unirest.GenericType;
import kong.unirest.Unirest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

import static org.springframework.util.CollectionUtils.isEmpty;

@Component
public class JavaRushGroupClientIml implements JavaRushGroupClient {

private String javarushApiGroupPath;
private String getJavarushApiPostPath;

public JavaRushGroupClientIml(@Value("${javarush.api.path}") String javarushApi){
this.javarushApiGroupPath=javarushApi+"/groups";
public JavaRushGroupClientIml(@Value("${javarush.api.path}") String javarushApi) {
this.javarushApiGroupPath = javarushApi + "/groups";
this.getJavarushApiPostPath = javarushApi + "/posts";
}
@Override
public List<GroupInfo> getGroupList(GroupRequestArgs requestArgs) {
Expand Down Expand Up @@ -45,4 +48,17 @@ public GroupDiscussionInfo getGroupById(Integer id) {
return Unirest.get(String.format("%s/group%s",javarushApiGroupPath,id.toString())).
asObject(GroupDiscussionInfo.class).getBody();
}


@Override
public Integer findLastArticle(Integer groupSubId) {
List<PostInfo> posts = Unirest.get(getJavarushApiPostPath)
.queryString("order", "NEW")
.queryString("groupKid", groupSubId.toString())
.queryString("limit", "1")
.asObject(new GenericType<List<PostInfo>>() {
})
.getBody();
return isEmpty(posts) ? 0 : Optional.ofNullable(posts.get(0)).map(PostInfo::getId).orElse(0);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.githab.javarushcommunity.javarush_telegrambot.javarushclient;

import com.githab.javarushcommunity.javarush_telegrambot.javarushclient.dto.PostInfo;

import java.util.List;

public interface JavaRushPostClient {

List<PostInfo> findNewPosts(Integer groupId, Integer lastPostId);
}
Loading