Search in sources :

Example 1 with Config

use of pokeraidbot.infrastructure.jpa.config.Config in project pokeraidbot by magnusmickelsson.

the class ConfigAwareCommand method execute.

@Override
protected void execute(CommandEvent commandEvent) {
    Config configForServer = null;
    try {
        final Guild guild = commandEvent.getGuild();
        if (guild != null) {
            final String server = guild.getName().trim().toLowerCase();
            configForServer = serverConfigRepository.getConfigForServer(server);
            if (configForServer == null) {
                final String noConfigText = localeService.getMessageFor(LocaleService.NO_CONFIG, localeService.getLocaleForUser(commandEvent.getAuthor()));
                commandEvent.reply(noConfigText);
                if (commandListener != null) {
                    commandListener.onCompletedCommand(commandEvent, this);
                }
                return;
            }
        }
        executeWithConfig(commandEvent, configForServer);
        if (commandListener != null) {
            commandListener.onCompletedCommand(commandEvent, this);
        }
    } catch (Throwable t) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Exception thrown from command " + this.getClass().getSimpleName() + " with input message \"" + commandEvent.getMessage().getRawContent() + "\"" + (configForServer != null ? " for server " + configForServer.getServer() : "") + ":\n" + t.getMessage());
            if (t.getMessage() == null) {
                LOGGER.debug("Dumping stacktrace, since exception was null.", t);
            }
        }
        try {
            if (t instanceof IllegalArgumentException) {
                getFeedbackStrategy(configForServer).replyError(configForServer, commandEvent, new UserMessedUpException(commandEvent.getAuthor().getName(), t.getMessage()), localeService);
            } else {
                getFeedbackStrategy(configForServer).replyError(configForServer, commandEvent, t, localeService);
            }
            if (commandListener != null) {
                commandListener.onTerminatedCommand(commandEvent, this);
            }
        } catch (Throwable tt) {
            LOGGER.warn("Exception when trying to give feedback about an error for server " + configForServer + ": " + tt.getMessage());
        }
    }
}
Also used : Config(pokeraidbot.infrastructure.jpa.config.Config) UserMessedUpException(pokeraidbot.domain.errors.UserMessedUpException) Guild(net.dv8tion.jda.core.entities.Guild)

Example 2 with Config

use of pokeraidbot.infrastructure.jpa.config.Config in project pokeraidbot by magnusmickelsson.

the class GymRepository method reloadGymData.

public void reloadGymData() {
    if (serverConfigRepository != null) {
        Map<String, Config> configMap = serverConfigRepository.getAllConfig();
        Map<String, Set<Gym>> gymsPerRegion = new HashMap<>();
        LOGGER.info("Config has following servers: " + configMap.keySet());
        for (String server : configMap.keySet()) {
            final Config config = serverConfigRepository.getConfigForServer(server);
            final String region = config.getRegion();
            final Set<Gym> existingGyms = gymsPerRegion.get(region);
            if (existingGyms == null) {
                try {
                    final Set<Gym> gymsInRegion = new CSVGymDataReader("/gyms_" + region + ".csv").readAll();
                    gymsPerRegion.put(region, gymsInRegion);
                    LOGGER.info("Loaded " + gymsInRegion.size() + " gyms for region " + region + ".");
                } catch (Throwable t) {
                    LOGGER.warn("Could not load data for region " + region + ", skipping.");
                }
            }
        }
        for (String region : gymsPerRegion.keySet()) {
            Set<Gym> gymsForRegion = gymsPerRegion.get(region);
            this.gymsPerRegion.put(region, gymsForRegion);
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Config(pokeraidbot.infrastructure.jpa.config.Config) CSVGymDataReader(pokeraidbot.infrastructure.CSVGymDataReader)

Example 3 with Config

use of pokeraidbot.infrastructure.jpa.config.Config in project pokeraidbot by magnusmickelsson.

the class RaidOverviewCommand method getMessageRefreshingTaskToSchedule.

public static Callable<Boolean> getMessageRefreshingTaskToSchedule(User user, String server, String messageId, LocaleService localeService, Locale locale, ServerConfigRepository serverConfigRepository, RaidRepository raidRepository, ClockService clockService, MessageChannel messageChannel, final ExecutorService executorService, PokemonRaidStrategyService strategyService) {
    final Callable<Boolean> refreshEditThreadTask = () -> {
        final Callable<Boolean> editTask = () -> {
            // Update once a minute
            TimeUnit.SECONDS.sleep(60);
            final Config config = serverConfigRepository.getConfigForServer(server);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Thread: " + Thread.currentThread().getId() + " - Updating for server " + config.getServer() + " with ID " + messageId);
            }
            final Message message = messageChannel.getMessageById(messageId).complete();
            if (config.getOverviewMessageId() != null && message != null) {
                final String messageString = getOverviewMessage(config, localeService, raidRepository, clockService, locale, strategyService);
                messageChannel.editMessageById(messageId, messageString).queue(m -> {
                }, m -> {
                    LOGGER.warn(m.getClass().getSimpleName() + " thrown: " + m.getMessage());
                    if (m instanceof SocketTimeoutException) {
                        LOGGER.debug("We got a socket timeout, which could be that the server is temporarily " + "down. Let's not clean up things before we know if it works or not.");
                    }
                });
                return true;
            } else {
                LOGGER.warn("Could not find message for overview - config ID: " + config.getOverviewMessageId() + ", message: " + (message == null ? "null" : message.getId()) + ". Cleaning up...");
                cleanUp(config, messageId, serverConfigRepository, messageChannel);
                return false;
            }
        };
        boolean overviewOk = true;
        do {
            try {
                overviewOk = executorService.submit(editTask).get();
            } catch (InterruptedException | ExecutionException | OverviewException e) {
                LOGGER.warn("Exception when running edit task: " + e.getMessage() + ".");
                if (Utils.isExceptionOrCauseNetworkIssues(e)) {
                    LOGGER.info("Exception was due to timeout, so trying again later. Could be temporary.");
                    overviewOk = true;
                } else {
                    LOGGER.info("Exception was not due to timeout, so terminating this overview.");
                    overviewOk = false;
                }
            }
        } while (overviewOk);
        return false;
    };
    return refreshEditThreadTask;
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) Message(net.dv8tion.jda.core.entities.Message) Config(pokeraidbot.infrastructure.jpa.config.Config) Callable(java.util.concurrent.Callable)

Example 4 with Config

use of pokeraidbot.infrastructure.jpa.config.Config in project pokeraidbot by magnusmickelsson.

the class BotService method initializeConfig.

@Transactional
public void initializeConfig() {
    if (serverConfigRepository.findAll().size() == 0) {
        LOGGER.warn("Could not find any configuration in database, assuming fresh install. " + "Creating basic server configurations..");
        // My test servers
        serverConfigRepository.save(new Config("manhattan_new_york", false, Locale.ENGLISH, "pokeraidbot_us_test"));
        serverConfigRepository.save(new Config("uppsala", "zhorhn tests stuff"));
        serverConfigRepository.save(new Config("uppsala", "pokeraidbot_lab2"));
        serverConfigRepository.save(new Config("uppsala", "pokeraidbot_stage"));
        serverConfigRepository.save(new Config("uppsala", "pokeraidbot_test"));
        LOGGER.info("Server configurations created. Add more via the command for an administrator " + "in a server where pokeraidbot has been added: !raid install");
    }
    gymRepository.reloadGymData();
}
Also used : Config(pokeraidbot.infrastructure.jpa.config.Config) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with Config

use of pokeraidbot.infrastructure.jpa.config.Config in project pokeraidbot by magnusmickelsson.

the class AdminCommands method execute.

@Override
protected void execute(CommandEvent event) {
    final User user = event.getAuthor();
    if (user == null || user.getId() == null || (!user.getId().equals(BotServerMain.BOT_CREATOR_USERID))) {
        event.replyInDM("This command is reserved only for bot creator. Hands off! ;p Your user ID was: " + String.valueOf(user.getId()));
        return;
    } else {
        final String eventArgs = event.getArgs();
        if (eventArgs.startsWith("userconfig")) {
            String userId = eventArgs.replaceAll("userconfig\\s{1,3}", "");
            final UserConfig userConfig = userConfigRepository.findOne(userId);
            if (userConfig == null) {
                event.replyInDM("No user with ID " + userId);
                return;
            } else {
                userConfigRepository.delete(userConfig);
                event.replyInDM("Removed user configuration for user with ID " + userId);
                return;
            }
        } else if (eventArgs.startsWith("permissions")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            sb.append("**Permissions for bot across servers:**\n\n");
            for (Guild guild : guilds) {
                final Member member = guild.getMember(bot.getSelfUser());
                if (member == null) {
                    event.replyInDM("Could not get bot as servermember!");
                    return;
                }
                sb.append("*").append(guild.getName()).append("*\n");
                for (Permission p : member.getPermissions()) {
                    sb.append(p.getName()).append("(Guild: ").append(p.isGuild()).append(" Channel: ").append(p.isChannel()).append(")\n");
                }
                sb.append("\n\n");
            }
            event.replyInDM(sb.toString());
            return;
        } else if (eventArgs.startsWith("clear tracking")) {
            trackingCommandListener.clearCache();
            event.replyInDM("Cleared tracking cache.");
            return;
        } else if (eventArgs.startsWith("announce")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            for (Guild guild : guilds) {
                try {
                    guild.getDefaultChannel().sendMessage(eventArgs.replaceAll("announce\\s{1,3}", "")).queue();
                    sb.append("Sent message for guild ").append(guild.getName()).append("\n");
                } catch (Throwable t) {
                    sb.append("Failed to send message for guild ").append(guild.getName()).append(": ").append(t.getMessage()).append("\n");
                }
            }
            event.replyInDM(sb.toString());
            return;
        } else if (eventArgs.startsWith("ismember")) {
            String userIdAndGuildName = eventArgs.replaceAll("ismember\\s{1,3}", "");
            String[] args = userIdAndGuildName.split(" ");
            if (args.length < 2) {
                event.reply("Bad syntax, should be something like: !raid admin ismember {userid} {guildname}");
                return;
            } else {
                final JDA bot = botService.getBot();
                Guild guild = null;
                final List<Guild> guilds = bot.getGuilds();
                String guildName = StringUtils.join(ArrayUtils.remove(args, 0), " ");
                for (Guild guildToCheck : guilds) {
                    if (guildToCheck.getName().equalsIgnoreCase(guildName)) {
                        guild = guildToCheck;
                    }
                }
                if (guild != null) {
                    final Member memberById = guild.getMemberById(args[0]);
                    if (memberById != null) {
                        event.reply("User is a member of server " + guild.getName());
                    } else {
                        event.reply("User is not a member of server " + guild.getName());
                    }
                } else {
                    event.reply("There was no server the user is a member of.");
                }
                return;
            }
        } else if (eventArgs.startsWith("member")) {
            String userIdAndGuildName = eventArgs.replaceAll("member\\s{1,3}", "");
            String[] args = userIdAndGuildName.split(" ");
            if (args.length < 1 || args.length > 2) {
                event.reply("Bad syntax, should be something like: !raid admin member {userid}");
                return;
            } else {
                StringBuilder sb = new StringBuilder();
                final JDA bot = botService.getBot();
                final List<Guild> guilds = bot.getGuilds();
                sb.append("User with ID ").append(args[0]).append(" is a member of the following servers:\n\n");
                if (guilds.size() == 0) {
                    sb.append("-");
                }
                for (Guild guild : guilds) {
                    final Member memberById = guild.getMemberById(args[0]);
                    if (memberById != null) {
                        sb.append(guild.getName()).append(" (Username ").append(memberById.getUser().getName()).append(")\n");
                    }
                }
                event.reply(sb.toString());
                return;
            }
        } else if (eventArgs.startsWith("guilds")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            for (Guild guildToCheck : guilds) {
                sb.append(guildToCheck.getName().toLowerCase()).append("\n");
            }
            event.reply(sb.toString());
            return;
        } else if (eventArgs.startsWith("test")) {
            final Config configForServer = serverConfigRepository.getConfigForServer(event.getGuild().getName().toLowerCase());
            String[] args = eventArgs.replaceAll("test\\s{1,3}", "").trim().split(" ");
            String pokemon = args[0];
            LocalDateTime startsAt = LocalDateTime.of(LocalDate.now(), Utils.parseTime(user, args[1], localeService));
            String gymName = StringUtils.join(ArrayUtils.removeElements(args, 0, 1), " ").trim();
            final String region = configForServer.getRegion();
            Raid raid = new Raid(pokemonRepository.search(pokemon, user), startsAt.plusMinutes(Utils.RAID_DURATION_IN_MINUTES), gymRepository.search(user, gymName, region), localeService, region);
            final Raid createdRaid = raidRepository.newRaid(botService.getBot().getSelfUser(), raid, event.getGuild(), configForServer, event.getMessage().getRawContent());
            event.reply("Bot created your test raid: " + createdRaid);
            return;
        } else if (eventArgs.startsWith("tier5")) {
            String[] bosses = eventArgs.replaceAll("tier5\\s{1,3}", "").trim().split(";");
            if (bosses == null || bosses.length < 1) {
                event.reply("Bad syntax, should be: !raid admin tier5 Boss1;Boss2;Boss3");
                return;
            } else {
                final CopyOnWriteArrayList<String> currentTier5Bosses = new CopyOnWriteArrayList<>();
                currentTier5Bosses.addAll(Arrays.asList(bosses));
                BotService.currentTier5Bosses = currentTier5Bosses;
                event.reply("Set current tier5 boss list: " + StringUtils.join(bosses, ", "));
                return;
            }
        }
    }
    event.reply("No such command. Existing ones are:\n- userconfig {userid}\n- permissions\n" + "- clear tracking\n- announce {message}\n- ismember {userid} {guild name}\n- guilds\n" + " - member {userid}\n - test {pokemon} {start time} {gym}\n- tier5 {list of bosses ;-separated}");
}
Also used : LocalDateTime(java.time.LocalDateTime) User(net.dv8tion.jda.core.entities.User) JDA(net.dv8tion.jda.core.JDA) UserConfig(pokeraidbot.infrastructure.jpa.config.UserConfig) Config(pokeraidbot.infrastructure.jpa.config.Config) UserConfig(pokeraidbot.infrastructure.jpa.config.UserConfig) Guild(net.dv8tion.jda.core.entities.Guild) Raid(pokeraidbot.domain.raid.Raid) Permission(net.dv8tion.jda.core.Permission) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Member(net.dv8tion.jda.core.entities.Member) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

Config (pokeraidbot.infrastructure.jpa.config.Config)18 User (net.dv8tion.jda.core.entities.User)9 Guild (net.dv8tion.jda.core.entities.Guild)8 LocalDateTime (java.time.LocalDateTime)7 Gym (pokeraidbot.domain.gym.Gym)7 LocalTime (java.time.LocalTime)5 Test (org.junit.Test)5 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)5 Transactional (org.springframework.transaction.annotation.Transactional)3 HashMap (java.util.HashMap)2 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)2 CSVGymDataReader (pokeraidbot.infrastructure.CSVGymDataReader)2 RaidGroup (pokeraidbot.infrastructure.jpa.raid.RaidGroup)2 SocketTimeoutException (java.net.SocketTimeoutException)1 LocalDate (java.time.LocalDate)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Locale (java.util.Locale)1 Set (java.util.Set)1 Callable (java.util.concurrent.Callable)1