Search in sources :

Example 1 with Aiode

use of net.robinfriedli.aiode.Aiode in project aiode by robinfriedli.

the class GuildPropertyInterceptor method updatePresets.

private void updatePresets(AbstractGuildProperty argumentPrefixProperty, Character oldArgumentPrefix, char newArgumentPrefix, Session session) {
    List<Preset> presets = queryBuilderFactory.find(Preset.class).build(session).getResultList();
    String defaultValue = argumentPrefixProperty.getDefaultValue();
    char[] chars = defaultValue.toCharArray();
    char defaultArgPrefix;
    if (chars.length == 1) {
        defaultArgPrefix = chars[0];
    } else {
        defaultArgPrefix = ArgumentPrefixProperty.DEFAULT_FALLBACK;
    }
    char argPrefix = oldArgumentPrefix != null ? oldArgumentPrefix : defaultArgPrefix;
    ArgumentPrefixProperty.Config argumentPrefixConfig = new ArgumentPrefixProperty.Config(argPrefix, defaultArgPrefix);
    for (Preset preset : presets) {
        Aiode aiode = Aiode.get();
        AbstractCommand command = preset.instantiateCommand(aiode.getCommandManager(), commandContext, preset.getName());
        String oldPreset = preset.getPreset();
        StringBuilder newPresetBuilder = new StringBuilder(oldPreset);
        List<Integer> oldPrefixOccurrences = Lists.newArrayList();
        CommandParser commandParser = new CommandParser(command, argumentPrefixConfig, new CommandParseListener() {

            @Override
            public void onModeSwitch(CommandParser.Mode previousMode, CommandParser.Mode newMode, int index, char character) {
                // they are in fact argument prefixes
                if (newMode instanceof ArgumentBuildingMode) {
                    oldPrefixOccurrences.add(index);
                }
            }
        });
        commandParser.parse(oldPreset);
        for (int oldPrefixOccurrence : oldPrefixOccurrences) {
            newPresetBuilder.setCharAt(oldPrefixOccurrence, newArgumentPrefix);
        }
        String newPreset = newPresetBuilder.toString();
        if (!oldPreset.equals(newPreset)) {
            preset.setPreset(newPreset);
        }
    }
}
Also used : Preset(net.robinfriedli.aiode.entities.Preset) ArgumentPrefixProperty(net.robinfriedli.aiode.discord.property.properties.ArgumentPrefixProperty) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) ArgumentBuildingMode(net.robinfriedli.aiode.command.parser.ArgumentBuildingMode) Aiode(net.robinfriedli.aiode.Aiode) CommandParser(net.robinfriedli.aiode.command.parser.CommandParser) CommandParseListener(net.robinfriedli.aiode.command.parser.CommandParseListener)

Example 2 with Aiode

use of net.robinfriedli.aiode.Aiode in project aiode by robinfriedli.

the class PermissionExceptionHandler method handleException.

@Override
public Result handleException(Throwable uncaughtException, PermissionException exceptionToHandle) {
    if (Aiode.isInitialised()) {
        Aiode aiode = Aiode.get();
        ExecutionContext executionContext = ExecutionContext.Current.get();
        if (executionContext != null) {
            MessageService messageService = aiode.getMessageService();
            Permission permission = exceptionToHandle.getPermission();
            TextChannel channel = executionContext.getChannel();
            Guild guild = executionContext.getGuild();
            Aiode.LOGGER.warn(String.format("Bot is missing permission %s on guild %s", permission, guild));
            messageService.send("Bot is missing permission: " + permission.getName(), channel);
            return Result.HANDLED;
        }
    }
    return Result.UNHANDLED;
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) ExecutionContext(net.robinfriedli.aiode.concurrent.ExecutionContext) Permission(net.dv8tion.jda.api.Permission) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) MessageService(net.robinfriedli.aiode.discord.MessageService)

Example 3 with Aiode

use of net.robinfriedli.aiode.Aiode in project aiode by robinfriedli.

the class ExceptionHandlerExecutor method handleException.

/**
 * Finds applicable {@link ExceptionHandler}s by calling {@link ExceptionHandlerRegistry#getApplicableExceptionHandlersOrdered(Class)}
 * and calls {@link ExceptionHandler#handleException(Throwable, Throwable)}.
 *
 * @param e the exception to handle.
 * @throws Throwable any throwable, usually the input throwable propagated by {@link #handleUnhandled(Throwable)}
 */
@SuppressWarnings("unchecked")
public final void handleException(Throwable e) throws Throwable {
    if (Aiode.isInitialised()) {
        boolean handled = false;
        try {
            Aiode aiode = Aiode.get();
            ExceptionHandlerRegistry exceptionHandlerRegistry = aiode.getExceptionHandlerRegistry();
            Throwable toHandle = e;
            outer: do {
                List<ExceptionHandler<?>> applicableHandlers = exceptionHandlerRegistry.getApplicableExceptionHandlersOrdered(toHandle.getClass());
                // safety: applicableHandlers only contains handlers that accept Throwables of the type of toHandle or a supertype thereof
                for (@SuppressWarnings("rawtypes") ExceptionHandler handler : applicableHandlers) {
                    // noinspection unchecked
                    ExceptionHandler.Result result = handler.handleException(e, toHandle);
                    if (result == ExceptionHandler.Result.HANDLED) {
                        handled = true;
                        break outer;
                    } else if (result == ExceptionHandler.Result.SKIP_TO_CAUSE) {
                        break;
                    }
                }
            } while ((toHandle = toHandle.getCause()) != null);
        } catch (Exception e1) {
            logger.error(String.format("Exception occurred while calling exception handlers for exception %s. Falling back to #handleUnhandled", e), e1);
            handleUnhandled(e);
            return;
        }
        if (!handled) {
            handleUnhandled(e);
        }
    } else {
        handleUnhandled(e);
    }
}
Also used : List(java.util.List) Aiode(net.robinfriedli.aiode.Aiode)

Example 4 with Aiode

use of net.robinfriedli.aiode.Aiode in project aiode by robinfriedli.

the class DeleteGrantedRolesForDeletedRolesTask method run.

@Override
protected void run(JobExecutionContext jobExecutionContext) {
    Aiode aiode = Aiode.get();
    ShardManager shardManager = aiode.getShardManager();
    QueryBuilderFactory queryBuilderFactory = aiode.getQueryBuilderFactory();
    StaticSessionProvider.consumeSession(session -> {
        List<GuildSpecification> guildSpecifications = queryBuilderFactory.find(GuildSpecification.class).build(session).getResultList();
        int deletionCounter = 0;
        for (GuildSpecification guildSpecification : guildSpecifications) {
            Guild guild = guildSpecification.getGuild(shardManager);
            if (guild == null) {
                continue;
            }
            for (AccessConfiguration accessConfiguration : guildSpecification.getAccessConfigurations()) {
                Set<GrantedRole> grantedRoles = accessConfiguration.getRoles();
                for (GrantedRole grantedRole : grantedRoles) {
                    Role guildRole = grantedRole.getRole(guild);
                    if (guildRole == null) {
                        // role has been deleted
                        accessConfiguration.removeRole(grantedRole);
                        session.delete(grantedRole);
                        ++deletionCounter;
                    }
                }
            }
        }
        if (deletionCounter > 0) {
            logger.info("Deleted " + deletionCounter + " GrantedRole entities for roles that no longer exist");
        }
    });
}
Also used : Role(net.dv8tion.jda.api.entities.Role) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) GrantedRole(net.robinfriedli.aiode.entities.GrantedRole) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) AccessConfiguration(net.robinfriedli.aiode.entities.AccessConfiguration)

Example 5 with Aiode

use of net.robinfriedli.aiode.Aiode in project aiode by robinfriedli.

the class GuildManager method getDefaultTextChannelForGuild.

private TextChannel getDefaultTextChannelForGuild(Guild guild, GuildContext guildContext) {
    Aiode aiode = Aiode.get();
    Member selfMember = guild.getSelfMember();
    // fetch the default text channel from the customised property
    GuildPropertyManager guildPropertyManager = aiode.getGuildPropertyManager();
    AbstractGuildProperty defaultTextChannelProperty = guildPropertyManager.getProperty("defaultTextChannelId");
    if (defaultTextChannelProperty != null) {
        String defaultTextChannelId;
        try {
            defaultTextChannelId = (String) hibernateComponent.invokeWithSession(session -> defaultTextChannelProperty.get(guildContext.getSpecification(session)));
        } catch (NullPointerException e) {
            throw new RuntimeException(e);
        }
        if (!Strings.isNullOrEmpty(defaultTextChannelId)) {
            TextChannel textChannelById = guild.getTextChannelById(defaultTextChannelId);
            if (textChannelById != null && selfMember.hasAccess(textChannelById) && textChannelById.canTalk(selfMember)) {
                return textChannelById;
            }
        }
    }
    // check if the guild's playback has a current communication text channel
    MessageChannel playbackCommunicationChannel = guildContext.getPlayback().getCommunicationChannel();
    if (playbackCommunicationChannel instanceof TextChannel) {
        TextChannel textChannelFromPlayback = (TextChannel) playbackCommunicationChannel;
        if (selfMember.hasAccess(textChannelFromPlayback) && textChannelFromPlayback.canTalk(selfMember)) {
            return textChannelFromPlayback;
        }
    }
    // use guild default defined by discord
    TextChannel defaultChannel = guild.getDefaultChannel();
    if (defaultChannel != null && selfMember.hasAccess(defaultChannel) && defaultChannel.canTalk(selfMember)) {
        return defaultChannel;
    } else {
        TextChannel systemChannel = guild.getSystemChannel();
        if (systemChannel != null && selfMember.hasAccess(systemChannel) && systemChannel.canTalk()) {
            return systemChannel;
        }
    }
    List<TextChannel> availableChannels = guild.getTextChannels().stream().filter(channel -> selfMember.hasAccess(channel) && channel.canTalk(selfMember)).collect(Collectors.toList());
    if (availableChannels.isEmpty()) {
        return null;
    } else {
        return availableChannels.get(0);
    }
}
Also used : AbstractGuildProperty(net.robinfriedli.aiode.discord.property.AbstractGuildProperty) AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) PlaylistItemTimestampInterceptor(net.robinfriedli.aiode.persist.interceptors.PlaylistItemTimestampInterceptor) PlaybackHistory(net.robinfriedli.aiode.entities.PlaybackHistory) JxpBackend(net.robinfriedli.jxp.api.JxpBackend) LoggerFactory(org.slf4j.LoggerFactory) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) HibernatePlaylistMigrator(net.robinfriedli.aiode.persist.tasks.HibernatePlaylistMigrator) ExecutionContext(net.robinfriedli.aiode.concurrent.ExecutionContext) Guild(net.dv8tion.jda.api.entities.Guild) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) Playlist(net.robinfriedli.aiode.entities.Playlist) Map(java.util.Map) Resource(org.springframework.core.io.Resource) EmbedDocumentContribution(net.robinfriedli.aiode.entities.xml.EmbedDocumentContribution) CommandManager(net.robinfriedli.aiode.command.CommandManager) AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) AudioManager(net.robinfriedli.aiode.audio.AudioManager) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Sets(com.google.common.collect.Sets) List(java.util.List) AccessConfiguration(net.robinfriedli.aiode.entities.AccessConfiguration) SnowflakeMap(net.robinfriedli.aiode.util.SnowflakeMap) Optional(java.util.Optional) InterceptorChain(net.robinfriedli.aiode.persist.interceptors.InterceptorChain) HibernateComponent(net.robinfriedli.aiode.boot.configurations.HibernateComponent) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) AbstractGuildProperty(net.robinfriedli.aiode.discord.property.AbstractGuildProperty) LocalDateTime(java.time.LocalDateTime) Session(org.hibernate.Session) MutexSync(net.robinfriedli.exec.MutexSync) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) QueryBuilderFactory(net.robinfriedli.aiode.persist.qb.QueryBuilderFactory) GuildPropertyManager(net.robinfriedli.aiode.discord.property.GuildPropertyManager) SearchEngine(net.robinfriedli.aiode.util.SearchEngine) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) Nullable(javax.annotation.Nullable) VerifyPlaylistInterceptor(net.robinfriedli.aiode.persist.interceptors.VerifyPlaylistInterceptor) Context(net.robinfriedli.jxp.persist.Context) Logger(org.slf4j.Logger) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) CommandHistory(net.robinfriedli.aiode.entities.CommandHistory) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Conditions(net.robinfriedli.jxp.queries.Conditions) HibernateInvoker(net.robinfriedli.aiode.function.HibernateInvoker) Aiode(net.robinfriedli.aiode.Aiode) SpotifyApi(se.michaelthelin.spotify.SpotifyApi) Component(org.springframework.stereotype.Component) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) GuildPropertyManager(net.robinfriedli.aiode.discord.property.GuildPropertyManager) Aiode(net.robinfriedli.aiode.Aiode) Member(net.dv8tion.jda.api.entities.Member)

Aggregations

Aiode (net.robinfriedli.aiode.Aiode)21 Guild (net.dv8tion.jda.api.entities.Guild)10 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 Session (org.hibernate.Session)7 TextChannel (net.dv8tion.jda.api.entities.TextChannel)6 ShardManager (net.dv8tion.jda.api.sharding.ShardManager)5 CommandContext (net.robinfriedli.aiode.command.CommandContext)5 SpotifyApi (se.michaelthelin.spotify.SpotifyApi)5 List (java.util.List)4 AudioManager (net.robinfriedli.aiode.audio.AudioManager)4 ExecutionContext (net.robinfriedli.aiode.concurrent.ExecutionContext)4 GuildSpecification (net.robinfriedli.aiode.entities.GuildSpecification)4 Playlist (net.robinfriedli.aiode.entities.Playlist)4 AudioPlayer (com.sedmelluq.discord.lavaplayer.player.AudioPlayer)3 IOException (java.io.IOException)3 LocalDateTime (java.time.LocalDateTime)3 AudioPlayback (net.robinfriedli.aiode.audio.AudioPlayback)3 CommandManager (net.robinfriedli.aiode.command.CommandManager)3 GuildContext (net.robinfriedli.aiode.discord.GuildContext)3 AccessConfiguration (net.robinfriedli.aiode.entities.AccessConfiguration)3