Search in sources :

Example 6 with DiscordException

use of sx.blah.discord.util.DiscordException in project DiscordSailv2 by Vaerys-Dawn.

the class Main method main.

public static void main(String[] args) throws UnknownHostException {
    // important, do not move
    PatchHandler.preInitPatches();
    logger = LoggerFactory.getLogger(Main.class);
    logger.info("Starting bot...");
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            logger.info(">>> Running Shutdown Process <<<");
            if (Globals.savingFiles) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Utility.sendStack(e);
                }
            }
            Globals.saveFiles(true);
        }
    });
    String token = null;
    // you need to set a token in Token/Token.txt for the bot to run
    try {
        Discord4J.disableAudio();
        FileHandler.createDirectory(Constants.DIRECTORY_STORAGE);
        FileHandler.createDirectory(Constants.DIRECTORY_GLOBAL_IMAGES);
        FileHandler.createDirectory(Constants.DIRECTORY_COMP);
        FileHandler.createDirectory(Constants.DIRECTORY_BACKUPS);
        FileHandler.createDirectory(Constants.DIRECTORY_TEMP);
        FileHandler.createDirectory(Constants.DIRECTORY_OLD_FILES);
        FileHandler.createDirectory(Constants.DIRECTORY_ERROR);
        // load config phase 1
        Config config = (Config) Config.create(Constants.FILE_CONFIG, new Config());
        GlobalData globalData = (GlobalData) GlobalData.create(Constants.FILE_GLOBAL_DATA, new GlobalData());
        config = Config.check(config);
        // getting bot token
        try {
            token = FileHandler.readFromFile(Constants.FILE_TOKEN).get(0);
        } catch (IndexOutOfBoundsException e) {
            logger.error("!!!BOT TOKEN NOT VALID PLEASE CHECK \"Storage/Token.txt\" AND UPDATE THE TOKEN!!!");
            System.exit(Constants.EXITCODE_STOP);
        }
        try {
            List<String> pastebinToken = FileHandler.readFromFile(Constants.FILE_PASTEBIN_TOKEN);
            Client.initPastebin(pastebinToken);
        } catch (IndexOutOfBoundsException e) {
            logger.info("No Pastebin Token found.");
        }
        // stuff that i cant getToggles to work because reasons, ignore completely
        // try{
        // List<String> richPresesnce = FileHandler.readFromFile(Constants.FILE_RPC_TOKEN);
        // Client.initRichPresence(richPresesnce);
        // }catch (IndexOutOfBoundsException e){
        // logger.info("Rich presence information missing.");
        // }
        // try {
        // List<String> imgurToken = FileHandler.readFromFile(Constants.FILE_IMGUR_TOKEN);
        // Client.initImgur(imgurToken);
        // } catch (IndexOutOfBoundsException e) {
        // logger.info("No Patreon Token found.");
        // }
        IDiscordClient client = Client.createClient(token, false);
        // load config phase 2
        Globals.initConfig(client, config, globalData);
        if (Globals.creatorID == 153159020528533505L) {
            try {
                List<String> patreonToken = FileHandler.readFromFile(Constants.FILE_PATREON_TOKEN);
                Client.initPatreon(patreonToken);
            } catch (IndexOutOfBoundsException e) {
                logger.info("No Patreon Token found.");
            }
        }
        Globals.validateConfig();
        if (Globals.errorStack != null) {
            logger.error(">\n> Begin Config Error Report <<\n" + "at " + Constants.DIRECTORY_STORAGE + Constants.FILE_CONFIG + "\n" + Globals.errorStack + ">> End Error Report <<");
            System.exit(Constants.EXITCODE_STOP);
        }
        ThreadGroup group = new ThreadGroup("GuildCreateGroup");
        final int[] count = new int[] { 0 };
        // login + register listener.
        client.login();
        // initialize creatorID if it is completely unset:
        if (config.creatorID == 0) {
            IUser botOwner = client.getApplicationOwner();
            config.creatorID = botOwner.getLongID();
            Globals.creatorID = config.creatorID;
            logger.info("Default creatorID set to user " + botOwner.getName() + "#" + botOwner.getDiscriminator());
            // save it back out to file.
            config.flushFile();
        }
        ExecutorService guildService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        ExecutorService commandService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        ExecutorService creatorService = new ThreadPoolExecutor(2, 50, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), r -> new Thread(group, r, group.getName() + "-Thread-" + ++count[0]));
        EventDispatcher dispatcher = client.getDispatcher();
        dispatcher.registerListener(guildService, new GuildCreateListener());
        dispatcher.registerListener(commandService, new AnnotationListener());
        dispatcher.registerListener(creatorService, new CreatorHandler());
        dispatcher.registerTemporaryListener(new InitEvent());
        // validate config file
        Globals.setVersion();
        // Init Patch system.
        // timed events getSlashCommands
        new TimerHandler();
    } catch (DiscordException ex) {
        logger.error(ex.getErrorMessage());
    } catch (RateLimitException e) {
        Utility.sendStack(e);
    }
}
Also used : RateLimitException(sx.blah.discord.util.RateLimitException) Config(com.github.vaerys.pogos.Config) IDiscordClient(sx.blah.discord.api.IDiscordClient) EventDispatcher(sx.blah.discord.api.events.EventDispatcher) GlobalData(com.github.vaerys.pogos.GlobalData) ExecutorService(java.util.concurrent.ExecutorService) DiscordException(sx.blah.discord.util.DiscordException) IUser(sx.blah.discord.handle.obj.IUser) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 7 with DiscordException

use of sx.blah.discord.util.DiscordException in project Ublisk by Derkades.

the class DiscordBot method onChat.

@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event) {
    if (!enabled) {
        super.log(this, LogLevel.DEBUG, "Skipping discord bot for this message - module has not been initialized successfully.");
        return;
    }
    Player player = event.getPlayer();
    String message = "[" + player.getName() + "] " + event.getMessage();
    IChannel channel = client.getChannelByID("310155421719724052");
    try {
        channel.sendMessage(message);
    } catch (MissingPermissionsException e) {
        e.printStackTrace();
    } catch (RateLimitException e) {
        e.printStackTrace();
    } catch (DiscordException e) {
        e.printStackTrace();
    }
}
Also used : Player(org.bukkit.entity.Player) IChannel(sx.blah.discord.handle.obj.IChannel) RateLimitException(sx.blah.discord.util.RateLimitException) DiscordException(sx.blah.discord.util.DiscordException) MissingPermissionsException(sx.blah.discord.util.MissingPermissionsException) EventHandler(org.bukkit.event.EventHandler)

Example 8 with DiscordException

use of sx.blah.discord.util.DiscordException in project KaellyBot by Kaysoro.

the class PrefixCommand method request.

@Override
public boolean request(IMessage message) {
    if (super.request(message)) {
        Language lg = Translator.getLanguageFrom(message.getChannel());
        if (isUserHasEnoughRights(message)) {
            Matcher m = getMatcher(message);
            m.find();
            String newPrefix = m.group(1).trim();
            if (newPrefix.length() >= 1 && newPrefix.length() <= Constants.prefixeLimit) {
                Guild.getGuild(message.getGuild()).setPrefixe(newPrefix);
                Message.sendText(message.getChannel(), Translator.getLabel(lg, "prefix.request.1").replace("{prefix}", getPrefixMdEscaped(message)));
                try {
                    Message.sendText(message.getGuild().getOwner().getOrCreatePMChannel(), Translator.getLabel(lg, "prefix.request.2").replace("{prefix}", getPrefixMdEscaped(message)).replace("{guild.name}", message.getGuild().getName()));
                } catch (DiscordException e) {
                    LOG.warn("request", "Impossible de contacter l'administrateur de la guilde [" + message.getGuild().getName() + "].");
                }
                return true;
            } else
                prefixeOutOfBounds.throwException(message, this, lg);
        } else
            noEnoughRights.throwException(message, this, lg);
    }
    return false;
}
Also used : Language(enums.Language) Matcher(java.util.regex.Matcher) AdvancedDiscordException(exceptions.AdvancedDiscordException) BasicDiscordException(exceptions.BasicDiscordException) DiscordException(sx.blah.discord.util.DiscordException)

Example 9 with DiscordException

use of sx.blah.discord.util.DiscordException in project KaellyBot by Kaysoro.

the class GuildCreateListener method onReady.

@EventSubscriber
public void onReady(GuildCreateEvent event) {
    try {
        if (!Guild.getGuilds().containsKey(event.getGuild().getStringID())) {
            Guild guild = new Guild(event.getGuild().getStringID(), event.getGuild().getName(), Translator.detectLanguage(event.getGuild().getDefaultChannel()));
            guild.addToDatabase();
            Language lg = guild.getLanguage();
            LOG.info("La guilde " + guild.getId() + " - " + guild.getName() + " a ajouté " + Constants.name);
            String customMessage = Translator.getLabel(lg, "welcome.message");
            customMessage = customMessage.replaceAll("\\{name\\}", Constants.name).replaceAll("\\{game\\}", Constants.game).replaceAll("\\{prefix\\}", Constants.prefixCommand).replaceAll("\\{help\\}", HelpCommand.NAME).replaceAll("\\{server\\}", new ServerCommand().getName()).replaceAll("\\{lang\\}", new LanguageCommand().getName()).replaceAll("\\{twitter\\}", new TwitterCommand().getName()).replaceAll("\\{almanax\\}", new AlmanaxCommand().getName()).replaceAll("\\{rss\\}", new RSSCommand().getName()).replaceAll("\\{owner\\}", event.getGuild().getOwner().mention()).replaceAll("\\{guild\\}", event.getGuild().getName());
            if (event.getGuild().getDefaultChannel() != null && event.getGuild().getDefaultChannel().getModifiedPermissions(ClientConfig.DISCORD().getOurUser()).contains(Permissions.SEND_MESSAGES))
                Message.sendText(event.getGuild().getDefaultChannel(), customMessage);
            else
                try {
                    Message.sendText(event.getGuild().getOwner().getOrCreatePMChannel(), customMessage);
                } catch (DiscordException e) {
                    LOG.warn("onReady", "Impossible de contacter l'administrateur de la guilde [" + guild.getName() + "].");
                }
            Message.sendText(ClientConfig.DISCORD().getChannelByID(Constants.chanReportID), "[NEW] **" + guild.getName() + "** (" + guild.getLanguage().getAbrev() + "), +" + event.getGuild().getUsers().size() + " utilisateurs");
        }
    } catch (Exception e) {
        Reporter.report(e, event.getGuild());
        LOG.error("onReady", e);
    }
}
Also used : Language(enums.Language) DiscordException(sx.blah.discord.util.DiscordException) LanguageCommand(commands.config.LanguageCommand) Guild(data.Guild) DiscordException(sx.blah.discord.util.DiscordException) ServerCommand(commands.config.ServerCommand) TwitterCommand(commands.config.TwitterCommand) AlmanaxCommand(commands.classic.AlmanaxCommand) RSSCommand(commands.config.RSSCommand) EventSubscriber(sx.blah.discord.api.events.EventSubscriber)

Example 10 with DiscordException

use of sx.blah.discord.util.DiscordException in project de-DiscordBot by DACH-Discord.

the class Authorization method createClient.

public static IDiscordClient createClient(final String token, final boolean login) {
    // Creates the ClientBuilder instance
    ClientBuilder clientBuilder = new ClientBuilder();
    // Adds the login info to the builder
    clientBuilder.withToken(token);
    try {
        if (login) {
            // Creates the client instance and logs the client in
            return clientBuilder.login();
        } else {
            // Creates the client instance but it doesn't log the client in yet, you would have to call client.login() yourself
            return clientBuilder.build();
        }
    } catch (DiscordException e) {
        // This is thrown if there was a problem building the client
        Util.error(e);
        return null;
    }
}
Also used : DiscordException(sx.blah.discord.util.DiscordException) ClientBuilder(sx.blah.discord.api.ClientBuilder)

Aggregations

DiscordException (sx.blah.discord.util.DiscordException)20 ClientBuilder (sx.blah.discord.api.ClientBuilder)7 IChannel (sx.blah.discord.handle.obj.IChannel)4 MissingPermissionsException (sx.blah.discord.util.MissingPermissionsException)4 RateLimitException (sx.blah.discord.util.RateLimitException)4 Language (enums.Language)3 IDiscordClient (sx.blah.discord.api.IDiscordClient)3 IGuild (sx.blah.discord.handle.obj.IGuild)3 IMessage (sx.blah.discord.handle.obj.IMessage)3 IUser (sx.blah.discord.handle.obj.IUser)3 ProfileObject (com.github.vaerys.objects.ProfileObject)2 TrackLikes (com.github.vaerys.objects.TrackLikes)2 Matcher (java.util.regex.Matcher)2 EventDispatcher (sx.blah.discord.api.events.EventDispatcher)2 DiscordClientImpl (sx.blah.discord.api.internal.DiscordClientImpl)2 IReaction (sx.blah.discord.handle.obj.IReaction)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 CommandObject (com.github.vaerys.commands.CommandObject)1 ChannelSetting (com.github.vaerys.enums.ChannelSetting)1 UserSetting (com.github.vaerys.enums.UserSetting)1