Search in sources :

Example 1 with Activity

use of net.dv8tion.jda.api.entities.Activity 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 Activity

use of net.dv8tion.jda.api.entities.Activity in project Ninbot by Nincodedo.

the class StreamListenerTest method userStartsStreamingNotAlreadyStreamingOnCooldown.

@Test
void userStartsStreamingNotAlreadyStreamingOnCooldown() {
    UserActivityStartEvent userActivityStartEvent = mock(UserActivityStartEvent.class);
    Member member = mock(Member.class);
    Guild guild = mock(Guild.class);
    Activity activity = mock(Activity.class);
    MessageAction messageAction = mock(MessageAction.class);
    AuditableRestAction auditableRestAction = mock(AuditableRestAction.class);
    when(configService.getValuesByName("123", ConfigConstants.STREAMING_ANNOUNCE_USERS)).thenReturn(List.of("123"));
    when(userActivityStartEvent.getMember()).thenReturn(member);
    when(member.getId()).thenReturn("123");
    when(userActivityStartEvent.getGuild()).thenReturn(guild);
    when(guild.getId()).thenReturn("123");
    when(userActivityStartEvent.getNewActivity()).thenReturn(activity);
    when(activity.getType()).thenReturn(Activity.ActivityType.STREAMING);
    streamListener.onGenericUserPresence(userActivityStartEvent);
    verify(messageAction, times(0)).queue();
    verify(auditableRestAction, times(0)).queue();
}
Also used : AuditableRestAction(net.dv8tion.jda.api.requests.restaction.AuditableRestAction) MessageAction(net.dv8tion.jda.api.requests.restaction.MessageAction) Activity(net.dv8tion.jda.api.entities.Activity) UserActivityStartEvent(net.dv8tion.jda.api.events.user.UserActivityStartEvent) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member) Test(org.junit.jupiter.api.Test)

Example 3 with Activity

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

the class PresenceUpdateHandler method handleActivities.

private void handleActivities(List<Activity> newActivities, @Nullable MemberImpl member, MemberPresenceImpl presence) {
    List<Activity> oldActivities = presence.getActivities();
    presence.setActivities(newActivities);
    if (member == null)
        return;
    boolean unorderedEquals = Helpers.deepEqualsUnordered(oldActivities, newActivities);
    if (unorderedEquals) {
        boolean deepEquals = Helpers.deepEquals(oldActivities, newActivities);
        if (!deepEquals) {
            getJDA().handleEvent(new UserUpdateActivityOrderEvent(getJDA(), responseNumber, oldActivities, member));
        }
    } else {
        getJDA().getEntityBuilder().updateMemberCache(member);
        // create modifiable copy
        List<Activity> stoppedActivities = new ArrayList<>(oldActivities);
        List<Activity> startedActivities = new ArrayList<>();
        for (Activity activity : newActivities) {
            if (!stoppedActivities.remove(activity))
                startedActivities.add(activity);
        }
        for (Activity activity : startedActivities) {
            getJDA().handleEvent(new UserActivityStartEvent(getJDA(), responseNumber, member, activity));
        }
        for (Activity activity : stoppedActivities) {
            getJDA().handleEvent(new UserActivityEndEvent(getJDA(), responseNumber, member, activity));
        }
        getJDA().handleEvent(new UserUpdateActivitiesEvent(getJDA(), responseNumber, member, oldActivities));
    }
}
Also used : UserActivityEndEvent(net.dv8tion.jda.api.events.user.UserActivityEndEvent) ArrayList(java.util.ArrayList) UserUpdateActivitiesEvent(net.dv8tion.jda.api.events.user.update.UserUpdateActivitiesEvent) Activity(net.dv8tion.jda.api.entities.Activity) UserUpdateActivityOrderEvent(net.dv8tion.jda.api.events.user.update.UserUpdateActivityOrderEvent) UserActivityStartEvent(net.dv8tion.jda.api.events.user.UserActivityStartEvent)

Example 4 with Activity

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

the class PresenceUpdateHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    // Ignore events for relationships, presences are guild only to us
    if (content.isNull("guild_id")) {
        log.debug("Received PRESENCE_UPDATE without guild_id. Ignoring event.");
        return null;
    }
    if (api.getCacheFlags().stream().noneMatch(CacheFlag::isPresence))
        return null;
    // Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked or not cached.
    final long guildId = content.getUnsignedLong("guild_id");
    if (getJDA().getGuildSetupController().isLocked(guildId))
        return guildId;
    GuildImpl guild = (GuildImpl) getJDA().getGuildById(guildId);
    if (guild == null) {
        getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle);
        EventCache.LOG.debug("Received a PRESENCE_UPDATE for a guild that is not yet cached! GuildId:{} UserId: {}", guildId, content.getObject("user").get("id"));
        return null;
    }
    CacheView.SimpleCacheView<MemberPresenceImpl> presences = guild.getPresenceView();
    if (presences == null)
        // technically this should be impossible
        return null;
    DataObject jsonUser = content.getObject("user");
    final long userId = jsonUser.getUnsignedLong("id");
    MemberImpl member = (MemberImpl) guild.getMemberById(userId);
    MemberPresenceImpl presence = presences.get(userId);
    OnlineStatus status = OnlineStatus.fromKey(content.getString("status"));
    if (status == OnlineStatus.OFFLINE)
        presences.remove(userId);
    if (presence == null) {
        presence = new MemberPresenceImpl();
        if (status != OnlineStatus.OFFLINE) {
            try (UnlockHook lock = presences.writeLock()) {
                presences.getMap().put(userId, presence);
            }
        }
    }
    // Now that we've update the User's info, lets see if we need to set the specific Presence information.
    // This is stored in the Member objects.
    // We set the activities to null to prevent parsing if the cache was disabled
    final DataArray activityArray = !getJDA().isCacheFlagSet(CacheFlag.ACTIVITY) || content.isNull("activities") ? null : content.getArray("activities");
    List<Activity> newActivities = new ArrayList<>();
    boolean parsedActivity = parseActivities(userId, activityArray, newActivities);
    if (getJDA().isCacheFlagSet(CacheFlag.CLIENT_STATUS) && !content.isNull("client_status"))
        handleClientStatus(content, presence);
    // Check if activities changed
    if (parsedActivity)
        handleActivities(newActivities, member, presence);
    if (presence.getOnlineStatus() != status) {
        OnlineStatus oldStatus = presence.getOnlineStatus();
        presence.setOnlineStatus(status);
        if (member != null) {
            getJDA().getEntityBuilder().updateMemberCache(member);
            getJDA().handleEvent(new UserUpdateOnlineStatusEvent(getJDA(), responseNumber, member, oldStatus));
        }
    }
    return null;
}
Also used : CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) MemberImpl(net.dv8tion.jda.internal.entities.MemberImpl) MemberPresenceImpl(net.dv8tion.jda.internal.entities.MemberPresenceImpl) OnlineStatus(net.dv8tion.jda.api.OnlineStatus) ArrayList(java.util.ArrayList) Activity(net.dv8tion.jda.api.entities.Activity) DataArray(net.dv8tion.jda.api.utils.data.DataArray) GuildImpl(net.dv8tion.jda.internal.entities.GuildImpl) DataObject(net.dv8tion.jda.api.utils.data.DataObject) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) UserUpdateOnlineStatusEvent(net.dv8tion.jda.api.events.user.update.UserUpdateOnlineStatusEvent)

Example 5 with Activity

use of net.dv8tion.jda.api.entities.Activity in project Ninbot by Nincodedo.

the class StreamListenerTest method userStartsStreamingNotAlreadyStreamingNoCooldown.

@Test
void userStartsStreamingNotAlreadyStreamingNoCooldown() {
    UserActivityStartEvent userActivityStartEvent = mock(UserActivityStartEvent.class);
    Member member = mock(Member.class);
    Guild guild = mock(Guild.class);
    Activity activity = mock(Activity.class);
    User user = mock(User.class);
    TextChannel textChannel = mock(TextChannel.class);
    MessageAction messageAction = mock(MessageAction.class);
    Role streamingRole = mock(Role.class);
    RichPresence richPresence = mock(RichPresence.class);
    AuditableRestAction auditableRestAction = mock(AuditableRestAction.class);
    Message message = mock(Message.class);
    when(configService.getValuesByName("123", ConfigConstants.STREAMING_ANNOUNCE_USERS)).thenReturn(List.of("123"));
    when(configService.getSingleValueByName("123", ConfigConstants.STREAMING_ANNOUNCE_CHANNEL)).thenReturn(Optional.of("123"));
    when(configService.getSingleValueByName("123", ConfigConstants.STREAMING_ROLE)).thenReturn(Optional.of("123"));
    when(userActivityStartEvent.getMember()).thenReturn(member);
    when(member.getUser()).thenReturn(user);
    when(member.getId()).thenReturn("123");
    when(userActivityStartEvent.getGuild()).thenReturn(guild);
    when(guild.getId()).thenReturn("123");
    when(userActivityStartEvent.getNewActivity()).thenReturn(activity);
    when(activity.getType()).thenReturn(Activity.ActivityType.STREAMING);
    when(userActivityStartEvent.getUser()).thenReturn(user);
    when(user.getName()).thenReturn("Nin");
    when(activity.isRich()).thenReturn(true);
    when(activity.asRichPresence()).thenReturn(richPresence);
    when(activity.getUrl()).thenReturn("https://twitch.tv/nincodedo");
    when(richPresence.getState()).thenReturn("Zeldo Breath of the Wild 2");
    when(guild.getLocale()).thenReturn(Locale.ENGLISH);
    when(guild.getMember(user)).thenReturn(member);
    when(guild.getTextChannelById("123")).thenReturn(textChannel);
    when(textChannel.sendMessage(any(Message.class))).thenReturn(messageAction);
    when(guild.getRoleById("123")).thenReturn(streamingRole);
    when(guild.addRoleToMember(member, streamingRole)).thenReturn(auditableRestAction);
    when(textChannel.getLatestMessageId()).thenReturn("123");
    when(textChannel.retrieveMessageById("123")).thenReturn(auditableRestAction);
    when(auditableRestAction.complete()).thenReturn(message);
    when(message.getContentRaw()).thenReturn("some other stream announcement");
    streamListener.onGenericUserPresence(userActivityStartEvent);
    verify(messageAction, times(1)).queue(any());
    verify(auditableRestAction, times(1)).queue();
}
Also used : Role(net.dv8tion.jda.api.entities.Role) TextChannel(net.dv8tion.jda.api.entities.TextChannel) User(net.dv8tion.jda.api.entities.User) AuditableRestAction(net.dv8tion.jda.api.requests.restaction.AuditableRestAction) Message(net.dv8tion.jda.api.entities.Message) MessageAction(net.dv8tion.jda.api.requests.restaction.MessageAction) Activity(net.dv8tion.jda.api.entities.Activity) UserActivityStartEvent(net.dv8tion.jda.api.events.user.UserActivityStartEvent) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member) RichPresence(net.dv8tion.jda.api.entities.RichPresence) Test(org.junit.jupiter.api.Test)

Aggregations

Activity (net.dv8tion.jda.api.entities.Activity)8 UserActivityStartEvent (net.dv8tion.jda.api.events.user.UserActivityStartEvent)4 Guild (net.dv8tion.jda.api.entities.Guild)3 Member (net.dv8tion.jda.api.entities.Member)3 ArrayList (java.util.ArrayList)2 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)2 AuditableRestAction (net.dv8tion.jda.api.requests.restaction.AuditableRestAction)2 MessageAction (net.dv8tion.jda.api.requests.restaction.MessageAction)2 Test (org.junit.jupiter.api.Test)2 Preconditions (com.google.common.base.Preconditions)1 ButtonInteractListener (dev.cerus.mapads.discordbot.listener.ButtonInteractListener)1 MessageDeleteListener (dev.cerus.mapads.discordbot.listener.MessageDeleteListener)1 java.util (java.util)1 UUID (java.util.UUID)1 CompletableFuture (java.util.concurrent.CompletableFuture)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