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

fixed bot spamming, updated /register and /stat #320

Merged
merged 5 commits into from
Feb 12, 2024
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
1 change: 1 addition & 0 deletions bot/src/main/java/com/community/tools/model/Messages.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public class Messages {

public static final String WELCOME_MENTION =
"Greetings, %s! Use /register and provide your GitHub username to complete registration";
public static final String WELCOME_OLD_MENTION = "Greetings, %s! Haven't seen you in a while.";
public static final String GITHUB_ACCOUNT_NOT_FOUND =
"GitHub username you provided is incorrect. Check it and try again.";
public static final String REGISTRATION_COMPLETED =
Expand Down
23 changes: 16 additions & 7 deletions bot/src/main/java/com/community/tools/service/MessageListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import net.dv8tion.jda.api.entities.MessageType;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
Expand Down Expand Up @@ -39,13 +38,19 @@ public MessageListener(UserRepository userRepository,

@Override
public void memberJoin(GuildMemberJoinEvent event) {
if (event.getUser().isBot()) {
return;
}
String userId = event.getUser().getId();
String guildId = event.getGuild().getId();
if (resetUser(userId, guildId)) {
messageService.addRoleToUser(guildId, userId, newbieRoleName);
messageService.sendMessageToConversation(welcomeChannelName,
String.format(Messages.WELCOME_MENTION, event.getUser().getAsMention()));
} else {
messageService.sendMessageToConversation(welcomeChannelName,
String.format(Messages.WELCOME_OLD_MENTION, event.getUser().getAsMention()));
}
messageService.sendMessageToConversation(welcomeChannelName,
String.format(Messages.WELCOME_MENTION, event.getUser().getAsMention()));
}

@Override
Expand All @@ -58,12 +63,16 @@ public void commandReceived(SlashCommandEvent event) {
.run(event);
}

/**
* Receives and processes messages in guilds.
* Currently, there is no reaction from bot, as sending default message for any event
* leads to spamming.
*
* @param event received event from Discord
*/
@Override
public void guildMessageReceived(GuildMessageReceivedEvent event) {
if (event.getMessage().getType() != MessageType.GUILD_MEMBER_JOIN) {
messageService.sendMessageToConversation(event.getChannel().getName(),
Messages.DEFAULT_MESSAGE);
}

}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.community.tools.service.MessageService;
import com.community.tools.service.github.GitHubService;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
Expand All @@ -30,6 +31,9 @@ public class RegisterCommand extends Command {
@Value("${newbieRole}")
private String newbieRoleName;

@Value("${guild.id}")
private String guildId;

/**
* Basic constructor for the class, specifies command data and injects required beans.
*
Expand All @@ -55,33 +59,62 @@ public RegisterCommand(GitHubService gitHubService,
@Override
public void run(SlashCommandEvent command) {
String userId = command.getUser().getId();
User user = userRepository.findByUserId(userId)
.orElseThrow(() -> new RuntimeException("User with id = [" + userId + "] was not found"));
User user = getUser(userId);
Optional<OptionMapping> option = Optional.ofNullable(command.getOption(OPTION_NAME));
String gitName = user.getGitName();

if (option.isEmpty()) {
handleNoOption(command, gitName);
handleNoOption(command, user.getGitName());
return;
}

String username = option.get().getAsString();
if (!gitHubUserExists(username)) {
command.reply(Messages.GITHUB_ACCOUNT_NOT_FOUND).queue();
return;
}

updateUser(user, username);
sendReply(command, user.getGitName());
}

private User getUser(String userId) {
return userRepository.findByUserId(userId)
.orElseGet(() -> createNewUser(userId));
}

private User createNewUser(String userId) {
messageService.addRoleToUser(guildId, userId, newbieRoleName);
User user = new User();
user.setUserId(userId);
user.setGuildId(guildId);
user.setDateRegistration(LocalDate.now());
return user;
}

private boolean gitHubUserExists(String username) {
try {
gitHubService.getUserByLoginInGitHub(username);
return true;
} catch (IOException e) {
log.error("GitHub account with username {} was not found", username, e);
command.reply(Messages.GITHUB_ACCOUNT_NOT_FOUND).queue();
return;
return false;
}
}

private void updateUser(User user, String username) {
if (user.getGitName() == null) {
messageService.removeRole(user.getGuildId(), user.getUserId(), newbieRoleName);
}
user.setGitName(username);
userRepository.save(user);
}

private void sendReply(SlashCommandEvent command, String gitName) {
if (gitName == null) {
messageService.removeRole(user.getGuildId(), userId, newbieRoleName);
command.reply(Messages.REGISTRATION_COMPLETED).queue();
} else {
command.reply(Messages.USERNAME_UPDATED).queue();
}

user.setGitName(username);
userRepository.save(user);
}

private static void handleNoOption(SlashCommandEvent command, String gitName) {
Expand All @@ -92,4 +125,5 @@ private static void handleNoOption(SlashCommandEvent command, String gitName) {
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


Expand All @@ -15,6 +16,9 @@ public class StatCommand extends Command {

private final StatisticService statisticService;

@Value("${adminRole}")
private String adminRoleName;

public StatCommand(StatisticService statisticService) {
super(new CommandData("stat", "Receive stats"));
this.statisticService = statisticService;
Expand All @@ -32,7 +36,7 @@ public void run(SlashCommandEvent command) {
return;
}
List<Role> userRoles = member.getRoles();
boolean isAdmin = userRoles.stream().anyMatch(role -> role.getName().equals("admin"));
boolean isAdmin = userRoles.stream().anyMatch(role -> role.getName().equals(adminRoleName));

if (isAdmin) {
command.reply("Статистика генерируется.Пожалуйста подождите...").queue();
Expand Down
3 changes: 2 additions & 1 deletion bot/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ hallOfFameChannel = hall-of-fame
generalInformationChannel = test_3
welcomeChannel = welcome
newbieRole = newbie
adminRole = Admin
urlServer = ${URL_SERVER}

testModeSwitcher = false
Expand All @@ -70,4 +71,4 @@ spring.ai.openai.chat.options.response-format=text

#notification
text.channel=notifications
guild.id=${GUILD_ID}
guild.id=${GUILD_ID}
Loading