Search in sources :

Example 1 with ApplicationInfo

use of net.dv8tion.jda.api.entities.ApplicationInfo in project Utility by anweisen.

the class DiscordBot method init.

protected final void init() throws Exception {
    if (initialized)
        throw new IllegalStateException("init() was already called");
    initialized = true;
    builder = builder().validate();
    DiscordBotBuilder.logger.debug("Building bot with following configuration:" + "\n\t" + config + "\n\t" + builder + "\n\t" + (builder.databaseConfig == null ? "BotDatabaseConfig{null}" : builder.databaseConfig));
    boolean requireDatabase = builder.databaseConfig != null || !builder.tables.isEmpty() || builder.requireDatabase;
    if (builder.databaseConfig == null) {
        builder.databaseConfig = new BotDatabaseConfig("guilds", "guildId", null, null, null);
    }
    if (requireDatabase) {
        database = config.createDatabase();
        database.connect();
        builder.tables.forEach((ExceptionallyBiConsumer<String, SQLColumn[]>) database::createTable);
    } else {
        database = Database.unsupported();
    }
    builder.fileLanguages.addAll(config.getLanguageFiles());
    commandManager = new DefaultCommandManager(builder.databaseConfig.getPrefixColumn() == null ? new ConstantPrefixProvider(config.getDefaultPrefix()) : new DatabasePrefixProvider(config.getDefaultPrefix(), database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getPrefixColumn())).setUseEmbeds(builder.useEmbeds);
    if (builder.databaseConfig.getTeamRoleColumn() != null) {
        commandManager.setTeamRoleManager(new DatabaseTeamRoleManager(database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getTeamRoleColumn()));
    }
    if (builder.databaseConfig.getLanguageColumn() != null) {
        LanguageManager languageManager = new DatabaseLanguageManager(database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getLanguageColumn());
        commandManager.setLanguageManager(languageManager);
        for (String filename : builder.fileLanguages) languageManager.readFile(filename);
        for (String filename : builder.resourceLanguages) languageManager.readResource(filename);
        languageManager.setDefaultLanguage(config.getDefaultLanguage());
    } else if (!builder.fileLanguages.isEmpty() || !builder.resourceLanguages.isEmpty()) {
        DiscordBotBuilder.logger.warn("Languages were registered but no database for language management is setup!");
        LanguageManager languageManager = new ConstantLanguageManager();
        commandManager.setLanguageManager(languageManager);
        for (String filename : builder.fileLanguages) languageManager.readFile(filename);
        for (String filename : builder.resourceLanguages) languageManager.readResource(filename);
        languageManager.setDefaultLanguage(config.getDefaultLanguage());
    }
    builder.parsers.forEach((key, parser) -> commandManager.getParserContext().registerParser(key, parser.getFirst(), parser.getSecond()));
    commandManager.register(builder.commands);
    builder.taskCommands.forEach(pair -> commandManager.register(pair.getFirst(), pair.getSecond()));
    List<GatewayIntent> intents = Arrays.asList(builder.intents);
    if (!intents.contains(GatewayIntent.DIRECT_MESSAGES))
        DiscordBotBuilder.logger.warn("Missing GatewayIntent.DIRECT_MESSAGES, no commands will be available in private chats");
    if (!intents.contains(GatewayIntent.GUILD_MESSAGES))
        DiscordBotBuilder.logger.warn("Missing GatewayIntent.GUILD_MESSAGES, no commands will be available in guild chats");
    DefaultShardManagerBuilder shardManagerBuilder = DefaultShardManagerBuilder.create(config.getToken(), intents).setCallbackPoolProvider(newThreadPoolProvider("Callback")).setEventPoolProvider(newThreadPoolProvider("Events")).setShardsTotal(config.getShards()).setMemberCachePolicy(builder.memberCachePolicy).setEventManagerProvider(shardId -> eventManager).setStatusProvider(shardId -> config.getOnlineStatus()).addEventListeners(new CommandListener(commandManager), this);
    if (builder.chunkingFilter != null)
        shardManagerBuilder.setChunkingFilter(builder.chunkingFilter);
    builder.builderSettings.forEach(action -> action.accept(shardManagerBuilder));
    builder.listener.forEach(shardManagerBuilder::addEventListeners);
    for (CacheFlag cache : CacheFlag.values()) {
        if (builder.cacheFlags.contains(cache)) {
            shardManagerBuilder.enableCache(cache);
        } else {
            shardManagerBuilder.disableCache(cache);
        }
    }
    shardManager = shardManagerBuilder.build();
    builder.shardManagerSettings.forEach(action -> action.accept(shardManager));
    if (!builder.customSlashCommands.isEmpty())
        getJDA().updateCommands().addCommands(builder.customSlashCommands).queue();
    else if (!builder.disableAutoSlashCommands)
        commandManager.setupSlashCommands(getJDA());
    getJDA().retrieveApplicationInfo().queue(applicationInfo -> this.applicationInfo = applicationInfo);
    onStart();
    if (!builder.activities.isEmpty()) {
        new Timer("BotActivityChanger").schedule(new TimerTask() {

            private int index = 0;

            @Override
            public void run() {
                if (index >= builder.activities.size()) {
                    index = 0;
                }
                Supplier<? extends Activity> activitySupplier = builder.activities.get(index);
                Activity activity = activitySupplier.get();
                shardManager.setActivity(activity);
                index++;
            }
        }, 3000, builder.activityUpdateRate * 1000L);
    }
}
Also used : DatabasePrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.DatabasePrefixProvider) ThreadPoolProvider(net.dv8tion.jda.api.sharding.ThreadPoolProvider) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) DefaultShardManagerBuilder(net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) ReadyEvent(net.dv8tion.jda.api.events.ReadyEvent) Supplier(java.util.function.Supplier) Status(net.dv8tion.jda.api.JDA.Status) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) ConfigProvider(net.anweisen.utilities.jda.manager.bot.config.ConfigProvider) SQLColumn(net.anweisen.utilities.database.SQLColumn) CommandManager(net.anweisen.utilities.jda.manager.CommandManager) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExceptionallyBiConsumer(net.anweisen.utilities.common.function.ExceptionallyBiConsumer) LanguageManager(net.anweisen.utilities.jda.manager.language.LanguageManager) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) DefaultCommandManager(net.anweisen.utilities.jda.manager.impl.DefaultCommandManager) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) Nonnull(javax.annotation.Nonnull) Database(net.anweisen.utilities.database.Database) ExecutorService(java.util.concurrent.ExecutorService) ConstantPrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.ConstantPrefixProvider) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) NamedThreadFactory(net.anweisen.utilities.common.collection.NamedThreadFactory) ActionEventListener(net.anweisen.utilities.jda.manager.listener.manager.ActionEventListener) Activity(net.dv8tion.jda.api.entities.Activity) BotConfigCreator(net.anweisen.utilities.jda.manager.bot.config.BotConfigCreator) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Consumer(java.util.function.Consumer) SubscribeEvent(net.dv8tion.jda.api.hooks.SubscribeEvent) CheckReturnValue(javax.annotation.CheckReturnValue) CommandListener(net.anweisen.utilities.jda.manager.listener.CommandListener) CombinedEventManager(net.anweisen.utilities.jda.manager.listener.manager.CombinedEventManager) DatabaseTeamRoleManager(net.anweisen.utilities.jda.manager.impl.DatabaseTeamRoleManager) ILogger(net.anweisen.utilities.common.logging.ILogger) Preconditions(com.google.common.base.Preconditions) IEventManager(net.dv8tion.jda.api.hooks.IEventManager) FileDocument(net.anweisen.utilities.common.config.FileDocument) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) ApplicationInfo(net.dv8tion.jda.api.entities.ApplicationInfo) ConstantPrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.ConstantPrefixProvider) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) DatabasePrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.DatabasePrefixProvider) Activity(net.dv8tion.jda.api.entities.Activity) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) DefaultCommandManager(net.anweisen.utilities.jda.manager.impl.DefaultCommandManager) DatabaseTeamRoleManager(net.anweisen.utilities.jda.manager.impl.DatabaseTeamRoleManager) CommandListener(net.anweisen.utilities.jda.manager.listener.CommandListener) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) DefaultShardManagerBuilder(net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) LanguageManager(net.anweisen.utilities.jda.manager.language.LanguageManager) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) Supplier(java.util.function.Supplier)

Example 2 with ApplicationInfo

use of net.dv8tion.jda.api.entities.ApplicationInfo in project flowermoon by wolf-yuan-6115.

the class AboutCommand method execute.

@Override
protected void execute(CommandEvent event) {
    if (oauthLink == null) {
        try {
            ApplicationInfo info = event.getJDA().retrieveApplicationInfo().complete();
            oauthLink = info.isBotPublic() ? info.getInviteUrl(0L, perms) : "";
        } catch (Exception e) {
            Logger log = LoggerFactory.getLogger("OAuth2");
            log.error("Could not generate invite link ", e);
            oauthLink = "";
        }
    }
    EmbedBuilder builder = new EmbedBuilder();
    builder.setColor(event.isFromType(ChannelType.TEXT) ? event.getGuild().getSelfMember().getColor() : color);
    builder.setAuthor(event.getSelfUser().getName() + " 的個人資料!", null, event.getSelfUser().getAvatarUrl());
    boolean join = !(event.getClient().getServerInvite() == null || event.getClient().getServerInvite().isEmpty());
    boolean inv = !oauthLink.isEmpty();
    String invline = "\n" + (join ? "Join my server [`here`](" + event.getClient().getServerInvite() + ")" : (inv ? "請 " : "")) + (inv ? (join ? ", 或 " : "") + "[`邀請`](" + oauthLink + ") 我到你的伺服器" : "") + "!";
    String author = event.getJDA().getUserById(event.getClient().getOwnerId()) == null ? "<@" + event.getClient().getOwnerId() + ">" : event.getJDA().getUserById(event.getClient().getOwnerId()).getName();
    StringBuilder descr = new StringBuilder().append("你好! 我是 **").append(event.getSelfUser().getName()).append("**, ").append(description).append("\n我").append(IS_AUTHOR ? "使用Java寫成" : "的擁有者是").append(" **").append(author).append("** 正在使用 " + JDAUtilitiesInfo.AUTHOR + "的 [指令擴充](" + JDAUtilitiesInfo.GITHUB + ") (").append(JDAUtilitiesInfo.VERSION).append(") 以及 [JDA 程式庫](https://github.com/DV8FromTheWorld/JDA) (").append(JDAInfo.VERSION).append(")\n\n這個中文版本是由Wolf yuan翻譯,可以在 [這裡](https://github.com/wolf-yuan-6115/flowermoon) 下載\n輸入 `").append(event.getClient().getTextualPrefix()).append(event.getClient().getHelpWord()).append("` 來看見我的指令!").append(join || inv ? invline : "").append("\n\n我擁有這些功能: ```css");
    for (String feature : features) descr.append("\n").append(event.getClient().getSuccess().startsWith("<") ? REPLACEMENT_ICON : event.getClient().getSuccess()).append(" ").append(feature);
    descr.append(" ```");
    builder.setDescription(descr);
    if (event.getJDA().getShardInfo() == null) {
        builder.addField("狀態", event.getJDA().getGuilds().size() + " 個伺服器\n1 個分片", true);
        builder.addField("使用者", event.getJDA().getUsers().size() + " 個用戶\n" + event.getJDA().getGuilds().stream().mapToInt(g -> g.getMembers().size()).sum() + " total", true);
        builder.addField("頻道", event.getJDA().getTextChannels().size() + " 個文字頻道\n" + event.getJDA().getVoiceChannels().size() + " 個語音頻道", true);
    } else {
        builder.addField("狀態", (event.getClient()).getTotalGuilds() + " 個伺服器\n於分片 " + (event.getJDA().getShardInfo().getShardId() + 1) + "/" + event.getJDA().getShardInfo().getShardTotal() + "上", true);
        builder.addField("此分片有", event.getJDA().getUsers().size() + " 個使用者\n" + event.getJDA().getGuilds().size() + " 個伺服器", true);
        builder.addField("", event.getJDA().getTextChannels().size() + " 個文字頻道\n" + event.getJDA().getVoiceChannels().size() + " 個語音頻道", true);
    }
    builder.setFooter("最後一次重新啟動", null);
    builder.setTimestamp(event.getClient().getStartTime());
    event.reply(builder.build());
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ApplicationInfo(net.dv8tion.jda.api.entities.ApplicationInfo) Logger(org.slf4j.Logger)

Aggregations

ApplicationInfo (net.dv8tion.jda.api.entities.ApplicationInfo)2 Preconditions (com.google.common.base.Preconditions)1 java.util (java.util)1 ExecutorService (java.util.concurrent.ExecutorService)1 Executors (java.util.concurrent.Executors)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 Consumer (java.util.function.Consumer)1 Supplier (java.util.function.Supplier)1 Collectors (java.util.stream.Collectors)1 CheckReturnValue (javax.annotation.CheckReturnValue)1 Nonnull (javax.annotation.Nonnull)1 NamedThreadFactory (net.anweisen.utilities.common.collection.NamedThreadFactory)1 FileDocument (net.anweisen.utilities.common.config.FileDocument)1 ExceptionallyBiConsumer (net.anweisen.utilities.common.function.ExceptionallyBiConsumer)1 ILogger (net.anweisen.utilities.common.logging.ILogger)1 Database (net.anweisen.utilities.database.Database)1 SQLColumn (net.anweisen.utilities.database.SQLColumn)1 CommandManager (net.anweisen.utilities.jda.manager.CommandManager)1 BotConfigCreator (net.anweisen.utilities.jda.manager.bot.config.BotConfigCreator)1 ConfigProvider (net.anweisen.utilities.jda.manager.bot.config.ConfigProvider)1