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 4 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,12 +59,10 @@ 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;
}

Expand All @@ -73,7 +75,7 @@ public void run(SlashCommandEvent command) {
return;
}

if (gitName == null) {
if (user.getGitName() == null) {
messageService.removeRole(user.getGuildId(), userId, newbieRoleName);
command.reply(Messages.REGISTRATION_COMPLETED).queue();
} else {
Expand All @@ -84,6 +86,20 @@ public void run(SlashCommandEvent command) {
userRepository.save(user);
}

private User getUser(String userId) {
Optional<User> userOptional = userRepository.findByUserId(userId);
if (userOptional.isEmpty()) {
messageService.addRoleToUser(guildId, userId, newbieRoleName);
User user = new User();
user.setUserId(userId);
user.setGuildId(guildId);
user.setDateRegistration(LocalDate.now());
return user;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we save the created user into db in such case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

User is saved a bit later, when he passes the registration and submits his GitHub username. But if it is more convenient, I can add that line here

Copy link

@lez-doit lez-doit Feb 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we save the data later, it's alright. However, I suppose it would be better to use getUser method only for getting some actual users from DB, and extract the logic of their creation somewhere else.

} else {
return userOptional.get();
}
}

private static void handleNoOption(SlashCommandEvent command, String gitName) {
if (gitName == null) {
command.reply(Messages.NOT_REGISTERED).queue();
Expand Down
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