Search in sources :

Example 1 with AudioManager

use of net.dv8tion.jda.api.managers.AudioManager in project toby-bot by ml404.

the class Handler method onGuildVoiceMove.

@Override
public void onGuildVoiceMove(GuildVoiceMoveEvent event) {
    Guild guild = event.getGuild();
    AudioManager audioManager = guild.getAudioManager();
    String volumePropertyName = ConfigDto.Configurations.VOLUME.getConfigValue();
    ConfigDto databaseConfig = configService.getConfigByName(volumePropertyName, event.getGuild().getId());
    int defaultVolume = databaseConfig != null ? Integer.parseInt(databaseConfig.getValue()) : 100;
    List<Member> nonBotConnectedMembersInOldChannel = event.getChannelLeft().getMembers().stream().filter(member -> !member.getUser().isBot()).collect(Collectors.toList());
    if (Objects.equals(audioManager.getConnectedChannel(), event.getChannelLeft()) && nonBotConnectedMembersInOldChannel.isEmpty()) {
        closeAudioPlayer(guild, audioManager, defaultVolume);
    }
    List<Member> nonBotConnectedMembers = event.getChannelJoined().getMembers().stream().filter(member -> !member.getUser().isBot()).collect(Collectors.toList());
    if (!nonBotConnectedMembers.isEmpty() && !audioManager.isConnected()) {
        PlayerManager.getInstance().getMusicManager(guild).getAudioPlayer().setVolume(defaultVolume);
        audioManager.openAudioConnection(event.getChannelJoined());
    }
}
Also used : AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) MusicPlayerHelper.playUserIntro(toby.helpers.MusicPlayerHelper.playUserIntro) JDA(net.dv8tion.jda.api.JDA) BotMain(toby.BotMain) UserDto(toby.jpa.dto.UserDto) AudioManager(net.dv8tion.jda.api.managers.AudioManager) LoggerFactory(org.slf4j.LoggerFactory) Configurable(org.springframework.beans.factory.annotation.Configurable) Autowired(org.springframework.beans.factory.annotation.Autowired) GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) EventWaiter(com.jagrosh.jdautilities.commons.waiter.EventWaiter) ReadyEvent(net.dv8tion.jda.api.events.ReadyEvent) ConfigDto(toby.jpa.dto.ConfigDto) Service(org.springframework.stereotype.Service) Nonnull(javax.annotation.Nonnull) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) Logger(org.slf4j.Logger) Emotes(toby.emote.Emotes) GuildVoiceMoveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) GuildMusicManager(toby.lavaplayer.GuildMusicManager) CommandManager(toby.managers.CommandManager) Collectors(java.util.stream.Collectors) PlayerManager(toby.lavaplayer.PlayerManager) Objects(java.util.Objects) toby.jpa.service(toby.jpa.service) GuildVoiceJoinEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent) List(java.util.List) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) AudioManager(net.dv8tion.jda.api.managers.AudioManager) ConfigDto(toby.jpa.dto.ConfigDto)

Example 2 with AudioManager

use of net.dv8tion.jda.api.managers.AudioManager in project toby-bot by ml404.

the class Handler method onGuildVoiceJoin.

// Auto joining voice channel when it becomes occupied and an audio connection doesn't already exist on the server, then play the associated user's intro song
@Override
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
    Guild guild = event.getGuild();
    AudioManager audioManager = guild.getAudioManager();
    String volumePropertyName = ConfigDto.Configurations.VOLUME.getConfigValue();
    ConfigDto databaseVolumeConfig = configService.getConfigByName(volumePropertyName, event.getGuild().getId());
    ConfigDto deleteDelayConfig = configService.getConfigByName(ConfigDto.Configurations.DELETE_DELAY.getConfigValue(), event.getGuild().getId());
    int defaultVolume = databaseVolumeConfig != null ? Integer.parseInt(databaseVolumeConfig.getValue()) : 100;
    List<Member> nonBotConnectedMembers = event.getChannelJoined().getMembers().stream().filter(member -> !member.getUser().isBot()).collect(Collectors.toList());
    AudioPlayer audioPlayer = PlayerManager.getInstance().getMusicManager(guild).getAudioPlayer();
    if (!nonBotConnectedMembers.isEmpty() && !audioManager.isConnected()) {
        audioPlayer.setVolume(defaultVolume);
        audioManager.openAudioConnection(event.getChannelJoined());
    }
    Member member = event.getMember();
    long discordId = member.getUser().getIdLong();
    long guildId = member.getGuild().getIdLong();
    UserDto userDto = userService.getUserById(discordId, guildId);
    if (Objects.equals(audioManager.getConnectedChannel(), event.getChannelJoined())) {
        playUserIntro(userDto, guild, guild.getDefaultChannel(), Integer.parseInt(deleteDelayConfig.getValue()));
    }
}
Also used : AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) MusicPlayerHelper.playUserIntro(toby.helpers.MusicPlayerHelper.playUserIntro) JDA(net.dv8tion.jda.api.JDA) BotMain(toby.BotMain) UserDto(toby.jpa.dto.UserDto) AudioManager(net.dv8tion.jda.api.managers.AudioManager) LoggerFactory(org.slf4j.LoggerFactory) Configurable(org.springframework.beans.factory.annotation.Configurable) Autowired(org.springframework.beans.factory.annotation.Autowired) GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) EventWaiter(com.jagrosh.jdautilities.commons.waiter.EventWaiter) ReadyEvent(net.dv8tion.jda.api.events.ReadyEvent) ConfigDto(toby.jpa.dto.ConfigDto) Service(org.springframework.stereotype.Service) Nonnull(javax.annotation.Nonnull) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) Logger(org.slf4j.Logger) Emotes(toby.emote.Emotes) GuildVoiceMoveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) GuildMusicManager(toby.lavaplayer.GuildMusicManager) CommandManager(toby.managers.CommandManager) Collectors(java.util.stream.Collectors) PlayerManager(toby.lavaplayer.PlayerManager) Objects(java.util.Objects) toby.jpa.service(toby.jpa.service) GuildVoiceJoinEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent) List(java.util.List) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) AudioManager(net.dv8tion.jda.api.managers.AudioManager) ConfigDto(toby.jpa.dto.ConfigDto) AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) UserDto(toby.jpa.dto.UserDto)

Example 3 with AudioManager

use of net.dv8tion.jda.api.managers.AudioManager in project toby-bot by ml404.

the class LeaveCommand method handle.

@Override
public void handle(CommandContext ctx, String prefix, UserDto requestingUserDto, Integer deleteDelay) {
    ICommand.deleteAfter(ctx.getMessage(), deleteDelay);
    final TextChannel channel = ctx.getChannel();
    final Member self = ctx.getSelfMember();
    final GuildVoiceState selfVoiceState = self.getVoiceState();
    if (!requestingUserDto.hasMusicPermission()) {
        sendErrorMessage(ctx, channel, deleteDelay);
        return;
    }
    if (!selfVoiceState.inVoiceChannel()) {
        channel.sendMessage("I'm not in a voice channel, somebody shoot this guy").queue(message -> ICommand.deleteAfter(message, deleteDelay));
        return;
    }
    final Member member = ctx.getMember();
    final GuildVoiceState memberVoiceState = member.getVoiceState();
    Guild guild = ctx.getGuild();
    final AudioManager audioManager = guild.getAudioManager();
    final VoiceChannel memberChannel = memberVoiceState.getChannel();
    GuildMusicManager musicManager = PlayerManager.getInstance().getMusicManager(guild);
    if (PlayerManager.getInstance().isCurrentlyStoppable() || member.hasPermission(Permission.KICK_MEMBERS)) {
        String volumePropertyName = ConfigDto.Configurations.VOLUME.getConfigValue();
        ConfigDto databaseConfig = configService.getConfigByName(volumePropertyName, ctx.getGuild().getId());
        int defaultVolume = databaseConfig != null ? Integer.parseInt(databaseConfig.getValue()) : 100;
        musicManager.getScheduler().setLooping(false);
        musicManager.getScheduler().getQueue().clear();
        musicManager.getAudioPlayer().stopTrack();
        musicManager.getAudioPlayer().setVolume(defaultVolume);
        audioManager.closeAudioConnection();
        channel.sendMessageFormat("Disconnecting from `\uD83D\uDD0A %s`", memberChannel.getName()).queue(message -> ICommand.deleteAfter(message, deleteDelay));
    } else {
        sendDeniedStoppableMessage(channel, musicManager, deleteDelay);
    }
}
Also used : AudioManager(net.dv8tion.jda.api.managers.AudioManager) ConfigDto(toby.jpa.dto.ConfigDto) GuildMusicManager(toby.lavaplayer.GuildMusicManager)

Example 4 with AudioManager

use of net.dv8tion.jda.api.managers.AudioManager in project Bean by Xirado.

the class InteractionCommandHandler method handleSlashCommand.

public void handleSlashCommand(@NotNull SlashCommandInteractionEvent event, @Nullable Member member) {
    Runnable r = () -> {
        try {
            if (!event.isFromGuild())
                return;
            Guild guild = event.getGuild();
            SlashCommand command = null;
            long guildId = event.getGuild().getIdLong();
            if (registeredGuildCommands.containsKey(guildId)) {
                List<SlashCommand> guildCommands = registeredGuildCommands.get(guildId).stream().filter(cmd -> cmd instanceof SlashCommand).map(cmd -> (SlashCommand) cmd).toList();
                SlashCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
                if (guildCommand != null)
                    command = guildCommand;
            }
            if (command == null) {
                SlashCommand globalCommand = getRegisteredSlashCommands().stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
                if (globalCommand != null)
                    command = globalCommand;
            }
            if (command != null) {
                SlashCommandContext ctx = new SlashCommandContext(event);
                List<Permission> neededPermissions = command.getRequiredUserPermissions();
                List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
                if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
                    event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
                    return;
                }
                if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
                    event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
                    return;
                }
                if (command.getCommandFlags().contains(CommandFlag.DJ_ONLY)) {
                    if (!ctx.getGuildData().isDJ(member)) {
                        event.replyEmbeds(EmbedUtil.errorEmbed("You need to be a DJ to do this!")).queue();
                        return;
                    }
                }
                if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
                    GuildVoiceState guildVoiceState = member.getVoiceState();
                    if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
                        event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
                        return;
                    }
                }
                if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
                    GuildVoiceState voiceState = member.getVoiceState();
                    AudioManager manager = event.getGuild().getAudioManager();
                    if (manager.isConnected()) {
                        if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
                            event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
                            return;
                        }
                    }
                }
                if (command.getCommandFlags().contains(CommandFlag.REQUIRES_LAVALINK_NODE)) {
                    if (!ctx.isLavalinkNodeAvailable()) {
                        event.replyEmbeds(EmbedUtil.errorEmbed("There are currently no voice nodes available!\nIf the issue persists, please leave a message on our support server!")).addActionRow(Util.getSupportButton()).queue();
                        return;
                    }
                }
                command.executeCommand(event, ctx);
                Metrics.COMMANDS.labels("success").inc();
            }
        } catch (Exception e) {
            Metrics.COMMANDS.labels("failed").inc();
            LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
            if (event.isAcknowledged())
                event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            else
                event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            LOGGER.error("Could not execute slash-command", e);
            StringBuilder path = new StringBuilder("/" + event.getCommandPath().replace("/", " "));
            for (OptionMapping option : event.getOptions()) {
                path.append(" *").append(option.getName()).append("* : ").append("`").append(option.getAsString()).append("`");
            }
            EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a slash-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", path.toString(), false).setColor(EmbedUtil.ERROR_COLOR);
            event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
        }
    };
    Bean.getInstance().getCommandExecutor().execute(r);
}
Also used : LocaleLoader(at.xirado.bean.translation.LocaleLoader) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) Permission(net.dv8tion.jda.api.Permission) AudioManager(net.dv8tion.jda.api.managers.AudioManager) LoggerFactory(org.slf4j.LoggerFactory) Util(at.xirado.bean.misc.Util) Member(net.dv8tion.jda.api.entities.Member) Command(net.dv8tion.jda.api.interactions.commands.Command) ArrayList(java.util.ArrayList) at.xirado.bean.command.slashcommands.moderation(at.xirado.bean.command.slashcommands.moderation) UserContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent) Guild(net.dv8tion.jda.api.entities.Guild) at.xirado.bean.command.slashcommands.music(at.xirado.bean.command.slashcommands.music) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) Map(java.util.Map) GenericCommand(at.xirado.bean.command.GenericCommand) SlashCommand(at.xirado.bean.command.SlashCommand) EmbedUtil(at.xirado.bean.misc.EmbedUtil) UserContextCommand(at.xirado.bean.command.context.UserContextCommand) MockContextMenuCommand(at.xirado.bean.command.context.message.MockContextMenuCommand) Logger(org.slf4j.Logger) at.xirado.bean.command.slashcommands(at.xirado.bean.command.slashcommands) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Metrics(at.xirado.bean.misc.Metrics) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) MessageContextCommand(at.xirado.bean.command.context.MessageContextCommand) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) CommandFlag(at.xirado.bean.command.CommandFlag) at.xirado.bean.command.slashcommands.leveling(at.xirado.bean.command.slashcommands.leveling) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Bean(at.xirado.bean.Bean) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) SlapContextMenuCommand(at.xirado.bean.command.context.user.SlapContextMenuCommand) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) Guild(net.dv8tion.jda.api.entities.Guild) SlashCommand(at.xirado.bean.command.SlashCommand) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) AudioManager(net.dv8tion.jda.api.managers.AudioManager) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with AudioManager

use of net.dv8tion.jda.api.managers.AudioManager in project SkyBot by duncte123.

the class LavalinkManager method openConnection.

public void openConnection(VoiceChannel channel) {
    if (!isEnabled()) {
        throw new IllegalStateException("Using lavaplayer is no longer supported");
    }
    final AudioManager audioManager = channel.getGuild().getAudioManager();
    // Turn on the deafen icon for the bot
    audioManager.setSelfDeafened(true);
    lavalink.getLink(channel.getGuild()).connect(channel);
}
Also used : AudioManager(net.dv8tion.jda.api.managers.AudioManager)

Aggregations

AudioManager (net.dv8tion.jda.api.managers.AudioManager)48 GuildVoiceState (net.dv8tion.jda.api.entities.GuildVoiceState)12 Member (net.dv8tion.jda.api.entities.Member)10 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)9 Guild (net.dv8tion.jda.api.entities.Guild)9 List (java.util.List)8 VoiceChannel (net.dv8tion.jda.api.entities.VoiceChannel)8 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 AudioPlayer (com.sedmelluq.discord.lavaplayer.player.AudioPlayer)5 EventWaiter (com.jagrosh.jdautilities.commons.waiter.EventWaiter)4 Nonnull (javax.annotation.Nonnull)4 GuildMusicManager (me.fero.ascent.lavaplayer.GuildMusicManager)4 Permission (net.dv8tion.jda.api.Permission)4 ArrayList (java.util.ArrayList)3 Collections (java.util.Collections)3 Consumer (java.util.function.Consumer)3 Collectors (java.util.stream.Collectors)3 net.dv8tion.jda.api.entities (net.dv8tion.jda.api.entities)3 OptionMapping (net.dv8tion.jda.api.interactions.commands.OptionMapping)3