Search in sources :

Example 26 with AudioManager

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

the class Handler method onGuildVoiceLeave.

// Auto leaving voice channel when it becomes empty
@Override
public void onGuildVoiceLeave(GuildVoiceLeaveEvent 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> nonBotConnectedMembers = event.getChannelLeft().getMembers().stream().filter(member -> !member.getUser().isBot()).collect(Collectors.toList());
    if (Objects.equals(audioManager.getConnectedChannel(), event.getChannelLeft()) && nonBotConnectedMembers.isEmpty()) {
        closeAudioPlayer(guild, audioManager, defaultVolume);
    }
}
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 27 with AudioManager

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

the class JoinCommand 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();
    if (!requestingUserDto.hasMusicPermission()) {
        sendErrorMessage(ctx, channel, deleteDelay);
        return;
    }
    final GuildVoiceState memberVoiceState = doJoinChannelValidation(ctx, channel, deleteDelay);
    if (memberVoiceState == null)
        return;
    final AudioManager audioManager = ctx.getGuild().getAudioManager();
    final VoiceChannel memberChannel = memberVoiceState.getChannel();
    if (self.hasPermission(Permission.VOICE_CONNECT)) {
        audioManager.openAudioConnection(memberChannel);
        String volumePropertyName = ConfigDto.Configurations.VOLUME.getConfigValue();
        ConfigDto databaseConfig = configService.getConfigByName(volumePropertyName, ctx.getGuild().getId());
        int defaultVolume = databaseConfig != null ? Integer.parseInt(databaseConfig.getValue()) : 100;
        PlayerManager.getInstance().getMusicManager(ctx.getGuild()).getAudioPlayer().setVolume(defaultVolume);
        channel.sendMessageFormat("Connecting to `\uD83D\uDD0A %s` with volume '%s'", memberChannel.getName(), defaultVolume).queue(message -> ICommand.deleteAfter(message, deleteDelay));
    }
}
Also used : AudioManager(net.dv8tion.jda.api.managers.AudioManager) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ConfigDto(toby.jpa.dto.ConfigDto) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) Member(net.dv8tion.jda.api.entities.Member)

Example 28 with AudioManager

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

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)

Example 29 with AudioManager

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

the class InteractionCommandHandler method handleUserContextCommand.

public void handleUserContextCommand(@NotNull UserContextInteractionEvent event) {
    if (!event.isFromGuild())
        return;
    Guild guild = event.getGuild();
    Member member = event.getMember();
    UserContextCommand command = null;
    if (registeredGuildCommands.containsKey(guild.getIdLong())) {
        List<UserContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof UserContextCommand).map(cmd -> (UserContextCommand) cmd).toList();
        UserContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (guildCommand != null)
            command = guildCommand;
    }
    if (command == null) {
        UserContextCommand globalCommand = getRegisteredUserContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (globalCommand != null)
            command = globalCommand;
    }
    if (command == null)
        return;
    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.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;
            }
        }
    }
    UserContextCommand finalCommand = command;
    Runnable r = () -> {
        try {
            finalCommand.executeCommand(event);
            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 user-context-menu-command", e);
            EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a user-context-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", event.getName(), 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().submit(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) UserContextCommand(at.xirado.bean.command.context.UserContextCommand) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) Guild(net.dv8tion.jda.api.entities.Guild) AudioManager(net.dv8tion.jda.api.managers.AudioManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member)

Example 30 with AudioManager

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

the class InteractionCommandHandler method handleMessageContextCommand.

public void handleMessageContextCommand(@NotNull MessageContextInteractionEvent event) {
    if (!event.isFromGuild())
        return;
    Guild guild = event.getGuild();
    Member member = event.getMember();
    MessageContextCommand command = null;
    if (registeredGuildCommands.containsKey(guild.getIdLong())) {
        List<MessageContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof MessageContextCommand).map(cmd -> (MessageContextCommand) cmd).toList();
        MessageContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (guildCommand != null)
            command = guildCommand;
    }
    if (command == null) {
        MessageContextCommand globalCommand = getRegisteredMessageContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (globalCommand != null)
            command = globalCommand;
    }
    if (command == null)
        return;
    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.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;
            }
        }
    }
    MessageContextCommand finalCommand = command;
    Runnable r = () -> {
        try {
            finalCommand.executeCommand(event);
            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 message-context-menu-command", e);
            EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a message-context-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", event.getName(), 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().submit(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) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) Guild(net.dv8tion.jda.api.entities.Guild) MessageContextCommand(at.xirado.bean.command.context.MessageContextCommand) AudioManager(net.dv8tion.jda.api.managers.AudioManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member)

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