Skip to content

Commit

Permalink
New Update
Browse files Browse the repository at this point in the history
1. Fix
  • Loading branch information
megoRU committed Aug 23, 2024
1 parent 42f9f5d commit 5374924
Show file tree
Hide file tree
Showing 12 changed files with 124 additions and 167 deletions.
33 changes: 19 additions & 14 deletions src/main/java/main/controller/UpdateController.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;

@Getter
@Component
Expand All @@ -35,7 +36,7 @@ public class UpdateController {
private final GiveawayRepositoryService giveawayRepositoryService;

//LOGGER
private final static Logger LOGGER = Logger.getLogger(UpdateController.class.getName());
private final static Logger LOGGER = LoggerFactory.getLogger(UpdateController.class.getName());

//CORE
private CoreBot coreBot;
Expand Down Expand Up @@ -64,16 +65,20 @@ public void processEvent(Object event) {
}

private void distributeEventsByType(Object event) {
if (event instanceof SlashCommandInteractionEvent) {
slashEvent((SlashCommandInteractionEvent) event);
} else if (event instanceof ButtonInteractionEvent) {
buttonEvent((ButtonInteractionEvent) event);
} else if (event instanceof GuildJoinEvent) {
joinEvent((GuildJoinEvent) event);
} else if (event instanceof MessageReactionAddEvent) {
reactionEvent((MessageReactionAddEvent) event);
} else if (event instanceof GuildLeaveEvent) {
leaveEvent((GuildLeaveEvent) event);
if (event instanceof SlashCommandInteractionEvent slashCommandInteractionEvent) {
LOGGER.info(slashCommandInteractionEvent.getName());
slashEvent(slashCommandInteractionEvent);
} else if (event instanceof ButtonInteractionEvent buttonInteractionEvent) {
LOGGER.info(buttonInteractionEvent.getInteraction().getButton().getLabel());
buttonEvent(buttonInteractionEvent);
} else if (event instanceof GuildJoinEvent guildJoinEvent) {
joinEvent(guildJoinEvent);
} else if (event instanceof MessageReactionAddEvent messageReactionAddEvent) {
LOGGER.info(messageReactionAddEvent.getMessageAuthorId());
reactionEvent(messageReactionAddEvent);
} else if (event instanceof GuildLeaveEvent guildLeaveEvent) {
LOGGER.info(guildLeaveEvent.getGuild().getId());
leaveEvent(guildLeaveEvent);
}
}

Expand Down Expand Up @@ -136,8 +141,8 @@ private void slashEvent(@NotNull SlashCommandInteractionEvent event) {
cancelCommand.cancel(event);
}
case "check-bot-permission" -> {
CheckBot checkBot = new CheckBot();
checkBot.check(event);
CheckPermissions checkPermissions = new CheckPermissions();
checkPermissions.check(event);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import java.util.Objects;

@Service
public class CheckBot {
public class CheckPermissions {

private static final JSONParsers jsonParsers = new JSONParsers();

Expand Down
42 changes: 12 additions & 30 deletions src/main/java/main/core/events/HelpCommand.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package main.core.events;

import main.config.BotStart;
import main.jsonparser.JSONParsers;
import main.model.entity.Settings;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -40,18 +37,18 @@ public void help(@NotNull SlashCommandInteractionEvent event) {
info.setTitle("Giveaway");
info.addField("Slash Commands",
String.format("""
</start:941286272390037535> - %s
</stop:941286272390037536> - %s
</scheduling:1102283573349851166> - %s
</cancel:1102283573349851167> - %s
</reroll:957624805446799452> - %s
</predefined:1049647289779630080> - %s
</list:941286272390037538> - %s
</settings:1204911821056905277> - %s
</participants:952572018077892638> - %s
</check-bot-permission:1009065886335914054> - %s
</change:1027901550456225842> - %s
""",
</start:941286272390037535> - %s
</stop:941286272390037536> - %s
</scheduling:1102283573349851166> - %s
</cancel:1102283573349851167> - %s
</reroll:957624805446799452> - %s
</predefined:1049647289779630080> - %s
</list:941286272390037538> - %s
</settings:1204911821056905277> - %s
</participants:952572018077892638> - %s
</check-bot-permission:1009065886335914054> - %s
</change:1027901550456225842> - %s
""",
helpStart,
helpStop,
helpScheduling,
Expand All @@ -72,21 +69,6 @@ public void help(@NotNull SlashCommandInteractionEvent event) {
List<Button> buttons = new ArrayList<>();
buttons.add(Button.link("https://discord.gg/UrWG3R683d", "Support"));

Settings settings = BotStart.getMapLanguages().get(guildId);

if (settings != null) {
if (settings.getLanguage().equals("eng")) {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Сменить язык ")
.withEmoji(Emoji.fromUnicode("U+1F1F7U+1F1FA")));
} else {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Change language ")
.withEmoji(Emoji.fromUnicode("U+1F1ECU+1F1E7")));
}
} else {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Сменить язык ")
.withEmoji(Emoji.fromUnicode("U+1F1F7U+1F1FA")));
}

event.replyEmbeds(info.build()).setEphemeral(true).addActionRow(buttons).queue();
}
}
82 changes: 26 additions & 56 deletions src/main/java/main/core/events/JoinEvent.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package main.core.events;

import main.config.BotStart;
import main.model.entity.Settings;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.unions.DefaultGuildChannelUnion;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import org.jetbrains.annotations.NotNull;
Expand All @@ -21,61 +19,33 @@
public class JoinEvent {

public void join(@NotNull GuildJoinEvent event) {
try {
String guildId = event.getGuild().getId();
Settings settings = BotStart.getMapLanguages().get(Long.parseLong(guildId));

EmbedBuilder welcome = new EmbedBuilder();
welcome.setColor(Color.GREEN);
welcome.addField("Giveaway", "Thanks for adding " + "**" + "Giveaway" + "** " + "bot to " + event.getGuild().getName() + "!\n", false);
welcome.addField("Setup Bot Language", "Use: </settings:1204911821056905277>", false);
welcome.addField("Create Giveaway", "Use: </start:941286272390037535>", false);
welcome.addField("Create predefined Giveaway", "Use: </predefined:1049647289779630080> (Only Administrators)", false);
welcome.addField("Reroll Winner", "Use: </reroll:957624805446799452>", false);
welcome.addField("Stop Giveaway manually", "Use: </stop:941286272390037536> (Only Administrators)", false);
welcome.addField("List of commands", "Use: </help:941286272390037537>", false);
welcome.addField("Support server", ":helmet_with_cross: [Discord server](https://discord.com/invite/UrWG3R683d)\n", false);
welcome.addField("Information", "Our bot supports recovery of any Giveaway, upon request in support. " +
"Also, the bot automatically checks the lists of participants, even if the bot is turned off or there are problems in recording while working, " +
"it will automatically restore everything. This gives a 100% guarantee that each participant will be recorded.", false);

List<Button> buttons = new ArrayList<>();
buttons.add(Button.link("https://discord.gg/UrWG3R683d", "Support"));
buttons.add(Button.link("https://patreon.com/ghbots", "Patreon"));

if (settings != null) {
if (settings.getLanguage().equals("eng")) {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Сменить язык ")
.withEmoji(Emoji.fromUnicode("U+1F1F7U+1F1FA")));
} else {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Change language ")
.withEmoji(Emoji.fromUnicode("U+1F1ECU+1F1E7")));
}
} else {
buttons.add(Button.secondary(guildId + ":" + ButtonChangeLanguage.CHANGE_LANGUAGE, "Сменить язык ")
.withEmoji(Emoji.fromUnicode("U+1F1F7U+1F1FA")));
}

DefaultGuildChannelUnion defaultChannel = event.getGuild().getDefaultChannel();

if (defaultChannel != null) {
if (defaultChannel.getType() == ChannelType.TEXT) {
TextChannel textChannel = defaultChannel.asTextChannel();
if (event.getGuild().getSelfMember().hasPermission(textChannel,
Permission.MESSAGE_SEND,
Permission.VIEW_CHANNEL,
Permission.MESSAGE_EMBED_LINKS)) {
defaultChannel
.asTextChannel()
.sendMessageEmbeds(welcome.build())
.setActionRow(buttons)
.queue();
}
Member selfMember = event.getGuild().getSelfMember();
EmbedBuilder welcome = new EmbedBuilder();
welcome.setColor(Color.GREEN);
welcome.addField("Giveaway", "Thanks for adding " + "**" + "Giveaway" + "** " + "bot to " + event.getGuild().getName() + "!\n", false);
welcome.addField("Setup Bot Language", "Use: </settings:1204911821056905277>", false);
welcome.addField("Create Giveaway", "Use: </start:941286272390037535>", false);
welcome.addField("Create predefined Giveaway", "Use: </predefined:1049647289779630080> (Only Administrators)", false);
welcome.addField("Reroll Winner", "Use: </reroll:957624805446799452>", false);
welcome.addField("Stop Giveaway manually", "Use: </stop:941286272390037536> (Only Administrators)", false);
welcome.addField("List of commands", "Use: </help:941286272390037537>", false);
welcome.addField("Support server", ":helmet_with_cross: [Discord server](https://discord.com/invite/UrWG3R683d)\n", false);
welcome.addField("Information", "Our bot supports recovery of any Giveaway, upon request in support. " +
"Also, the bot automatically checks the lists of participants, even if the bot is turned off or there are problems in recording while working, " +
"it will automatically restore everything. This gives a 100% guarantee that each participant will be recorded.", false);

List<Button> buttons = new ArrayList<>();
buttons.add(Button.link("https://discord.gg/UrWG3R683d", "Support"));

DefaultGuildChannelUnion defaultChannel = event.getGuild().getDefaultChannel();

if (defaultChannel != null) {
if (defaultChannel.getType() == ChannelType.TEXT) {
TextChannel textChannel = defaultChannel.asTextChannel();
if (selfMember.hasPermission(textChannel, Permission.MESSAGE_SEND, Permission.VIEW_CHANNEL, Permission.MESSAGE_EMBED_LINKS)) {
textChannel.sendMessageEmbeds(welcome.build()).setActionRow(buttons).queue();
}
}
} catch (Exception e) {
System.out.println("Скорее всего нет `DefaultChannel`!");
e.printStackTrace();
}
}
}
5 changes: 4 additions & 1 deletion src/main/java/main/core/events/LeaveEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
import main.model.repository.SchedulingRepository;
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LeaveEvent {

private final static Logger LOGGER = LoggerFactory.getLogger(LeaveEvent.class.getName());
private final ActiveGiveawayRepository activeGiveawayRepository;
private final SchedulingRepository schedulingRepository;

Expand All @@ -26,7 +29,7 @@ public void leave(@NotNull GuildLeaveEvent event) {
activeGiveawayRepository.deleteById(event.getGuild().getIdLong());
schedulingRepository.deleteById(event.getGuild().getIdLong());
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage(), e);
}
}
}
58 changes: 24 additions & 34 deletions src/main/java/main/core/events/ParticipantsCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,64 +2,54 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import main.giveaway.Exceptions;
import lombok.AllArgsConstructor;
import main.jsonparser.JSONParsers;
import main.model.entity.ListUsers;
import main.model.repository.ListUsersRepository;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.utils.FileUpload;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
public class ParticipantsCommand {

private final ListUsersRepository listUsersRepository;

private static final JSONParsers jsonParsers = new JSONParsers();

@Autowired
public ParticipantsCommand(ListUsersRepository listUsersRepository) {
this.listUsersRepository = listUsersRepository;
}
private final ListUsersRepository listUsersRepository;

public void participants(@NotNull SlashCommandInteractionEvent event) {
var userIdLong = event.getUser().getIdLong();
var guildId = Objects.requireNonNull(event.getGuild()).getIdLong();

event.deferReply().setEphemeral(true).queue();
String id = event.getOption("giveaway_id", OptionMapping::getAsString);
try {
if (id != null) {
File file = new File("participants.json");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
List<ListUsers> listUsers = listUsersRepository.findAllByGiveawayIdAndCreatedUserId(Long.parseLong(id), userIdLong);
if (listUsers.isEmpty()) {
String noAccessReroll = jsonParsers.getLocale("no_access_reroll", guildId);
event.getHook().sendMessage(noAccessReroll).setEphemeral(true).queue();
return;
}
String json = gson.toJson(listUsers);
// Создание объекта FileWriter
FileWriter writer = new FileWriter(file);
// Запись содержимого в файл
writer.write(json);
writer.flush();
writer.close();
FileUpload fileUpload = FileUpload.fromData(file);
event.getHook().sendFiles(fileUpload).setEphemeral(true).queue();
} else {
event.getHook().sendMessage("Options is null").setEphemeral(true).queue();

if (id != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
List<ListUsers> listUsers = listUsersRepository.findAllByGiveawayIdAndCreatedUserId(Long.parseLong(id), userIdLong);
if (listUsers.isEmpty()) {
String noAccessReroll = jsonParsers.getLocale("no_access_reroll", guildId);
event.getHook().sendMessage(noAccessReroll).setEphemeral(true).queue();
return;
}
} catch (Exception exception) {
Exceptions.handle(exception, event.getHook());
String json = gson.toJson(listUsers);
InputStream inputStream = getInputStream(json);
FileUpload fileUpload = FileUpload.fromData(inputStream, "participants.json");
event.getHook().sendFiles(fileUpload).setEphemeral(true).queue();
} else {
event.getHook().sendMessage("Options is null").setEphemeral(true).queue();
}
}

private InputStream getInputStream(@NotNull String text) {
return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
}
}
10 changes: 5 additions & 5 deletions src/main/java/main/core/events/StartCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,23 @@
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;


@Service
public class StartCommand {

private final static Logger LOGGER = LoggerFactory.getLogger(StartCommand.class.getName());
private final ActiveGiveawayRepository activeGiveawayRepository;
private final SchedulingRepository schedulingRepository;
private final GiveawayRepositoryService giveawayRepositoryService;
private final static Logger LOGGER = Logger.getLogger(StartCommand.class.getName());

private static final JSONParsers jsonParsers = new JSONParsers();

Expand Down Expand Up @@ -173,8 +174,7 @@ public void start(@NotNull SlashCommandInteractionEvent event, UpdateController
minParticipants);

} catch (Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);

LOGGER.error(e.getMessage(), e);
String slashErrors = jsonParsers.getLocale("slash_errors", guildId);
errors.setDescription(slashErrors);
if (event.isAcknowledged()) event.getHook().editOriginalEmbeds(errors.build()).queue();
Expand Down
Loading

0 comments on commit 5374924

Please sign in to comment.