Add auto create voice channels

This commit is contained in:
Sebastien Clement 2021-02-18 14:48:58 +01:00
parent dbf4f43019
commit 2ddf973299
7 changed files with 272 additions and 146 deletions

View File

@ -5,11 +5,8 @@ import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.Tools.AntiSpam;
import net.Broken.Tools.*;
import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.Moderateur;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.EmbedBuilder;
@ -132,6 +129,8 @@ public class BotListener extends ListenerAdapter {
userStatsUtils.runningCounters.put(event.getMember().getId(), temp);
}
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.join(event.getChannelJoined());
}
}
@ -143,10 +142,11 @@ public class BotListener extends ListenerAdapter {
if (event.getGuild().getAudioManager().getConnectedChannel().getMembers().size() == 1) {
logger.debug("I'm alone, close audio connection.");
AudioM.getInstance(event.getGuild()).stop();
}
}
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.leave(event.getChannelLeft());
}
@Override

View File

@ -10,7 +10,7 @@ import java.util.List;
@Entity
public class GuildPreferenceEntity {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String guildId;
@ -32,9 +32,23 @@ public class GuildPreferenceEntity {
@ElementCollection
private List<String> visibleVoiceChanel;
private boolean autoVoice;
private String autoVoiceChannelID;
private String autoVoiceChannelTitle;
public GuildPreferenceEntity(String guildId, boolean antiSpam, boolean welcome, String welcomeMessage, String welcomeChanelID, boolean defaultRole, String defaultRoleId, boolean dailyMadame, ArrayList<String> visibleVoiceChanel) {
public GuildPreferenceEntity(String guildId,
boolean antiSpam,
boolean welcome,
String welcomeMessage,
String welcomeChanelID,
boolean defaultRole,
String defaultRoleId,
boolean dailyMadame,
ArrayList<String> visibleVoiceChanel,
boolean autoVoice,
String autoVoiceChannelID,
String autoVoiceChannelTitle) {
this.guildId = guildId;
this.antiSpam = antiSpam;
this.welcome = welcome;
@ -44,18 +58,22 @@ public class GuildPreferenceEntity {
this.defaultRoleId = defaultRoleId;
this.dailyMadame = dailyMadame;
this.visibleVoiceChanel = visibleVoiceChanel;
this.autoVoice = autoVoice;
this.autoVoiceChannelID = autoVoiceChannelID;
this.autoVoiceChannelTitle = autoVoiceChannelTitle;
}
public GuildPreferenceEntity(){}
public GuildPreferenceEntity() {
}
public static GuildPreferenceEntity getDefault(Guild guild){
public static GuildPreferenceEntity getDefault(Guild guild) {
ArrayList<String> voice = new ArrayList<>();
for(VoiceChannel voiceChannel : guild.getVoiceChannels()){
for (VoiceChannel voiceChannel : guild.getVoiceChannels()) {
voice.add(voiceChannel.getId());
}
return new GuildPreferenceEntity(guild.getId(), false, false, "Welcome to this awesome server @name! ", " ", false, " ", true, voice);
return new GuildPreferenceEntity(guild.getId(), false, false, "Welcome to this awesome server @name! ", " ", false, " ", true, voice, false, " ", " ");
}
public Integer getId() {
@ -137,4 +155,28 @@ public class GuildPreferenceEntity {
public void setVisibleVoiceChanel(List<String> visibleVoiceChanel) {
this.visibleVoiceChanel = visibleVoiceChanel;
}
public boolean isAutoVoice() {
return autoVoice;
}
public void setAutoVoice(boolean autoVoice) {
this.autoVoice = autoVoice;
}
public String getAutoVoiceChannelID() {
return autoVoiceChannelID;
}
public void setAutoVoiceChannelID(String autoVoiceChannelID) {
this.autoVoiceChannelID = autoVoiceChannelID;
}
public String getAutoVoiceChannelTitle() {
return autoVoiceChannelTitle;
}
public void setAutoVoiceChannelTitle(String autoVoiceChannelTitle) {
this.autoVoiceChannelTitle = autoVoiceChannelTitle;
}
}

View File

@ -6,6 +6,7 @@ import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class GetSettingsData {
public String description;
public String name;
public String id;
public TYPE type;
@ -15,8 +16,9 @@ public class GetSettingsData {
public GetSettingsData() {
}
public GetSettingsData(String name, String id, TYPE type, List<Value> values, String current) {
public GetSettingsData(String name, String description, String id, TYPE type, List<Value> values, String current) {
this.name = name;
this.description = description;
this.id = id;
this.type = type;
this.values = values;

View File

@ -0,0 +1,87 @@
package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.requests.RestAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.*;
import static net.Broken.MainBot.jda;
public class AutoVoiceChannel {
private static final HashMap<String, AutoVoiceChannel> INSTANCE_MAP = new HashMap<>();
private final Logger logger = LogManager.getLogger();
private final String guildID;
private final HashMap<Integer, String> createdChannels = new HashMap<>();
public static AutoVoiceChannel getInstance(Guild guild) {
if (INSTANCE_MAP.get(guild.getId()) == null) {
INSTANCE_MAP.put(guild.getId(), new AutoVoiceChannel(guild));
}
return INSTANCE_MAP.get(guild.getId());
}
public AutoVoiceChannel(Guild guild) {
this.guildID = guild.getId();
}
public void join(VoiceChannel voiceChannel) {
Guild guild = jda.getGuildById(guildID);
if (guild == null)
return;
GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(guild);
if ( pref.isAutoVoice() && voiceChannel.getId().equals(pref.getAutoVoiceChannelID())) {
logger.info("Creating new voice channel for Guild : " + guild.getName());
VoiceChannel newChannel = voiceChannel.createCopy().complete();
int next = getNextNumber();
String title = pref.getAutoVoiceChannelTitle();
title = title.replace("@count", Integer.toString(next));
newChannel.getManager().setName(title).queue();
createdChannels.put(next, newChannel.getId());
moveMembers(voiceChannel.getMembers(), newChannel);
}
}
public void leave(VoiceChannel voiceChannel) {
if (voiceChannel.getMembers().isEmpty()){
String id = voiceChannel.getId();
for(Map.Entry<Integer, String> entry : createdChannels.entrySet()) {
if (entry.getValue().equals(id)){
logger.info("Auto created channel is empty, deleting it ...");
voiceChannel.delete().reason("Auto-remove empty voice channel").queue();
}
}
}
}
private int getNextNumber() {
Set<Integer> keys = createdChannels.keySet();
for (int next = 1; next < 999; next++) {
if (!keys.contains(next))
return next;
}
return 999;
}
private void moveMembers(List<Member> members, VoiceChannel destination){
logger.debug("Moving Members to new voice channel...");
RestAction<Void> restAction = null;
for(Member member : members){
if (restAction == null)
restAction = destination.getGuild().moveVoiceMember(member, destination);
restAction = restAction.and(destination.getGuild().moveVoiceMember(member, destination));
}
if(restAction != null){
restAction.queue();
}
}
}

View File

@ -12,8 +12,6 @@ import java.net.URLConnection;
public class Redirection {
public Redirection(){
}
/**

View File

@ -3,38 +3,34 @@ package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.PendingPwdResetRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.Settings.GetSettingsData;
import net.Broken.RestApi.Data.Settings.PostSetSettings;
import net.Broken.RestApi.Data.Settings.Value;
import net.Broken.SpringContext;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.UserUtils;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SettingsUtils {
private static SettingsUtils INSTANCE;
private Logger logger = LogManager.getLogger();
private final Logger logger = LogManager.getLogger();
public static SettingsUtils getInstance(){
public static SettingsUtils getInstance() {
return (INSTANCE == null) ? new SettingsUtils() : INSTANCE;
}
private GuildPreferenceRepository guildPreferenceRepository;
private UserRepository userRepository;
private final GuildPreferenceRepository guildPreferenceRepository;
private final UserRepository userRepository;
private SettingsUtils() {
@ -45,28 +41,39 @@ public class SettingsUtils {
}
public ArrayList<GetSettingsData> extractSettings(Guild guild){
ArrayList<GetSettingsData> list = new ArrayList<>();
/**
* Extract all settings for displaying on webpage
*
* @param guild The guild
* @return All formatted settings
*/
public ArrayList<GetSettingsData> extractSettings(Guild guild) {
ArrayList<GetSettingsData> list = new ArrayList<>();
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
if (guildPrefList.isEmpty()) {
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
} else
guildPref = guildPrefList.get(0);
List<String> visibleVoice = new ArrayList<>(guildPref.getVisibleVoiceChanel());
if (visibleVoice.size() == 0) {
guildPref = setDefaultVoiceChannels(guild, guildPref);
}
list.add(new GetSettingsData(
"Visible Voices Channels",
null,
"voices_channels",
GetSettingsData.TYPE.SELECT_LIST,
getVoiceChanels(guild, guildPref),
getVoiceChannels(guild, visibleVoice),
null
));
list.add(new GetSettingsData(
"Enable Welcome Message",
null,
"welcome",
GetSettingsData.TYPE.BOOL,
null,
@ -74,6 +81,7 @@ public class SettingsUtils {
));
list.add(new GetSettingsData(
"Welcome Message chanel",
null,
"welcome_chanel_id",
GetSettingsData.TYPE.LIST,
getTextChannels(guild),
@ -81,6 +89,7 @@ public class SettingsUtils {
));
list.add(new GetSettingsData(
"Welcome Message",
null,
"welcome_message",
GetSettingsData.TYPE.STRING,
null,
@ -90,6 +99,7 @@ public class SettingsUtils {
list.add(new GetSettingsData(
"Enable Default Role",
null,
"default_role",
GetSettingsData.TYPE.BOOL,
null,
@ -97,15 +107,16 @@ public class SettingsUtils {
));
list.add(new GetSettingsData(
"Default Role",
null,
"default_role_id",
GetSettingsData.TYPE.LIST,
getRoles(guild),
guildPref.getDefaultRoleId()
));
list.add(new GetSettingsData(
"Enable Anti Spam",
null,
"anti_spam",
GetSettingsData.TYPE.BOOL,
null,
@ -114,38 +125,64 @@ public class SettingsUtils {
list.add(new GetSettingsData(
"Enable Daily Madame Message",
null,
"daily_madame",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isDailyMadame())
));
list.add(new GetSettingsData(
"Enable Auto Create Voice Chanel",
null,
"auto_voice",
GetSettingsData.TYPE.BOOL,
null,
Boolean.toString(guildPref.isAutoVoice())
));
list.add(new GetSettingsData(
"Base Voice Channel For Auto Create",
"If someone joint this channel, a new voice channel will be created with the same settings.",
"auto_voice_base_channel",
GetSettingsData.TYPE.LIST,
getVoiceChannels(guild, null),
guildPref.getAutoVoiceChannelID()
));
list.add(new GetSettingsData(
"Auto Created Voice Channel title",
"Auto created voice channel will use this title, @count will be replaced by the channel count.",
"auto_voice_channel_title",
GetSettingsData.TYPE.STRING,
null,
guildPref.getAutoVoiceChannelTitle()
));
return list;
}
public boolean checkPermission(String token, String guild){
if(token == null || guild == null){
/**
* Check if the user have the permission to set settings
*
* @param token User token
* @param guild Guild
* @return True if user have ADMINISTRATOR permission
*/
public boolean checkPermission(String token, String guild) {
if (token == null || guild == null) {
return false;
}
else{
} else {
try {
UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token);
User jdaUser = MainBot.jda.getUserById(user.getJdaId());
Guild jdaGuild = MainBot.jda.getGuildById(guild);
if(jdaGuild == null){
if (jdaGuild == null || jdaUser == null)
return false;
}
if(!jdaGuild.getMember(jdaUser).hasPermission(Permission.ADMINISTRATOR)){
Member guildUser = jdaGuild.getMember(jdaUser);
if (guildUser == null)
return false;
}
return true;
return guildUser.hasPermission(Permission.ADMINISTRATOR);
} catch (Exception e) {
logger.debug("Unknown Token or user :" + token);
return false;
@ -154,170 +191,131 @@ public class SettingsUtils {
}
public boolean setSettings(Guild guild, List<PostSetSettings> settings){
public boolean setSettings(Guild guild, List<PostSetSettings> settings) {
GuildPreferenceEntity pref = getPreference(guild);
for (PostSetSettings setting : settings){
for (PostSetSettings setting : settings) {
String value = setting.val;
logger.debug(setting.id + " : " + value);
switch (setting.id) {
case "voices_channels":
List<String> list = checkVoiceChanel(guild, setting.vals);
if(list == null){
if (list == null) {
logger.error("voices_channels error, bad ID.");
return false;
}
else{
} else
pref.setVisibleVoiceChanel(list);
}
break;
case "anti_spam":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setAntiSpam(result);
} else {
logger.error("anti_spam error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
boolean result_as = Boolean.parseBoolean(value);
pref.setAntiSpam(result_as);
break;
case "default_role":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setDefaultRole(result);
pref = guildPreferenceRepository.save(pref);
} else {
logger.error("default_role error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
boolean result_df = Boolean.parseBoolean(value);
pref.setDefaultRole(result_df);
pref = guildPreferenceRepository.save(pref);
break;
case "default_role_id":
try {
Role role = guild.getRoleById(value);
if (role != null) {
pref.setDefaultRoleId(role.getId());
pref = guildPreferenceRepository.save(pref);
} else {
} else
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
logger.error("default_role_id error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "welcome":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setWelcome(result);
} else {
logger.error("welcome error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
boolean result_w = Boolean.parseBoolean(value);
pref.setWelcome(result_w);
break;
case "welcome_chanel_id":
try {
TextChannel chanel = guild.getTextChannelById(value);
if (chanel != null) {
pref.setWelcomeChanelID(chanel.getId());
} else {
TextChannel channel = guild.getTextChannelById(value);
if (channel != null) {
pref.setWelcomeChanelID(channel.getId());
} else
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
logger.error("welcome_chanel_id error. Key: " + setting.id + " Val: " + setting.val);
return false;
}
break;
case "welcome_message":
pref.setWelcomeMessage(value);
break;
case "daily_madame":
if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) {
boolean result = Boolean.parseBoolean(value);
pref.setDailyMadame(result);
boolean result_dm = Boolean.parseBoolean(value);
pref.setDailyMadame(result_dm);
break;
} else {
logger.error("daily_madame error. Key: " + setting.id + " Val: " + setting.val);
case "auto_voice":
boolean result_av = Boolean.parseBoolean(value);
pref.setAutoVoice(result_av);
break;
case "auto_voice_base_channel":
VoiceChannel channel = guild.getVoiceChannelById(value);
if (channel == null) {
logger.error("voices_channels error, bad ID.");
return false;
}
} else
pref.setAutoVoiceChannelID(channel.getId());
break;
case "auto_voice_channel_title":
pref.setAutoVoiceChannelTitle(value);
break;
}
}
guildPreferenceRepository.save(pref);
return true;
}
private List<Value> getTextChannels(Guild guild){
private List<Value> getTextChannels(Guild guild) {
List<Value> channels = new ArrayList<>();
for(TextChannel channel : guild.getTextChannels()){
for (TextChannel channel : guild.getTextChannels()) {
channels.add(new Value(channel.getName(), channel.getId()));
}
return channels;
}
private List<Value> getRoles(Guild guild){
private List<Value> getRoles(Guild guild) {
List<Value> roles = new ArrayList<>();
for(Role role : guild.getRoles()){
for (Role role : guild.getRoles()) {
roles.add(new Value(role.getName(), role.getId()));
}
return roles;
}
private List<Value> getVoiceChanels(Guild guild, GuildPreferenceEntity guildPref){
List<String> prefVoice = new ArrayList<>(guildPref.getVisibleVoiceChanel());
if(prefVoice.size() == 0){
guildPref = setDefaultVoiceChanels(guild, guildPref);
private List<Value> getVoiceChannels(Guild guild, List<String> selected) {
List<Value> channels = new ArrayList<>();
for (VoiceChannel voiceChannel : guild.getVoiceChannels()) {
if (selected == null)
channels.add(new Value(voiceChannel.getName(), voiceChannel.getId()));
else
channels.add(new Value(voiceChannel.getName(), voiceChannel.getId(), selected.contains(voiceChannel.getId())));
}
List<Value> chanels = new ArrayList<>();
for(VoiceChannel voiceChannel : guild.getVoiceChannels()){
chanels.add(new Value(voiceChannel.getName(), voiceChannel.getId(), prefVoice.contains(voiceChannel.getId())));
prefVoice.remove(voiceChannel.getId());
}
if(prefVoice.size() != 0){
List<String> edit = guildPref.getVisibleVoiceChanel();
for(String prefVoiceItem : prefVoice){
edit.remove(prefVoiceItem);
}
guildPref.setVisibleVoiceChanel(edit);
guildPreferenceRepository.save(guildPref);
}
return chanels;
return channels;
}
private List<String> checkVoiceChanel(Guild guild, List<String> values){
private List<String> checkVoiceChanel(Guild guild, List<String> values) {
List<String> list = new ArrayList<>();
for(String value : values){
for (String value : values) {
if (guild.getVoiceChannelById(value) != null) {
list.add(value);
} else {
logger.error("Unknown voice chanel id: " + value);
logger.error("Unknown voice channel id: " + value);
list = null;
break;
}
@ -325,10 +323,10 @@ public class SettingsUtils {
return list;
}
public GuildPreferenceEntity cleanVoicePref(Guild guild, GuildPreferenceEntity guildPref){
public GuildPreferenceEntity cleanVisibleVoicePref(Guild guild, GuildPreferenceEntity guildPref) {
List<String> voice = guildPref.getVisibleVoiceChanel();
for(String prefVoice : guildPref.getVisibleVoiceChanel()){
if(guild.getVoiceChannelById(prefVoice) == null)
for (String prefVoice : guildPref.getVisibleVoiceChanel()) {
if (guild.getVoiceChannelById(prefVoice) == null)
voice.remove(prefVoice);
}
guildPref.setVisibleVoiceChanel(voice);
@ -336,11 +334,11 @@ public class SettingsUtils {
}
public GuildPreferenceEntity setDefaultVoiceChanels(Guild guild, GuildPreferenceEntity guildPref){
public GuildPreferenceEntity setDefaultVoiceChannels(Guild guild, GuildPreferenceEntity guildPref) {
List<String> prefVoice = guildPref.getVisibleVoiceChanel();
if(prefVoice == null)
if (prefVoice == null)
prefVoice = new ArrayList<>();
for(VoiceChannel voiceChannel : guild.getVoiceChannels()){
for (VoiceChannel voiceChannel : guild.getVoiceChannels()) {
prefVoice.add(voiceChannel.getId());
}
guildPref.setVisibleVoiceChanel(prefVoice);
@ -348,15 +346,14 @@ public class SettingsUtils {
}
public GuildPreferenceEntity getPreference(Guild guild){
public GuildPreferenceEntity getPreference(Guild guild) {
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
if (guildPrefList.isEmpty()) {
logger.info("Generate default pref for " + guild.getName());
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
} else
guildPref = guildPrefList.get(0);
return guildPref;
}

View File

@ -31,7 +31,7 @@ public class GetVoiceChanels {
List<String> chanels = pref.getVisibleVoiceChanel();
if(chanels == null || chanels.size() == 0){
pref = settingsUtils.setDefaultVoiceChanels(guild, pref);
pref = settingsUtils.setDefaultVoiceChannels(guild, pref);
chanels = pref.getVisibleVoiceChanel();
}
@ -46,7 +46,7 @@ public class GetVoiceChanels {
if(needClean){
logger.debug("Need Clean.");
settingsUtils.cleanVoicePref(guild, pref);
settingsUtils.cleanVisibleVoicePref(guild, pref);
}