Search in sources :

Example 36 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class CommandDataTest method testNormal.

@Test
public void testNormal() {
    CommandData command = new CommandDataImpl("ban", "Ban a user from this server").setDefaultEnabled(false).addOption(OptionType.USER, "user", "The user to ban", // required before non-required
    true).addOption(OptionType.STRING, "reason", // test that default is false
    "The ban reason").addOption(OptionType.INTEGER, "days", "The duration of the ban", // test with explicit false
    false);
    DataObject data = command.toData();
    Assertions.assertEquals("ban", data.getString("name"));
    Assertions.assertEquals("Ban a user from this server", data.getString("description"));
    Assertions.assertFalse(data.getBoolean("default_permission"));
    DataArray options = data.getArray("options");
    DataObject option = options.getObject(0);
    Assertions.assertTrue(option.getBoolean("required"));
    Assertions.assertEquals("user", option.getString("name"));
    Assertions.assertEquals("The user to ban", option.getString("description"));
    option = options.getObject(1);
    Assertions.assertFalse(option.getBoolean("required"));
    Assertions.assertEquals("reason", option.getString("name"));
    Assertions.assertEquals("The ban reason", option.getString("description"));
    option = options.getObject(2);
    Assertions.assertFalse(option.getBoolean("required"));
    Assertions.assertEquals("days", option.getString("name"));
    Assertions.assertEquals("The duration of the ban", option.getString("description"));
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) CommandDataImpl(net.dv8tion.jda.internal.interactions.CommandDataImpl) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Test(org.junit.jupiter.api.Test)

Example 37 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class EntityBuilder method createEmote.

public EmoteImpl createEmote(GuildImpl guildObj, DataObject json) {
    DataArray emoteRoles = json.optArray("roles").orElseGet(DataArray::empty);
    final long emoteId = json.getLong("id");
    final User user = json.isNull("user") ? null : createUser(json.getObject("user"));
    EmoteImpl emoteObj = (EmoteImpl) guildObj.getEmoteById(emoteId);
    if (emoteObj == null)
        emoteObj = new EmoteImpl(emoteId, guildObj);
    Set<Role> roleSet = emoteObj.getRoleSet();
    roleSet.clear();
    for (int j = 0; j < emoteRoles.length(); j++) {
        Role role = guildObj.getRoleById(emoteRoles.getString(j));
        if (role != null)
            roleSet.add(role);
    }
    if (user != null)
        emoteObj.setUser(user);
    return emoteObj.setName(json.getString("name", "")).setAnimated(json.getBoolean("animated")).setManaged(json.getBoolean("managed")).setAvailable(json.getBoolean("available", true));
}
Also used : TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Example 38 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class EntityBuilder method createMessage0.

private ReceivedMessage createMessage0(DataObject jsonObject, @Nonnull MessageChannel channel, boolean modifyCache) {
    final long id = jsonObject.getLong("id");
    final DataObject author = jsonObject.getObject("author");
    final long authorId = author.getLong("id");
    MemberImpl member = null;
    if (channel.getType().isGuild() && !jsonObject.isNull("member")) {
        DataObject memberJson = jsonObject.getObject("member");
        memberJson.put("user", author);
        GuildChannel guildChannel = (GuildChannel) channel;
        Guild guild = guildChannel.getGuild();
        member = createMember((GuildImpl) guild, memberJson);
        if (modifyCache) {
            // Update member cache with new information if needed
            updateMemberCache(member);
        }
    }
    final String content = jsonObject.getString("content", "");
    final boolean fromWebhook = jsonObject.hasKey("webhook_id");
    final boolean pinned = jsonObject.getBoolean("pinned");
    final boolean tts = jsonObject.getBoolean("tts");
    final boolean mentionsEveryone = jsonObject.getBoolean("mention_everyone");
    final OffsetDateTime editTime = jsonObject.isNull("edited_timestamp") ? null : OffsetDateTime.parse(jsonObject.getString("edited_timestamp"));
    final String nonce = jsonObject.isNull("nonce") ? null : jsonObject.get("nonce").toString();
    final int flags = jsonObject.getInt("flags", 0);
    // because java
    MessageChannel tmpChannel = channel;
    final List<Message.Attachment> attachments = map(jsonObject, "attachments", this::createMessageAttachment);
    final List<MessageEmbed> embeds = map(jsonObject, "embeds", this::createMessageEmbed);
    final List<MessageReaction> reactions = map(jsonObject, "reactions", (obj) -> createMessageReaction(tmpChannel, id, obj));
    final List<MessageSticker> stickers = map(jsonObject, "sticker_items", this::createSticker);
    MessageActivity activity = null;
    if (!jsonObject.isNull("activity"))
        activity = createMessageActivity(jsonObject);
    User user;
    if (channel.getType().isGuild()) {
        Guild guild = ((GuildChannel) channel).getGuild();
        if (member == null)
            member = (MemberImpl) guild.getMemberById(authorId);
        user = member != null ? member.getUser() : null;
        if (user == null) {
            if (fromWebhook || !modifyCache)
                user = createUser(author);
            else
                // Specifically for MESSAGE_CREATE
                throw new IllegalArgumentException(MISSING_USER);
        }
    } else {
        // Assume private channel
        if (authorId == getJDA().getSelfUser().getIdLong()) {
            user = getJDA().getSelfUser();
        } else {
            // Note, while PrivateChannel.getUser() can produce null, this invocation of it WILL NOT produce null
            // because when the bot receives a message in a private channel that was _not authored by the bot_ then
            // the message had to have come from the user, so that means that we had all the information to build
            // the channel properly (or fill-in the missing user info of an existing partial channel)
            user = ((PrivateChannel) channel).getUser();
        }
    }
    if (// update the user information on message receive
    modifyCache && !fromWebhook)
        updateUser((UserImpl) user, author);
    TLongSet mentionedRoles = new TLongHashSet();
    TLongSet mentionedUsers = new TLongHashSet(map(jsonObject, "mentions", (o) -> o.getLong("id")));
    Optional<DataArray> roleMentionArr = jsonObject.optArray("mention_roles");
    roleMentionArr.ifPresent((arr) -> {
        for (int i = 0; i < arr.length(); i++) mentionedRoles.add(arr.getLong(i));
    });
    MessageType type = MessageType.fromId(jsonObject.getInt("type"));
    ReceivedMessage message;
    Message referencedMessage = null;
    if (!jsonObject.isNull("referenced_message")) {
        DataObject referenceJson = jsonObject.getObject("referenced_message");
        try {
            referencedMessage = createMessage0(referenceJson, channel, false);
        } catch (IllegalArgumentException ex) {
            // We can just discard the message for some trivial cases
            if (UNKNOWN_MESSAGE_TYPE.equals(ex.getMessage()))
                LOG.debug("Received referenced message with unknown type. Type: {}", referenceJson.getInt("type", -1));
            else if (MISSING_CHANNEL.equals(ex.getMessage()))
                LOG.debug("Received referenced message with unknown channel. channel_id: {} Type: {}", referenceJson.getUnsignedLong("channel_id", 0), referenceJson.getInt("type", -1));
            else
                throw ex;
        }
    }
    MessageReference messageReference = null;
    if (// always contains the channel + message id for a referenced message
    !jsonObject.isNull("message_reference")) {
        // used for when referenced_message is not provided
        DataObject messageReferenceJson = jsonObject.getObject("message_reference");
        messageReference = new MessageReference(messageReferenceJson.getLong("message_id", 0), messageReferenceJson.getLong("channel_id", 0), messageReferenceJson.getLong("guild_id", 0), referencedMessage, api);
    }
    List<ActionRow> components = Collections.emptyList();
    Optional<DataArray> componentsArrayOpt = jsonObject.optArray("components");
    if (componentsArrayOpt.isPresent()) {
        DataArray array = componentsArrayOpt.get();
        components = array.stream(DataArray::getObject).filter(it -> it.getInt("type", 0) == 1).map(ActionRow::fromData).collect(Collectors.toList());
    }
    Message.Interaction messageInteraction = null;
    if (!jsonObject.isNull("interaction")) {
        GuildImpl guild = null;
        if (channel instanceof GuildChannel) {
            guild = (GuildImpl) ((GuildChannel) (channel)).getGuild();
        }
        messageInteraction = createMessageInteraction(guild, jsonObject.getObject("interaction"));
    }
    if (type == MessageType.UNKNOWN)
        throw new IllegalArgumentException(UNKNOWN_MESSAGE_TYPE);
    if (!type.isSystem()) {
        message = new ReceivedMessage(id, channel, type, messageReference, fromWebhook, mentionsEveryone, mentionedUsers, mentionedRoles, tts, pinned, content, nonce, user, member, activity, editTime, reactions, attachments, embeds, stickers, components, flags, messageInteraction);
    } else {
        message = new SystemMessage(id, channel, type, messageReference, fromWebhook, mentionsEveryone, mentionedUsers, mentionedRoles, tts, pinned, content, nonce, user, member, activity, editTime, reactions, attachments, embeds, stickers, flags);
        // We don't need to parse mentions for system messages, they are always empty anyway
        return message;
    }
    GuildImpl guild = message.isFromGuild() ? (GuildImpl) message.getGuild() : null;
    // Load users/members from message object through mentions
    List<User> mentionedUsersList = new ArrayList<>();
    List<Member> mentionedMembersList = new ArrayList<>();
    DataArray userMentions = jsonObject.getArray("mentions");
    for (int i = 0; i < userMentions.length(); i++) {
        DataObject mentionJson = userMentions.getObject(i);
        if (guild == null || mentionJson.isNull("member")) {
            // Can't load user without member context so fake them if possible
            User mentionedUser = createUser(mentionJson);
            mentionedUsersList.add(mentionedUser);
            if (guild != null) {
                Member mentionedMember = guild.getMember(mentionedUser);
                if (mentionedMember != null)
                    mentionedMembersList.add(mentionedMember);
            }
            continue;
        }
        // Load member/user from mention (gateway messages only)
        DataObject memberJson = mentionJson.getObject("member");
        mentionJson.remove("member");
        memberJson.put("user", mentionJson);
        Member mentionedMember = createMember(guild, memberJson);
        mentionedMembersList.add(mentionedMember);
        mentionedUsersList.add(mentionedMember.getUser());
    }
    message.setMentions(mentionedUsersList, mentionedMembersList);
    return message;
}
Also used : MemberCacheViewImpl(net.dv8tion.jda.internal.utils.cache.MemberCacheViewImpl) NotificationLevel(net.dv8tion.jda.api.entities.Guild.NotificationLevel) ExplicitContentLevel(net.dv8tion.jda.api.entities.Guild.ExplicitContentLevel) UnaryOperator(java.util.function.UnaryOperator) UserUpdateAvatarEvent(net.dv8tion.jda.api.events.user.update.UserUpdateAvatarEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) UserUpdateFlagsEvent(net.dv8tion.jda.api.events.user.update.UserUpdateFlagsEvent) TLongHashSet(gnu.trove.set.hash.TLongHashSet) JDAImpl(net.dv8tion.jda.internal.JDAImpl) EventCache(net.dv8tion.jda.internal.handle.EventCache) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) VerificationLevel(net.dv8tion.jda.api.entities.Guild.VerificationLevel) DataObject(net.dv8tion.jda.api.utils.data.DataObject) ToLongFunction(java.util.function.ToLongFunction) AudioChannelMixin(net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin) OnlineStatus(net.dv8tion.jda.api.OnlineStatus) TLongSet(gnu.trove.set.TLongSet) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) OffsetDateTime(java.time.OffsetDateTime) JDALogger(net.dv8tion.jda.internal.utils.JDALogger) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) DataArray(net.dv8tion.jda.api.utils.data.DataArray) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) Helpers(net.dv8tion.jda.internal.utils.Helpers) Timeout(net.dv8tion.jda.api.entities.Guild.Timeout) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) CaseInsensitiveMap(org.apache.commons.collections4.map.CaseInsensitiveMap) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) TemporalAccessor(java.time.temporal.TemporalAccessor) Template(net.dv8tion.jda.api.entities.templates.Template) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) UserUpdateDiscriminatorEvent(net.dv8tion.jda.api.events.user.update.UserUpdateDiscriminatorEvent) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) StreamSupport(java.util.stream.StreamSupport) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) TemplateChannel(net.dv8tion.jda.api.entities.templates.TemplateChannel) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) Logger(org.slf4j.Logger) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) UserUpdateNameEvent(net.dv8tion.jda.api.events.user.update.UserUpdateNameEvent) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TemplateGuild(net.dv8tion.jda.api.entities.templates.TemplateGuild) DateTimeFormatter(java.time.format.DateTimeFormatter) TLongObjectMap(gnu.trove.map.TLongObjectMap) net.dv8tion.jda.api.events.guild.member.update(net.dv8tion.jda.api.events.guild.member.update) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) IPermissionContainerMixin(net.dv8tion.jda.internal.entities.mixin.channel.attribute.IPermissionContainerMixin) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) TemplateGuild(net.dv8tion.jda.api.entities.templates.TemplateGuild) DataArray(net.dv8tion.jda.api.utils.data.DataArray) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) DataObject(net.dv8tion.jda.api.utils.data.DataObject) OffsetDateTime(java.time.OffsetDateTime) TLongSet(gnu.trove.set.TLongSet) TLongHashSet(gnu.trove.set.hash.TLongHashSet)

Example 39 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class EntityBuilder method createAuditLogEntry.

public AuditLogEntry createAuditLogEntry(GuildImpl guild, DataObject entryJson, DataObject userJson, DataObject webhookJson) {
    final long targetId = entryJson.getLong("target_id", 0);
    final long id = entryJson.getLong("id");
    final int typeKey = entryJson.getInt("action_type");
    final DataArray changes = entryJson.isNull("changes") ? null : entryJson.getArray("changes");
    final DataObject options = entryJson.isNull("options") ? null : entryJson.getObject("options");
    final String reason = entryJson.getString("reason", null);
    final UserImpl user = userJson == null ? null : createUser(userJson);
    final WebhookImpl webhook = webhookJson == null ? null : createWebhook(webhookJson);
    final Set<AuditLogChange> changesList;
    final ActionType type = ActionType.from(typeKey);
    if (changes != null) {
        changesList = new HashSet<>(changes.length());
        for (int i = 0; i < changes.length(); i++) {
            final DataObject object = changes.getObject(i);
            AuditLogChange change = createAuditLogChange(object);
            changesList.add(change);
        }
    } else {
        changesList = Collections.emptySet();
    }
    CaseInsensitiveMap<String, AuditLogChange> changeMap = new CaseInsensitiveMap<>(changeToMap(changesList));
    CaseInsensitiveMap<String, Object> optionMap = options != null ? new CaseInsensitiveMap<>(options.toMap()) : null;
    return new AuditLogEntry(type, typeKey, id, targetId, guild, user, webhook, reason, changeMap, optionMap);
}
Also used : ActionType(net.dv8tion.jda.api.audit.ActionType) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) DataArray(net.dv8tion.jda.api.utils.data.DataArray) CaseInsensitiveMap(org.apache.commons.collections4.map.CaseInsensitiveMap) DataObject(net.dv8tion.jda.api.utils.data.DataObject) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) DataObject(net.dv8tion.jda.api.utils.data.DataObject)

Example 40 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class EntityBuilder method createMember.

public MemberImpl createMember(GuildImpl guild, DataObject memberJson, DataObject voiceStateJson, DataObject presence) {
    boolean playbackCache = false;
    User user = createUser(memberJson.getObject("user"));
    DataArray roleArray = memberJson.getArray("roles");
    MemberImpl member = (MemberImpl) guild.getMember(user);
    if (member == null) {
        // Create a brand new member
        member = new MemberImpl(guild, user);
        member.setNickname(memberJson.getString("nick", null));
        member.setAvatarId(memberJson.getString("avatar", null));
        long boostTimestamp = memberJson.isNull("premium_since") ? 0 : Helpers.toTimestamp(memberJson.getString("premium_since"));
        member.setBoostDate(boostTimestamp);
        long timeOutTimestamp = memberJson.isNull("communication_disabled_until") ? 0 : Helpers.toTimestamp(memberJson.getString("communication_disabled_until"));
        member.setTimeOutEnd(timeOutTimestamp);
        if (!memberJson.isNull("pending"))
            member.setPending(memberJson.getBoolean("pending"));
        Set<Role> roles = member.getRoleSet();
        for (int i = 0; i < roleArray.length(); i++) {
            long roleId = roleArray.getUnsignedLong(i);
            Role role = guild.getRoleById(roleId);
            if (role != null)
                roles.add(role);
        }
    } else {
        // Update cached member and fire events
        List<Role> roles = new ArrayList<>(roleArray.length());
        for (int i = 0; i < roleArray.length(); i++) {
            long roleId = roleArray.getUnsignedLong(i);
            Role role = guild.getRoleById(roleId);
            if (role != null)
                roles.add(role);
        }
        updateMember(guild, member, memberJson, roles);
    }
    // Load joined_at if necessary
    if (!memberJson.isNull("joined_at") && !member.hasTimeJoined()) {
        member.setJoinDate(Helpers.toTimestamp(memberJson.getString("joined_at")));
    }
    // Load voice state and presence if necessary
    if (voiceStateJson != null && member.getVoiceState() != null)
        createVoiceState(guild, voiceStateJson, user, member);
    if (presence != null)
        createPresence(member, presence);
    return member;
}
Also used : TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Aggregations

DataArray (net.dv8tion.jda.api.utils.data.DataArray)67 DataObject (net.dv8tion.jda.api.utils.data.DataObject)40 Nonnull (javax.annotation.Nonnull)21 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)14 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)10 JDAImpl (net.dv8tion.jda.internal.JDAImpl)9 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)8 ArrayList (java.util.ArrayList)8 Route (net.dv8tion.jda.internal.requests.Route)8 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)7 Collectors (java.util.stream.Collectors)6 CheckReturnValue (javax.annotation.CheckReturnValue)6 TemplateRole (net.dv8tion.jda.api.entities.templates.TemplateRole)5 ParsingException (net.dv8tion.jda.api.exceptions.ParsingException)5 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)5 Bean (at.xirado.bean.Bean)4 java.util (java.util)4 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)4 Template (net.dv8tion.jda.api.entities.templates.Template)4 CacheView (net.dv8tion.jda.api.utils.cache.CacheView)4