use of net.dv8tion.jda.core.entities.VoiceChannel in project FredBoat by Frederikam.
the class MusicPersistenceHandler method reloadPlaylists.
private void reloadPlaylists(JDA jda) {
File dir = new File("music_persistence");
if (appConfig.isMusicDistribution()) {
log.warn("Music persistence loading is disabled on the MUSIC distribution! Use PATRON or DEVELOPMENT instead" + "How did this call end up in here anyways?");
return;
}
log.info("Began reloading playlists for shard {}", jda.getShardInfo().getShardId());
if (!dir.exists()) {
log.info("No music persistence directory found.");
return;
}
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
log.info("No files present in music persistence directory");
return;
}
for (File file : files) {
try {
Guild guild = jda.getGuildById(file.getName());
if (guild == null) {
// only load guilds that are part of this shard
continue;
}
JSONObject data = new JSONObject(FileUtils.readFileToString(file, Charset.forName("UTF-8")));
boolean isPaused = data.getBoolean("isPaused");
final JSONArray sources = data.getJSONArray("sources");
@Nullable VoiceChannel vc = jda.getVoiceChannelById(data.getString("vc"));
@Nullable TextChannel tc = jda.getTextChannelById(data.getString("tc"));
float volume = Float.parseFloat(data.getString("volume"));
RepeatMode repeatMode = data.getEnum(RepeatMode.class, "repeatMode");
boolean shuffle = data.getBoolean("shuffle");
GuildPlayer player = playerRegistry.getOrCreate(guild);
if (tc != null) {
musicTextChannelProvider.setMusicChannel(tc);
}
if (appConfig.getDistribution().volumeSupported()) {
player.setVolume(volume);
}
player.setRepeatMode(repeatMode);
player.setShuffle(shuffle);
final boolean[] isFirst = { true };
List<AudioTrackContext> tracks = new ArrayList<>();
sources.forEach((Object t) -> {
JSONObject json = (JSONObject) t;
byte[] message = Base64.decodeBase64(json.getString("message"));
Member member = guild.getMemberById(json.getLong("user"));
if (member == null)
// member left the guild meanwhile, set ourselves as the one who added the song
member = guild.getSelfMember();
AudioTrack at;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(message);
at = audioPlayerManager.decodeTrack(new MessageInput(bais)).decodedTrack;
} catch (IOException e) {
throw new RuntimeException(e);
}
if (at == null) {
log.error("Loaded track that was null! Skipping...");
return;
}
// Handle split tracks
AudioTrackContext atc;
JSONObject split = json.optJSONObject("split");
if (split != null) {
atc = new SplitAudioTrackContext(jdaEntityProvider, at, member, split.getLong("startPos"), split.getLong("endPos"), split.getString("title"));
at.setPosition(split.getLong("startPos"));
if (isFirst[0]) {
isFirst[0] = false;
if (data.has("position")) {
at.setPosition(split.getLong("startPos") + data.getLong("position"));
}
}
} else {
atc = new AudioTrackContext(jdaEntityProvider, at, member);
if (isFirst[0]) {
isFirst[0] = false;
if (data.has("position")) {
at.setPosition(data.getLong("position"));
}
}
}
tracks.add(atc);
});
player.loadAll(tracks);
if (!isPaused) {
if (vc != null) {
try {
player.joinChannel(vc);
player.play();
} catch (Exception ignored) {
}
}
if (tc != null) {
CentralMessaging.message(tc, MessageFormat.format(I18n.get(guild).getString("reloadSuccess"), sources.length())).send(null);
}
}
} catch (Exception ex) {
log.error("Error when loading persistence file", ex);
}
boolean deleted = file.delete();
log.info(deleted ? "Deleted persistence file: " + file : "Failed to delete persistence file: " + file);
}
}
use of net.dv8tion.jda.core.entities.VoiceChannel in project FredBoat by Frederikam.
the class JoinCommand method onInvoke.
@Override
public void onInvoke(@Nonnull CommandContext context) {
GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getOrCreate(context.guild);
VoiceChannel vc = player.getUserCurrentVoiceChannel(context.invoker);
try {
player.joinChannel(vc);
if (vc != null) {
context.reply(context.i18nFormat("joinJoining", vc.getName()));
}
} catch (IllegalStateException ex) {
if (vc != null) {
context.reply(context.i18nFormat("joinErrorAlreadyJoining", vc.getName()));
} else {
throw ex;
}
}
}
use of net.dv8tion.jda.core.entities.VoiceChannel in project DiscordBot by LXGaming.
the class JoinCommand method execute.
@Override
public void execute(TextChannel textChannel, Member member, Message message, List<String> arguments) {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setAuthor(textChannel.getJDA().getSelfUser().getName(), null, textChannel.getJDA().getSelfUser().getEffectiveAvatarUrl());
embedBuilder.setColor(DiscordUtil.DEFAULT);
if (arguments == null || arguments.isEmpty()) {
embedBuilder.setColor(DiscordUtil.ERROR);
embedBuilder.setTitle("Invalid arguments!", null);
DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
return;
}
List<VoiceChannel> voiceChannels = member.getGuild().getVoiceChannelsByName(arguments.get(0), false);
if (voiceChannels.size() < 1) {
embedBuilder.setColor(DiscordUtil.ERROR);
embedBuilder.setTitle("Unable to find specified voice channel!", null);
DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
return;
}
if (member.getGuild().getAudioManager().getConnectedChannel() != null) {
member.getGuild().getAudioManager().closeAudioConnection();
}
try {
member.getGuild().getAudioManager().openAudioConnection(voiceChannels.get(0));
embedBuilder.setColor(DiscordUtil.SUCCESS);
embedBuilder.setTitle("Joined channel '" + voiceChannels.get(0).getName() + "'.", null);
DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
} catch (RuntimeException ex) {
embedBuilder.setColor(DiscordUtil.ERROR);
embedBuilder.addField("Cannot join channel '" + voiceChannels.get(0).getName() + "'!", ex.getMessage(), false);
DiscordBot.getInstance().getDiscord().getMessageSender().sendMessage(textChannel, embedBuilder.build(), true);
}
}
use of net.dv8tion.jda.core.entities.VoiceChannel in project FlareBot by FlareBot.
the class VoiceChannelCleanup method cleanupVoiceChannels.
private void cleanupVoiceChannels() {
closedConnections.set(0);
logger.info("Checking for guilds with an inactive voice channel");
final AtomicInteger totalGuilds = new AtomicInteger(0);
final AtomicInteger totalVcs = new AtomicInteger(0);
final AtomicInteger killedVcs = new AtomicInteger(0);
Getters.getGuildCache().forEach(guild -> {
try {
totalGuilds.incrementAndGet();
if (guild != null && guild.getSelfMember() != null && guild.getSelfMember().getVoiceState() != null && guild.getSelfMember().getVoiceState().getChannel() != null) {
totalVcs.incrementAndGet();
VoiceChannel vc = guild.getSelfMember().getVoiceState().getChannel();
if (getHumansInChannel(vc) == 0) {
killedVcs.incrementAndGet();
cleanup(guild, FlareBot.instance().getMusicManager().getPlayer(guild.getId()), vc.getIdLong());
} else if (isPlayingMusic(vc)) {
VC_LAST_USED.put(vc.getIdLong(), System.currentTimeMillis());
} else {
if (!VC_LAST_USED.containsKey(vc.getIdLong())) {
VC_LAST_USED.put(vc.getIdLong(), System.currentTimeMillis());
return;
}
long lastUsed = VC_LAST_USED.get(vc.getIdLong());
if (System.currentTimeMillis() - lastUsed >= CLEANUP_THRESHOLD) {
killedVcs.incrementAndGet();
cleanup(guild, FlareBot.instance().getMusicManager().getPlayer(guild.getId()), vc.getIdLong());
}
}
}
} catch (Exception e) {
logger.error("Failed to check {} for inactive voice connection!", guild.getIdLong(), e);
}
});
logger.info("Checked {} guilds for inactive voice channels.", totalGuilds.get());
logger.info("Killed {} out of {} voice connections!", killedVcs.get(), totalVcs.get());
Metrics.voiceChannelsCleanedUp.inc(killedVcs.get());
}
use of net.dv8tion.jda.core.entities.VoiceChannel in project FlareBot by FlareBot.
the class VoiceChannelCleanup method cleanupPlayers.
private void cleanupPlayers() {
closedConnections.set(0);
logger.info("Checking for players which are inactive");
final AtomicInteger totalPlayers = new AtomicInteger(0);
final AtomicInteger killedPlayers = new AtomicInteger(0);
final AtomicInteger songsCleared = new AtomicInteger(0);
FlareBot.instance().getMusicManager().getPlayers().forEach(player -> {
try {
totalPlayers.incrementAndGet();
long guildId = Long.parseLong(player.getGuildId());
Guild g = Getters.getGuildById(guildId);
if (g == null) {
cleanup(null, player, guildId);
songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
killedPlayers.incrementAndGet();
return;
}
if (g.getSelfMember().getVoiceState() == null || g.getSelfMember().getVoiceState().getChannel() == null) {
if (!VC_LAST_USED.containsKey(guildId)) {
VC_LAST_USED.put(guildId, System.currentTimeMillis());
return;
}
if (System.currentTimeMillis() - VC_LAST_USED.get(guildId) >= CLEANUP_THRESHOLD) {
killedPlayers.incrementAndGet();
songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
cleanup(g, player, guildId);
return;
}
return;
}
VoiceChannel vc = g.getSelfMember().getVoiceState().getChannel();
if (!isPlayingMusic(vc)) {
if (!VC_LAST_USED.containsKey(guildId)) {
VC_LAST_USED.put(guildId, System.currentTimeMillis());
return;
}
if (System.currentTimeMillis() - VC_LAST_USED.get(guildId) >= CLEANUP_THRESHOLD) {
killedPlayers.incrementAndGet();
songsCleared.set(songsCleared.addAndGet(player.getPlaylist().size()));
cleanup(g, player, guildId);
}
} else {
VC_LAST_USED.remove(guildId);
}
} catch (Exception e) {
logger.error("Failed to check {} for inactive player!", player.getGuildId(), e);
}
});
logger.info("Checked {} players for inactivity.", totalPlayers.get());
logger.info("Killed {} out of {} players!", killedPlayers.get(), totalPlayers.get());
logger.info("Cleaned {} songs from players", songsCleared.get());
Metrics.playersCleanedUp.inc(killedPlayers.get());
}
Aggregations