Search in sources :

Example 1 with SelfUser

use of net.dv8tion.jda.api.entities.SelfUser in project pokeraidbot by magnusmickelsson.

the class GymHuntrRaidEventListener method onEvent.

@Override
public void onEvent(GenericEvent event) {
    if (event instanceof GuildMessageReceivedEvent) {
        GuildMessageReceivedEvent guildEvent = (GuildMessageReceivedEvent) event;
        final User messageAuthor = guildEvent.getAuthor();
        try {
            if (isUserGymhuntrBot(messageAuthor) || isUserPokeAlarmBot(messageAuthor)) {
                final String serverName = guildEvent.getGuild().getName().toLowerCase();
                final Config config = serverConfigRepository.getConfigForServer(serverName);
                if (config == null) {
                    LOGGER.warn("Server configuration is null for this guild: " + guildEvent.getGuild().getName());
                    return;
                }
                if (!config.useBotIntegration()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Skipping trigger, since bot integration setting is false for server " + guildEvent.getGuild().getName());
                    }
                    return;
                }
                final List<MessageEmbed> embeds = guildEvent.getMessage().getEmbeds();
                if (embeds != null && embeds.size() > 0) {
                    for (MessageEmbed embed : embeds) {
                        final LocalDateTime currentDateTime = clockService.getCurrentDateTime();
                        final String description = embed.getDescription();
                        final String title = embed.getTitle();
                        List<String> newRaidArguments;
                        if (isUserGymhuntrBot(messageAuthor)) {
                            newRaidArguments = gymhuntrArgumentsToCreateRaid(title, description, clockService);
                        } else if (isUserPokeAlarmBot(messageAuthor)) {
                            newRaidArguments = pokeAlarmArgumentsToCreateRaid(title, description, clockService);
                        } else {
                            newRaidArguments = new ArrayList<>();
                        }
                        try {
                            if (newRaidArguments != null && newRaidArguments.size() > 0) {
                                final Iterator<String> iterator = newRaidArguments.iterator();
                                final String gym = iterator.next();
                                final String pokemon = iterator.next();
                                final String time = iterator.next();
                                final Pokemon raidBoss = pokemonRepository.getByName(pokemon);
                                final String region = config.getRegion();
                                final Gym raidGym = gymRepository.findByName(gym, region);
                                final LocalDate currentDate = currentDateTime.toLocalDate();
                                final LocalDateTime endOfRaid = LocalDateTime.of(currentDate, LocalTime.parse(time, Utils.timeParseFormatter));
                                final SelfUser botUser = botService.getBot().getSelfUser();
                                final PokemonRaidInfo raidInfo;
                                raidInfo = strategyService.getRaidInfo(raidBoss);
                                handleRaidFromIntegration(botUser, guildEvent, raidBoss, raidGym, endOfRaid, config, clockService, raidInfo, strategyService);
                            } else {
                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("No arguments to create raid with for server " + config + ", skipping. Raw command: " + guildEvent.getMessage().getContentRaw());
                                }
                            }
                        } catch (Throwable t) {
                            LOGGER.warn("Exception when trying to get arguments for raid creation: " + t.getMessage());
                        }
                    }
                }
            }
        } catch (Throwable t) {
            LOGGER.warn("Exception thrown for event listener: " + t.getMessage());
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Stacktrace: ", t);
            }
        }
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) User(net.dv8tion.jda.api.entities.User) SelfUser(net.dv8tion.jda.api.entities.SelfUser) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Config(pokeraidbot.infrastructure.jpa.config.Config) PokemonRaidInfo(pokeraidbot.domain.pokemon.PokemonRaidInfo) LocalDate(java.time.LocalDate) Gym(pokeraidbot.domain.gym.Gym) Pokemon(pokeraidbot.domain.pokemon.Pokemon) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) SelfUser(net.dv8tion.jda.api.entities.SelfUser)

Example 2 with SelfUser

use of net.dv8tion.jda.api.entities.SelfUser in project JDA by DV8FromTheWorld.

the class DefaultShardManager method buildInstance.

protected JDAImpl buildInstance(final int shardId) throws LoginException {
    OkHttpClient httpClient = sessionConfig.getHttpClient();
    if (httpClient == null) {
        // httpClient == null implies we have a builder
        // noinspection ConstantConditions
        httpClient = sessionConfig.getHttpBuilder().build();
    }
    // imagine if we had macros or closures or destructuring :)
    ExecutorPair<ScheduledExecutorService> rateLimitPair = resolveExecutor(threadingConfig.getRateLimitPoolProvider(), shardId);
    ScheduledExecutorService rateLimitPool = rateLimitPair.executor;
    boolean shutdownRateLimitPool = rateLimitPair.automaticShutdown;
    ExecutorPair<ScheduledExecutorService> gatewayPair = resolveExecutor(threadingConfig.getGatewayPoolProvider(), shardId);
    ScheduledExecutorService gatewayPool = gatewayPair.executor;
    boolean shutdownGatewayPool = gatewayPair.automaticShutdown;
    ExecutorPair<ExecutorService> callbackPair = resolveExecutor(threadingConfig.getCallbackPoolProvider(), shardId);
    ExecutorService callbackPool = callbackPair.executor;
    boolean shutdownCallbackPool = callbackPair.automaticShutdown;
    ExecutorPair<ExecutorService> eventPair = resolveExecutor(threadingConfig.getEventPoolProvider(), shardId);
    ExecutorService eventPool = eventPair.executor;
    boolean shutdownEventPool = eventPair.automaticShutdown;
    ExecutorPair<ScheduledExecutorService> audioPair = resolveExecutor(threadingConfig.getAudioPoolProvider(), shardId);
    ScheduledExecutorService audioPool = audioPair.executor;
    boolean shutdownAudioPool = audioPair.automaticShutdown;
    AuthorizationConfig authConfig = new AuthorizationConfig(token);
    SessionConfig sessionConfig = this.sessionConfig.toSessionConfig(httpClient);
    ThreadingConfig threadingConfig = new ThreadingConfig();
    threadingConfig.setRateLimitPool(rateLimitPool, shutdownRateLimitPool);
    threadingConfig.setGatewayPool(gatewayPool, shutdownGatewayPool);
    threadingConfig.setCallbackPool(callbackPool, shutdownCallbackPool);
    threadingConfig.setEventPool(eventPool, shutdownEventPool);
    threadingConfig.setAudioPool(audioPool, shutdownAudioPool);
    MetaConfig metaConfig = new MetaConfig(this.metaConfig.getMaxBufferSize(), this.metaConfig.getContextMap(shardId), this.metaConfig.getCacheFlags(), this.sessionConfig.getFlags());
    final JDAImpl jda = new JDAImpl(authConfig, sessionConfig, threadingConfig, metaConfig);
    jda.setMemberCachePolicy(shardingConfig.getMemberCachePolicy());
    threadingConfig.init(jda::getIdentifierString);
    // We can only do member chunking with the GUILD_MEMBERS intent
    if ((shardingConfig.getIntents() & GatewayIntent.GUILD_MEMBERS.getRawValue()) == 0)
        jda.setChunkingFilter(ChunkingFilter.NONE);
    else
        jda.setChunkingFilter(chunkingFilter);
    jda.setShardManager(this);
    if (eventConfig.getEventManagerProvider() != null)
        jda.setEventManager(this.eventConfig.getEventManagerProvider().apply(shardId));
    if (this.sessionConfig.getAudioSendFactory() != null)
        jda.setAudioSendFactory(this.sessionConfig.getAudioSendFactory());
    this.eventConfig.getListeners().forEach(jda::addEventListener);
    this.eventConfig.getListenerProviders().forEach(provider -> jda.addEventListener(provider.apply(shardId)));
    // Set the presence information before connecting to have the correct information ready when sending IDENTIFY
    PresenceImpl presence = ((PresenceImpl) jda.getPresence());
    if (presenceConfig.getActivityProvider() != null)
        presence.setCacheActivity(presenceConfig.getActivityProvider().apply(shardId));
    if (presenceConfig.getIdleProvider() != null)
        presence.setCacheIdle(presenceConfig.getIdleProvider().apply(shardId));
    if (presenceConfig.getStatusProvider() != null)
        presence.setCacheStatus(presenceConfig.getStatusProvider().apply(shardId));
    if (this.gatewayURL == null) {
        try {
            SessionController.ShardedGateway gateway = jda.getShardedGateway();
            this.sessionConfig.getSessionController().setConcurrency(gateway.getConcurrency());
            this.gatewayURL = gateway.getUrl();
            if (this.gatewayURL == null)
                LOG.error("Acquired null gateway url from SessionController");
            else
                LOG.info("Login Successful!");
            if (getShardsTotal() == -1) {
                shardingConfig.setShardsTotal(gateway.getShardTotal());
                this.shards = new ShardCacheViewImpl(getShardsTotal());
                synchronized (queue) {
                    for (int i = 0; i < getShardsTotal(); i++) queue.add(i);
                }
            }
        } catch (CompletionException e) {
            if (e.getCause() instanceof LoginException)
                // complete() can't throw this because its a checked-exception so we have to unwrap it first
                throw (LoginException) e.getCause();
            throw e;
        }
    }
    final JDA.ShardInfo shardInfo = new JDA.ShardInfo(shardId, getShardsTotal());
    // Initialize SelfUser instance before logging in
    SelfUser selfUser = getShardCache().applyStream(s -> // this should never throw!
    s.map(JDA::getSelfUser).findFirst().orElse(null));
    // Copy from other JDA instance or do initial fetch
    if (selfUser == null)
        selfUser = retrieveSelfUser(jda);
    else
        selfUser = SelfUserImpl.copyOf((SelfUserImpl) selfUser, jda);
    jda.setSelfUser(selfUser);
    // This is already set by JDA internally, but this is to make sure the listeners catch it.
    jda.setStatus(JDA.Status.INITIALIZED);
    final int shardTotal = jda.login(this.gatewayURL, shardInfo, this.metaConfig.getCompression(), false, shardingConfig.getIntents(), this.metaConfig.getEncoding());
    if (getShardsTotal() == -1)
        shardingConfig.setShardsTotal(shardTotal);
    return jda;
}
Also used : ShardCacheViewImpl(net.dv8tion.jda.internal.utils.cache.ShardCacheViewImpl) ThreadingConfig(net.dv8tion.jda.internal.utils.config.ThreadingConfig) OkHttpClient(okhttp3.OkHttpClient) PresenceImpl(net.dv8tion.jda.internal.managers.PresenceImpl) JDA(net.dv8tion.jda.api.JDA) MetaConfig(net.dv8tion.jda.internal.utils.config.MetaConfig) SessionConfig(net.dv8tion.jda.internal.utils.config.SessionConfig) JDAImpl(net.dv8tion.jda.internal.JDAImpl) AuthorizationConfig(net.dv8tion.jda.internal.utils.config.AuthorizationConfig) SessionController(net.dv8tion.jda.api.utils.SessionController) LoginException(javax.security.auth.login.LoginException) SelfUser(net.dv8tion.jda.api.entities.SelfUser)

Aggregations

SelfUser (net.dv8tion.jda.api.entities.SelfUser)2 LocalDate (java.time.LocalDate)1 LocalDateTime (java.time.LocalDateTime)1 LoginException (javax.security.auth.login.LoginException)1 JDA (net.dv8tion.jda.api.JDA)1 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)1 User (net.dv8tion.jda.api.entities.User)1 GuildMessageReceivedEvent (net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent)1 SessionController (net.dv8tion.jda.api.utils.SessionController)1 JDAImpl (net.dv8tion.jda.internal.JDAImpl)1 PresenceImpl (net.dv8tion.jda.internal.managers.PresenceImpl)1 ShardCacheViewImpl (net.dv8tion.jda.internal.utils.cache.ShardCacheViewImpl)1 AuthorizationConfig (net.dv8tion.jda.internal.utils.config.AuthorizationConfig)1 MetaConfig (net.dv8tion.jda.internal.utils.config.MetaConfig)1 SessionConfig (net.dv8tion.jda.internal.utils.config.SessionConfig)1 ThreadingConfig (net.dv8tion.jda.internal.utils.config.ThreadingConfig)1 OkHttpClient (okhttp3.OkHttpClient)1 Gym (pokeraidbot.domain.gym.Gym)1 Pokemon (pokeraidbot.domain.pokemon.Pokemon)1 PokemonRaidInfo (pokeraidbot.domain.pokemon.PokemonRaidInfo)1