net.dv8tion.jda.api.entities.ChannelType Java Examples

The following examples show how to use net.dv8tion.jda.api.entities.ChannelType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiscordEntityValidator.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (StringUtils.isEmpty(value)) {
        return true;
    }
    if (ChannelType.TEXT == type && "-1".equals(value)) {
        return allowDm;
    }
    if (!PATTERN.matcher(value).matches()) {
        return false;
    }

    DiscordUserDetails userDetails = SecurityUtils.getCurrentUser();
    if (userDetails == null) {
        return false;
    }

    return !strict || gatewayService.isChannelOwner(CheckOwnerRequest.builder()
            .type(type)
            .channelId(value)
            .userId(userDetails.getId())
            .build());
}
 
Example #2
Source File: ReadyHandler.java    From JDA with Apache License 2.0 6 votes vote down vote up
public void handleReady(DataObject content)
{
    EntityBuilder builder = getJDA().getEntityBuilder();
    DataArray privateChannels = content.getArray("private_channels");

    for (int i = 0; i < privateChannels.length(); i++)
    {
        DataObject chan = privateChannels.getObject(i);
        ChannelType type = ChannelType.fromId(chan.getInt("type"));

        //noinspection SwitchStatementWithTooFewBranches
        switch (type)
        {
            case PRIVATE:
                builder.createPrivateChannel(chan);
                break;
            default:
                WebSocketClient.LOG.warn("Received a Channel in the private_channels array in READY of an unknown type! Type: {}", type);
        }
    }
}
 
Example #3
Source File: HelpCommand.java    From Yui with Apache License 2.0 5 votes vote down vote up
@Override
public void onCommand(MessageReceivedEvent e, String[] args)
{
    if(!e.isFromType(ChannelType.PRIVATE))
    {
        e.getTextChannel().sendMessage(new MessageBuilder()
                .append(e.getAuthor())
                .append(": Help information was sent as a private message.")
                .build()).queue();
    }
    sendPrivate(e.getAuthor().openPrivateChannel().complete(), args);
}
 
Example #4
Source File: JSONMessageErrorsHelper.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void sendErrorJSON(Message message, Throwable error, final boolean print, ObjectMapper mapper) {
    if (print) {
        logger.error(error.getLocalizedMessage(), error);
    }

    //Makes no difference if we use sendError or check here both perm types
    if (message.getChannelType() == ChannelType.TEXT) {
        final TextChannel channel = message.getTextChannel();
        if (!channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ,
            Permission.MESSAGE_WRITE, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_ADD_REACTION)) {
            return;
        }
    }

    message.addReaction(MessageUtils.getErrorReaction()).queue(null, (ignored) -> {});

    try {
        message.getChannel()
            .sendFile(
                mapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsBytes(EarthUtils.throwableToJSONObject(error, mapper)),
                "error.json"
            ).embed(
            defaultEmbed().setTitle("We got an error!")
                .setDescription(String.format("Error type: %s",
                    error.getClass().getSimpleName())).build()
        ).queue();
    }
    catch (JsonProcessingException e) {
        sendMsg(message.getTextChannel(), "Error while sending file: " + e);
    }
}
 
Example #5
Source File: Command.java    From Yui with Apache License 2.0 5 votes vote down vote up
protected Message sendMessage(MessageReceivedEvent e, Message message)
{
    if(e.isFromType(ChannelType.PRIVATE))
        return e.getPrivateChannel().sendMessage(message).complete();
    else
        return e.getTextChannel().sendMessage(message).complete();
}
 
Example #6
Source File: EvalCommand.java    From Yui with Apache License 2.0 5 votes vote down vote up
@Override
public void onCommand(MessageReceivedEvent e, String[] args)
{
    //Specifically ignores the user meew0 due to a conflict between his bot (Elgyem) and Yui.
    //We both agreed to make our bots ignore eachother's .eval commands.
    if (e.getAuthor().getId().equals("66237334693085184"))  //meew0's ID
        return;

    if (!Permissions.getPermissions().isOp(e.getAuthor()))
    {
        sendMessage(e, "Sorry, this command is OP only!");
        return;
    }

    try
    {
        engine.put("event", e);
        engine.put("message", e.getMessage());
        engine.put("channel", e.getChannel());
        engine.put("args", args);
        engine.put("api", e.getJDA());
        if (e.isFromType(ChannelType.TEXT))
        {
            engine.put("guild", e.getGuild());
            engine.put("member", e.getMember());
        }

        Object out = engine.eval(
                "(function() {" +
                    "with (imports) {" +
                        e.getMessage().getContentDisplay().substring(args[0].length()) +
                    "}" +
                "})();");
        sendMessage(e, out == null ? "Executed without error." : out.toString());
    }
    catch (Exception e1)
    {
        sendMessage(e, e1.getMessage());
    }
}
 
Example #7
Source File: GuildActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@CheckReturnValue
public ChannelData newChannel(@Nonnull ChannelType type, @Nonnull String name)
{
    ChannelData data = new ChannelData(type, name);
    addChannel(data);
    return data;
}
 
Example #8
Source File: MessagePaginationActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public MessagePaginationActionImpl(MessageChannel channel)
{
    super(channel.getJDA(), Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId()), 1, 100, 100);

    if (channel.getType() == ChannelType.TEXT)
    {
        TextChannel textChannel = (TextChannel) channel;
        if (!textChannel.getGuild().getSelfMember().hasPermission(textChannel, Permission.MESSAGE_HISTORY))
            throw new InsufficientPermissionException(textChannel, Permission.MESSAGE_HISTORY);
    }

    this.channel = channel;
}
 
Example #9
Source File: InsufficientPermissionException.java    From JDA with Apache License 2.0 5 votes vote down vote up
private InsufficientPermissionException(@Nonnull Guild guild, @Nullable GuildChannel channel, @Nonnull Permission permission, @Nonnull String reason)
{
    super(permission, reason);
    this.guildId = guild.getIdLong();
    this.channelId = channel == null ? 0 : channel.getIdLong();
    this.channelType = channel == null ? ChannelType.UNKNOWN : channel.getType();
}
 
Example #10
Source File: InsufficientPermissionException.java    From JDA with Apache License 2.0 5 votes vote down vote up
private InsufficientPermissionException(@Nonnull Guild guild, @Nullable GuildChannel channel, @Nonnull Permission permission)
{
    super(permission, "Cannot perform action due to a lack of Permission. Missing permission: " + permission.toString());
    this.guildId = guild.getIdLong();
    this.channelId = channel == null ? 0 : channel.getIdLong();
    this.channelType = channel == null ? ChannelType.UNKNOWN : channel.getType();
}
 
Example #11
Source File: ChatSoundBoardListener.java    From DiscordSoundboard with Apache License 2.0 5 votes vote down vote up
private void deleteMessage(MessageReceivedEvent event) {
    if (!event.isFromType(ChannelType.PRIVATE)) {
        try {
            event.getMessage().delete().queue();
        } catch (PermissionException e) {
            LOG.warn("Unable to delete message");
        }
    }
}
 
Example #12
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> void sendTempMessageSilent(Function<T, RestAction<Message>> action, T embed, int sec) {
    sendMessageSilentQueue(action, embed, message -> {
        JDA jda = message.getJDA();
        long messageId = message.getIdLong();
        long channelId = message.getChannel().getIdLong();
        ChannelType type = message.getChannelType();
        scheduler.schedule(() -> {
            MessageChannel channel = DiscordUtils.getChannel(jda, type, channelId);
            if (channel != null) {
                channel.retrieveMessageById(messageId).queue(this::delete);
            }
        }, new DateTime().plusSeconds(sec).toDate());
    });
}
 
Example #13
Source File: ChannelCreateHandler.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Override
protected Long handleInternally(DataObject content)
{
    ChannelType type = ChannelType.fromId(content.getInt("type"));

    long guildId = 0;
    JDAImpl jda = getJDA();
    if (type.isGuild())
    {
        guildId = content.getLong("guild_id");
        if (jda.getGuildSetupController().isLocked(guildId))
            return guildId;
    }

    EntityBuilder builder = jda.getEntityBuilder();
    switch (type)
    {
        case STORE:
        {
            builder.createStoreChannel(content, guildId);
            jda.handleEvent(
                new StoreChannelCreateEvent(
                    jda, responseNumber,
                    builder.createStoreChannel(content, guildId)));
            break;
        }
        case TEXT:
        {
            jda.handleEvent(
                new TextChannelCreateEvent(
                    jda, responseNumber,
                    builder.createTextChannel(content, guildId)));
            break;
        }
        case VOICE:
        {
            jda.handleEvent(
                new VoiceChannelCreateEvent(
                    jda, responseNumber,
                    builder.createVoiceChannel(content, guildId)));
            break;
        }
        case CATEGORY:
        {
            jda.handleEvent(
                new CategoryCreateEvent(
                    jda, responseNumber,
                    builder.createCategory(content, guildId)));
            break;
        }
        case PRIVATE:
        {
            jda.handleEvent(
                new PrivateChannelCreateEvent(
                    jda, responseNumber,
                    builder.createPrivateChannel(content)));
            break;
        }
        case GROUP:
            WebSocketClient.LOG.warn("Received a CREATE_CHANNEL for a group which is not supported");
            return null;
        default:
            WebSocketClient.LOG.debug("Discord provided an CREATE_CHANNEL event with an unknown channel type! JSON: {}", content);
    }
    return null;
}
 
Example #14
Source File: ChatSoundBoardListener.java    From DiscordSoundboard with Apache License 2.0 4 votes vote down vote up
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    String requestingUser = event.getAuthor().getName();
    if (!event.getAuthor().isBot() && ((respondToDms && event.isFromType(ChannelType.PRIVATE)) ||
            !event.isFromType(ChannelType.PRIVATE))) {

        String message = event.getMessage().getContentRaw().toLowerCase();
        if (message.startsWith(commandCharacter)) {
            if (soundPlayer.isUserAllowed(requestingUser) && !soundPlayer.isUserBanned(requestingUser)) {
                final int maxLineLength = messageSizeLimit;

                //Respond
                if (message.startsWith(commandCharacter + "list")) {
                    listCommand(event, requestingUser, message, maxLineLength);
                    //If the command is not list and starts with the specified command character try and play that "command" or sound file.
                } else if (message.startsWith(commandCharacter + "help")) {
                    helpCommand(event, requestingUser);
                } else if (message.startsWith(commandCharacter + "volume")) {
                    volumeCommand(event, requestingUser, message);
                } else if (message.startsWith(commandCharacter + "stop")) {
                    stopCommand(event, requestingUser, message);
                } else if (message.startsWith(commandCharacter + "info")) {
                    infoCommand(event, requestingUser);
                } else if (message.startsWith(commandCharacter + "remove")) {
                    removeCommand(event, message);
                } else if (message.startsWith(commandCharacter + "random")) {
                    randomCommand(event, requestingUser);
                } else if (message.startsWith(commandCharacter + "entrance") ||
                        message.startsWith(commandCharacter + "leave")) {
                    entranceOrLeaveCommand(event, message);
                } else if (message.startsWith(commandCharacter + "userdetails")) {
                    userDetails(event);
                } else if (message.startsWith(commandCharacter + "url")) {
                    String[] messageSplit = event.getMessage().getContentRaw().split(" ");
                    if (messageSplit.length >= 1) {
                        String url = messageSplit[1];
                        soundPlayer.playUrlForUser(url, requestingUser);
                    }
                } else if (message.startsWith(commandCharacter) &&
                        message.length() >= (commandCharacter.length() + 1)) {
                    soundFileCommand(event, requestingUser, message);
                } else {
                    if (message.startsWith(commandCharacter) || event.isFromType(ChannelType.PRIVATE)) {
                        nonRecognizedCommand(event, requestingUser);
                    } else {
                        replyByPrivateMessage(event, "You seem to need help.");
                        helpCommand(event, requestingUser);
                    }
                }
            } else {
                if (!soundPlayer.isUserAllowed(requestingUser)) {
                    replyByPrivateMessage(event, "I don't take orders from you.");
                }
                if (soundPlayer.isUserBanned(requestingUser)) {
                    replyByPrivateMessage(event, "You've been banned from using this soundboard bot.");
                }
            }
        } else {
            addAttachedSoundFile(event);
        }
    }
}
 
Example #15
Source File: GuildAction.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs a data object containing information on
 * a {@link net.dv8tion.jda.api.entities.GuildChannel GuildChannel} to be used in the construction
 * of a {@link net.dv8tion.jda.api.entities.Guild Guild}!
 *
 * @param  type
 *         The {@link net.dv8tion.jda.api.entities.ChannelType ChannelType} of the resulting GuildChannel
 *         <br>This may be of type {@link net.dv8tion.jda.api.entities.ChannelType#TEXT TEXT} or {@link net.dv8tion.jda.api.entities.ChannelType#VOICE VOICE}!
 * @param  name
 *         The name of the channel. This must be alphanumeric with underscores for type TEXT
 *
 * @throws java.lang.IllegalArgumentException
 *         <ul>
 *             <li>If provided with an invalid ChannelType</li>
 *             <li>If the provided name is {@code null} or blank</li>
 *             <li>If the provided name is not between 2-100 characters long</li>
 *             <li>If the type is TEXT and the provided name is not alphanumeric with underscores</li>
 *         </ul>
 */
public ChannelData(ChannelType type, String name)
{
    Checks.notBlank(name, "Name");
    Checks.check(type == ChannelType.TEXT || type == ChannelType.VOICE, "Can only create channels of type TEXT or VOICE in GuildAction!");
    Checks.check(name.length() >= 2 && name.length() <= 100, "Channel name has to be between 2-100 characters long!");
    Checks.check(type == ChannelType.VOICE || name.matches("[a-zA-Z0-9-_]+"), "Channels of type TEXT must have a name in alphanumeric with underscores!");

    this.type = type;
    this.name = name;
}
 
Example #16
Source File: GuildAction.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link ChannelData ChannelData}
 * instance and adds it to this GuildAction.
 *
 * @param  type
 *         The {@link net.dv8tion.jda.api.entities.ChannelType ChannelType} of the resulting GuildChannel
 *         <br>This may be of type {@link net.dv8tion.jda.api.entities.ChannelType#TEXT TEXT} or {@link net.dv8tion.jda.api.entities.ChannelType#VOICE VOICE}!
 * @param  name
 *         The name of the channel. This must be alphanumeric with underscores for type TEXT
 *
 * @throws java.lang.IllegalArgumentException
 *         <ul>
 *             <li>If provided with an invalid ChannelType</li>
 *             <li>If the provided name is {@code null} or blank</li>
 *             <li>If the provided name is not between 2-100 characters long</li>
 *             <li>If the type is TEXT and the provided name is not alphanumeric with underscores</li>
 *         </ul>
 *
 * @return The new ChannelData instance
 */
@Nonnull
@CheckReturnValue
ChannelData newChannel(@Nonnull ChannelType type, @Nonnull String name);
 
Example #17
Source File: ChannelOrderAction.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * The {@link net.dv8tion.jda.api.entities.ChannelType ChannelTypes} for the {@link #getSortBucket() sorting bucket}.
 *
 * @return The channel types
 *
 * @see    net.dv8tion.jda.api.entities.ChannelType#fromSortBucket(int)
 */
@Nonnull
default EnumSet<ChannelType> getChannelTypes()
{
    return ChannelType.fromSortBucket(getSortBucket());
}
 
Example #18
Source File: MessagePaginationAction.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * The {@link net.dv8tion.jda.api.entities.ChannelType ChannelType} of
 * the targeted {@link net.dv8tion.jda.api.entities.MessageChannel MessageChannel}.
 *
 * @return {@link net.dv8tion.jda.api.entities.ChannelType ChannelType}
 */
@Nonnull
default ChannelType getType()
{
    return getChannel().getType();
}
 
Example #19
Source File: InsufficientPermissionException.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * The {@link net.dv8tion.jda.api.entities.ChannelType} for the {@link #getChannelId() channel id}.
 *
 * @return The channel type or {@link net.dv8tion.jda.api.entities.ChannelType#UNKNOWN}.
 *
 * @since  4.0.0
 */
@Nonnull
public ChannelType getChannelType()
{
    return channelType;
}