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"));
}
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));
}
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;
}
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);
}
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;
}
Aggregations