Search in sources :

Example 1 with SlowmodeHandler

use of org.geysermc.discordbot.listeners.SlowmodeHandler in project GeyserDiscordBot by GeyserMC.

the class GeyserBot method main.

public static void main(String[] args) throws IOException, LoginException {
    // Load properties into the PropertiesManager
    Properties prop = new Properties();
    prop.load(new FileInputStream("bot.properties"));
    PropertiesManager.loadProperties(prop);
    // Setup sentry.io
    if (PropertiesManager.getSentryDsn() != null) {
        LOGGER.info("Loading sentry.io...");
        Sentry.init(options -> {
            options.setDsn(PropertiesManager.getSentryDsn());
            options.setEnvironment(PropertiesManager.getSentryEnv());
            LOGGER.info("Sentry.io loaded");
        });
    }
    // Connect to github
    github = new GitHubBuilder().withOAuthToken(PropertiesManager.getGithubToken()).build();
    // Initialize the waiter
    EventWaiter waiter = new EventWaiter();
    // Load filters
    SwearHandler.loadFilters();
    // Load the db
    StorageType storageType = StorageType.getByName(PropertiesManager.getDatabaseType());
    if (storageType == StorageType.UNKNOWN) {
        LOGGER.error("Invalid database type! '" + PropertiesManager.getDatabaseType() + "'");
        System.exit(1);
    }
    try {
        storageManager = storageType.getStorageManager().getDeclaredConstructor().newInstance();
        storageManager.setupStorage();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        LOGGER.error("Unable to create database link!");
        System.exit(1);
    }
    // Setup the main client
    CommandClientBuilder client = new CommandClientBuilder();
    client.setActivity(null);
    // No owner
    client.setOwnerId("0");
    client.setPrefix(PropertiesManager.getPrefix());
    client.useHelpBuilder(false);
    client.addCommands(COMMANDS.toArray(new Command[0]));
    client.addSlashCommands(SLASH_COMMANDS.toArray(new SlashCommand[0]));
    client.setListener(new CommandErrorHandler());
    client.setCommandPreProcessBiFunction((event, command) -> !SwearHandler.filteredMessages.contains(event.getMessage().getIdLong()));
    // Setup the tag client
    CommandClientBuilder tagClient = new CommandClientBuilder();
    tagClient.setActivity(null);
    // No owner
    tagClient.setOwnerId("0");
    String tagPrefix = PropertiesManager.getPrefix() + PropertiesManager.getPrefix();
    tagClient.setPrefix(tagPrefix);
    tagClient.setPrefixes(new String[] { "!tag " });
    tagClient.useHelpBuilder(false);
    tagClient.addCommands(TagsManager.getTags().toArray(new Command[0]));
    tagClient.setListener(new TagsListener());
    tagClient.setCommandPreProcessBiFunction((event, command) -> !SwearHandler.filteredMessages.contains(event.getMessage().getIdLong()));
    tagClient.setManualUpsert(true);
    // Disable pings on replies
    MessageAction.setDefaultMentionRepliedUser(false);
    // Setup the thread pool
    generalThreadPool = Executors.newScheduledThreadPool(5);
    // Register JDA
    try {
        jda = JDABuilder.createDefault(PropertiesManager.getToken()).setChunkingFilter(ChunkingFilter.ALL).setMemberCachePolicy(MemberCachePolicy.ALL).enableIntents(GatewayIntent.GUILD_MEMBERS).enableIntents(GatewayIntent.GUILD_PRESENCES).enableCache(CacheFlag.ACTIVITY).enableCache(CacheFlag.ROLE_TAGS).setStatus(OnlineStatus.ONLINE).setActivity(Activity.playing("Booting...")).setEnableShutdownHook(true).setEventManager(new SentryEventManager()).addEventListeners(waiter, new LogHandler(), new SwearHandler(), new PersistentRoleHandler(), new FileHandler(), new LevelHandler(), new DumpHandler(), new ErrorAnalyzer(), new ShutdownHandler(), new VoiceGroupHandler(), new BadLinksHandler(), client.build(), tagClient.build()).build();
    } catch (IllegalArgumentException exception) {
        LOGGER.error("Failed to initialize JDA!", exception);
        System.exit(1);
    }
    // Register listeners
    jda.addEventListener();
    // Setup the http server
    if (PropertiesManager.enableWeb()) {
        try {
            httpServer = new Server();
            httpServer.start();
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        }
    }
    // Setup the update check scheduler
    UpdateManager.setup();
    // Setup the health check scheduler
    HealthCheckerManager.setup();
    // Setup the rss feed check scheduler
    RssFeedManager.setup();
    // Setup all slow mode handlers
    generalThreadPool.schedule(() -> {
        for (Guild guild : jda.getGuilds()) {
            for (SlowModeInfo info : storageManager.getSlowModeChannels(guild)) {
                jda.addEventListener(new SlowmodeHandler(info.getChannel(), info.getDelay()));
            }
        }
    }, 5, TimeUnit.SECONDS);
    // Start the bStats tracking thread
    generalThreadPool.scheduleAtFixedRate(() -> {
        JSONArray servers = new JSONArray(RestClient.get("https://bstats.org/api/v1/plugins/5273/charts/servers/data"));
        JSONArray players = new JSONArray(RestClient.get("https://bstats.org/api/v1/plugins/5273/charts/players/data"));
        int serverCount = servers.getJSONArray(servers.length() - 1).getInt(1);
        int playerCount = players.getJSONArray(players.length() - 1).getInt(1);
        jda.getPresence().setActivity(Activity.playing(BotHelpers.coolFormat(serverCount) + " servers, " + BotHelpers.coolFormat(playerCount) + " players"));
    }, 5, 60 * 5, TimeUnit.SECONDS);
}
Also used : SlowmodeHandler(org.geysermc.discordbot.listeners.SlowmodeHandler) SentryEventManager(org.geysermc.discordbot.util.SentryEventManager) SwearHandler(org.geysermc.discordbot.listeners.SwearHandler) Server(org.geysermc.discordbot.http.Server) GitHubBuilder(org.kohsuke.github.GitHubBuilder) Properties(java.util.Properties) Guild(net.dv8tion.jda.api.entities.Guild) ErrorAnalyzer(org.geysermc.discordbot.listeners.ErrorAnalyzer) SlashCommand(com.jagrosh.jdautilities.command.SlashCommand) LogHandler(org.geysermc.discordbot.listeners.LogHandler) LevelHandler(org.geysermc.discordbot.listeners.LevelHandler) SlowModeInfo(org.geysermc.discordbot.storage.SlowModeInfo) ShutdownHandler(org.geysermc.discordbot.listeners.ShutdownHandler) TagsListener(org.geysermc.discordbot.tags.TagsListener) StorageType(org.geysermc.discordbot.storage.StorageType) CommandErrorHandler(org.geysermc.discordbot.listeners.CommandErrorHandler) JSONArray(org.json.JSONArray) EventWaiter(com.jagrosh.jdautilities.commons.waiter.EventWaiter) DumpHandler(org.geysermc.discordbot.listeners.DumpHandler) FileInputStream(java.io.FileInputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CommandClientBuilder(com.jagrosh.jdautilities.command.CommandClientBuilder) LoginException(javax.security.auth.login.LoginException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) FileHandler(org.geysermc.discordbot.listeners.FileHandler) PersistentRoleHandler(org.geysermc.discordbot.listeners.PersistentRoleHandler) BadLinksHandler(org.geysermc.discordbot.listeners.BadLinksHandler) SlashCommand(com.jagrosh.jdautilities.command.SlashCommand) Command(com.jagrosh.jdautilities.command.Command) VoiceGroupHandler(org.geysermc.discordbot.listeners.VoiceGroupHandler)

Example 2 with SlowmodeHandler

use of org.geysermc.discordbot.listeners.SlowmodeHandler in project GeyserDiscordBot by GeyserMC.

the class SlowmodeCommand method execute.

@Override
protected void execute(CommandEvent event) {
    List<String> args = new ArrayList<>(Arrays.asList(event.getArgs().split(" ")));
    // Check if a time string was specified
    if (args.size() >= 1 && args.get(0).trim().isEmpty()) {
        event.getMessage().replyEmbeds(new EmbedBuilder().setTitle("Invalid usage").setDescription("Please specify a time in the correct format `1h2m3s`.").setColor(BotColors.FAILURE.getColor()).build()).queue();
        return;
    }
    MessageEmbed slowmodeEmbed;
    if (args.get(0).trim().equals("off")) {
        for (Object listener : event.getJDA().getEventManager().getRegisteredListeners()) {
            if (listener instanceof SlowmodeHandler) {
                if (((SlowmodeHandler) listener).getChannelId() == event.getTextChannel().getIdLong()) {
                    event.getJDA().getEventManager().unregister(listener);
                    break;
                }
            }
        }
        GeyserBot.storageManager.setSlowModeChannel(event.getTextChannel(), 0);
        slowmodeEmbed = new EmbedBuilder().setTitle("Slowmode").setDescription("Slowmode disabled for " + event.getTextChannel().getAsMention() + " by " + event.getAuthor().getAsMention()).setTimestamp(Instant.now()).setColor(BotColors.SUCCESS.getColor()).build();
    } else {
        // Get the time
        int delay = BotHelpers.parseTimeString(args.get(0));
        // Check if time is valid
        if (delay == 0) {
            event.getMessage().replyEmbeds(new EmbedBuilder().setTitle("Invalid usage").setDescription("Please specify a time in the correct format `1h2m3s`.").setColor(BotColors.FAILURE.getColor()).build()).queue();
            return;
        }
        slowmodeEmbed = new EmbedBuilder().setTitle("Slowmode").setDescription("Slowmode updated for " + event.getTextChannel().getAsMention() + " set to `" + args.get(0) + "` (" + delay + "s) by " + event.getAuthor().getAsMention()).setTimestamp(Instant.now()).setColor(BotColors.SUCCESS.getColor()).build();
        boolean found = false;
        for (Object listener : event.getJDA().getEventManager().getRegisteredListeners()) {
            if (listener instanceof SlowmodeHandler) {
                if (((SlowmodeHandler) listener).getChannelId() == event.getTextChannel().getIdLong()) {
                    ((SlowmodeHandler) listener).setSeconds(delay);
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            event.getJDA().addEventListener(new SlowmodeHandler(event.getTextChannel().getIdLong(), delay));
        }
        // Update the db
        GeyserBot.storageManager.setSlowModeChannel(event.getTextChannel(), delay);
    }
    // Send the embed as a reply and to the log
    ServerSettings.getLogChannel(event.getGuild()).sendMessageEmbeds(slowmodeEmbed).queue();
    event.getMessage().replyEmbeds(slowmodeEmbed).queue();
}
Also used : SlowmodeHandler(org.geysermc.discordbot.listeners.SlowmodeHandler) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayList(java.util.ArrayList)

Aggregations

SlowmodeHandler (org.geysermc.discordbot.listeners.SlowmodeHandler)2 Command (com.jagrosh.jdautilities.command.Command)1 CommandClientBuilder (com.jagrosh.jdautilities.command.CommandClientBuilder)1 SlashCommand (com.jagrosh.jdautilities.command.SlashCommand)1 EventWaiter (com.jagrosh.jdautilities.commons.waiter.EventWaiter)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 LoginException (javax.security.auth.login.LoginException)1 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)1 Guild (net.dv8tion.jda.api.entities.Guild)1 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)1 Server (org.geysermc.discordbot.http.Server)1 BadLinksHandler (org.geysermc.discordbot.listeners.BadLinksHandler)1 CommandErrorHandler (org.geysermc.discordbot.listeners.CommandErrorHandler)1 DumpHandler (org.geysermc.discordbot.listeners.DumpHandler)1 ErrorAnalyzer (org.geysermc.discordbot.listeners.ErrorAnalyzer)1 FileHandler (org.geysermc.discordbot.listeners.FileHandler)1