60 lines
1.8 KiB
Java
60 lines
1.8 KiB
Java
|
package cc.fascinated.bat.service;
|
||
|
|
||
|
import cc.fascinated.bat.model.Guild;
|
||
|
import cc.fascinated.bat.repository.GuildRepository;
|
||
|
import lombok.NonNull;
|
||
|
import lombok.extern.log4j.Log4j2;
|
||
|
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
|
||
|
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||
|
import org.springframework.stereotype.Service;
|
||
|
|
||
|
import java.util.Optional;
|
||
|
|
||
|
/**
|
||
|
* @author Fascinated (fascinated7)
|
||
|
*/
|
||
|
@Service @Log4j2
|
||
|
public class GuildService extends ListenerAdapter {
|
||
|
/**
|
||
|
* The guild repository to use
|
||
|
*/
|
||
|
private final GuildRepository guildRepository;
|
||
|
|
||
|
/**
|
||
|
* The discord service to use
|
||
|
*/
|
||
|
private final DiscordService discordService;
|
||
|
|
||
|
@Autowired
|
||
|
public GuildService(@NonNull GuildRepository guildRepository, @NonNull DiscordService discordService) {
|
||
|
this.guildRepository = guildRepository;
|
||
|
this.discordService = discordService;
|
||
|
|
||
|
discordService.getJda().addEventListener(this);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Gets a guild by its ID
|
||
|
*
|
||
|
* @param id The ID of the guild
|
||
|
* @return The guild
|
||
|
*/
|
||
|
public Guild getGuild(@NonNull String id) {
|
||
|
long start = System.currentTimeMillis();
|
||
|
Optional<Guild> optionalGuild = guildRepository.findById(id);
|
||
|
if (optionalGuild.isPresent()) {
|
||
|
return optionalGuild.get();
|
||
|
}
|
||
|
Guild guild = guildRepository.save(new Guild(id));
|
||
|
log.info("Created guild \"{}\" in {}ms", id, System.currentTimeMillis() - start);
|
||
|
return guild;
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public void onGuildJoin(GuildJoinEvent event) {
|
||
|
log.info("Joined guild \"{}\"", event.getGuild().getId());
|
||
|
getGuild(event.getGuild().getId()); // Ensure the guild is in the database
|
||
|
}
|
||
|
}
|