Java Code Examples for net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent#getChannel()

The following examples show how to use net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent#getChannel() . 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: SlowModeCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent event, BotContext context, String query) {
    TextChannel channel = event.getChannel();
    if (!StringUtils.isNumeric(query)) {
        return showHelp(channel, context);
    }

    int seconds;
    try {
        seconds = Integer.parseInt(query);
    } catch (NumberFormatException e) {
        return showHelp(channel, context);
    }
    if (seconds < 0 || seconds > 120) {
        return showHelp(channel, context);
    }

    channel.sendTyping().queue();
    channel.getManager().setSlowmode(seconds).queue(e -> contextService.withContext(channel.getGuild(), () -> {
        if (seconds > 0) {
            String secPlurals = messageService.getCountPlural(seconds, "discord.plurals.second");
            messageService.onEmbedMessage(channel, "discord.command.mod.slow.enabled", seconds,
                    secPlurals);
        } else {
            messageService.onEmbedMessage(channel, "discord.command.mod.slow.disabled");
        }
    }));
    return true;
}
 
Example 2
Source File: MemberMessageFilter.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public final void doFilter(GuildMessageReceivedEvent event, FilterChain<GuildMessageReceivedEvent> chain) {
    try {
        if (!event.isWebhookMessage()
                && !event.getAuthor().isBot()
                && event.getMember() != null
                && event.getChannel() != null
                && event.getMessage().getType() == MessageType.DEFAULT) {
            doInternal(event, chain);
            return;
        }
    } catch (Throwable e) {
        log.warn("Unexpected filter error", e);
    }
    chain.doFilter(event);
}
 
Example 3
Source File: AudioEchoExample.java    From JDA with Apache License 2.0 6 votes vote down vote up
/**
 * Handle command with arguments.
 *
 * @param event
 *        The event for this command
 * @param guild
 *        The guild where its happening
 * @param arg
 *        The input argument
 */
private void onEchoCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
{
    boolean isNumber = arg.matches("\\d+"); // This is a regular expression that ensures the input consists of digits
    VoiceChannel channel = null;
    if (isNumber)                           // The input is an id?
    {
        channel = guild.getVoiceChannelById(arg);
    }
    if (channel == null)                    // Then the input must be a name?
    {
        List<VoiceChannel> channels = guild.getVoiceChannelsByName(arg, true);
        if (!channels.isEmpty())            // Make sure we found at least one exact match
            channel = channels.get(0);      // We found a channel! This cannot be null.
    }

    TextChannel textChannel = event.getChannel();
    if (channel == null)                    // I have no idea what you want mr user
    {
        onUnknownChannel(textChannel, arg); // Let the user know about our failure
        return;
    }
    connectTo(channel);                     // We found a channel to connect to!
    onConnecting(channel, textChannel);     // Let the user know, we were successful!
}
 
Example 4
Source File: ImageCommandBase.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public void handleBasicImage(GuildMessageReceivedEvent event, byte[] image) {
    final TextChannel channel = event.getChannel();

    if (event.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_ATTACH_FILES)) {
        channel.sendFile(image, getFileName()).queue();
    } else {
        sendMsg(channel, "I need permission to upload files in order for this command to work.");
    }
}
 
Example 5
Source File: AimlServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private Request createRequest(GuildMessageReceivedEvent event, String input) {
    Request.RequestBuilder builder = Request.builder()
            .input(input)
            .attribute("dMessageEvent", event)
            .attribute("dAuthorName", event.getAuthor().getName())
            .attribute("dAuthorMention", event.getAuthor().getAsMention())
            .attribute("dAuthorAvatarUrl", event.getAuthor().getEffectiveAvatarUrl());

    if (event.getMember() != null) {
        Member member = event.getMember();
        builder
                .attribute("dAuthorName", member.getEffectiveName())
                .attribute("dAuthorMention", member.getAsMention());
    }

    if (event.getGuild() != null) {
        Guild guild = event.getGuild();
        builder
                .attribute("dGuildName", guild.getName())
                .attribute("dGuildOwnerName", guild.getOwner().getEffectiveName());
    }

    if (event.getChannel() != null) {
        TextChannel channel = event.getChannel();
        builder.attribute("dChannelName", channel.getName());
    }
    return builder.build();
}
 
Example 6
Source File: DiscordGuildMessagePreProcessEvent.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
public DiscordGuildMessagePreProcessEvent(GuildMessageReceivedEvent jdaEvent) {
    super(jdaEvent.getJDA(), jdaEvent);
    this.author = jdaEvent.getAuthor();
    this.channel = jdaEvent.getChannel();
    this.guild = jdaEvent.getGuild();
    this.member = jdaEvent.getMember();
    this.message = jdaEvent.getMessage();
}
 
Example 7
Source File: DiscordGuildMessagePostProcessEvent.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
public DiscordGuildMessagePostProcessEvent(GuildMessageReceivedEvent jdaEvent, boolean cancelled, String processedMessage) {
    super(jdaEvent.getJDA(), jdaEvent);
    this.author = jdaEvent.getAuthor();
    this.channel = jdaEvent.getChannel();
    this.guild = jdaEvent.getGuild();
    this.member = jdaEvent.getMember();
    this.message = jdaEvent.getMessage();

    this.setCancelled(cancelled);
    this.processedMessage = processedMessage;
}
 
Example 8
Source File: DiscordGuildMessageReceivedEvent.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
public DiscordGuildMessageReceivedEvent(GuildMessageReceivedEvent jdaEvent) {
    super(jdaEvent.getJDA(), jdaEvent);
    this.author = jdaEvent.getAuthor();
    this.channel = jdaEvent.getChannel();
    this.guild = jdaEvent.getGuild();
    this.member = jdaEvent.getMember();
    this.message = jdaEvent.getMessage();
}
 
Example 9
Source File: GulagCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doCommand(MemberReference reference, GuildMessageReceivedEvent event, BotContext context, String content) {
    TextChannel channel = event.getChannel();

    if (StringUtils.isBlank(content)) {
        showHelp(event, context);
        return false;
    }

    Member targetMember = reference.getMember();
    if (targetMember != null && supportService.isModerator(targetMember)) {
        return fail(event);
    }

    User targetUser = reference.getUser();
    if (targetUser != null && discordService.isSuperUser(targetUser)) {
        return fail(event);
    }

    String id = reference.getId();

    String targetName = targetUser != null
            ? String.format("%s#%s (%s)", targetUser.getName(), targetUser.getDiscriminator(), id)
            : id;

    boolean success = gulagService.send(event.getMember(), Long.valueOf(reference.getId()), content);
    if (!success) {
        messageService.onEmbedMessage(channel, "discord.command.gulag.exists", targetName);
        return false;
    }

    messageService.onEmbedMessage(channel, "discord.command.gulag.success", targetName);

    if (targetMember != null) {
        targetMember.ban(1, content).queueAfter(30, TimeUnit.SECONDS);
    } else if (targetUser != null) {
        event.getGuild().ban(targetUser, 1, content).queue();
    }

    if (targetUser != null) {
        discordService.getShardManager().getGuildCache()
                .stream()
                .filter(e -> e.getOwner() != null && targetUser.equals(e.getOwner().getUser()))
                .forEach(e -> e.leave().queue());
    }

    Guild guild = discordService.getShardManager().getGuildById(id);
    if (guild != null) {
        guild.leave().queue();
    }
    return true;
}
 
Example 10
Source File: ClearCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected boolean doCommand(MemberReference reference, GuildMessageReceivedEvent event, BotContext context, String query) throws DiscordException {
    Member member = reference.getMember();
    String moderatorId = event.getMember().getId();
    String executionMessageId = event.getMessageId();

    boolean includeInvocation = reference.isAuthorSelected() || (member != null && member.equals(event.getMember()));

    if (StringUtils.isBlank(query) || !StringUtils.isNumeric(query)) {
        showHelp(event, context);
        return false;
    }
    int number = Integer.parseInt(query);
    if (number == 0 || number > MAX_MESSAGES) {
        showHelp(event, context);
        return false;
    }
    final int finalNumber = number + (includeInvocation ? 1 : 0);

    String userId = reference.isAuthorSelected() ? null : reference.getId();

    DateTime limit = new DateTime()
            .minusWeeks(2)
            .minusHours(1);

    TextChannel channel = event.getChannel();

    boolean canAttach = channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_ATTACH_FILES);
    StringBuilder history = new StringBuilder();
    DateTimeFormatter formatter = DateTimeFormat.mediumDateTime()
            .withLocale(contextService.getLocale())
            .withZone(context.getTimeZone());

    Set<String> ids = ConcurrentHashMap.newKeySet();

    channel.sendTyping().queue(r -> {
        channel.getIterableHistory()
                .takeWhileAsync(e -> {
                    if (CommonUtils.getDate(e.getTimeCreated()).isBefore(limit)) {
                        return false;
                    }
                    if (StringUtils.isEmpty(userId)
                            || e.getMember() != null && Objects.equals(e.getMember().getId(), userId)) {
                        ids.add(e.getId());
                        if (canAttach && !executionMessageId.equals(e.getId())) {
                            appendHistory(history, formatter, e);
                        }
                    }
                    return ids.size() < finalNumber;
                })
                .exceptionally(e -> {
                    log.error("Clear failed", e);
                    fail(event);
                    return null;
                })
                .whenCompleteAsync((messages, t) -> contextService.withContext(context.getConfig().getGuildId(), () -> {
                    int finalCount = ids.size();
                    if (includeInvocation) {
                        finalCount--;
                    }
                    if (finalCount <= 0) {
                        messageService.onEmbedMessage(event.getChannel(), "discord.command.mod.clear.absent");
                        return;
                    }

                    ids.forEach(e -> actionsHolderService.markAsDeleted(channel.getId(), e));
                    channel.purgeMessagesById(new ArrayList<>(ids));

                    AuditActionBuilder builder = auditService.log(channel.getGuild(), AuditActionType.MESSAGES_CLEAR)
                            .withChannel(channel)
                            .withUser(channel.getGuild().getMemberById(moderatorId))
                            .withAttribute(MESSAGE_COUNT, finalCount);
                    if (canAttach && history.length() > 0) {
                        builder.withAttachment(channel.getId() + ".log", history.toString().getBytes());
                    }
                    builder.save();

                    String pluralMessages = messageService.getCountPlural(finalCount, "discord.plurals.message");
                    messageService.onTempMessage(channel, 5, "discord.command.mod.clear.deleted", finalCount, pluralMessages);
                }));
    });
    return true;
}
 
Example 11
Source File: CurrencyCmds.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public static void applyPotionEffect(GuildMessageReceivedEvent event, Item item, Player p, Map<String, String> arguments, String content, boolean isPet, I18nContext languageContext) {
    final ManagedDatabase db = MantaroData.db();
    if ((item.getItemType() == ItemType.POTION || item.getItemType() == ItemType.BUFF) && item instanceof Potion) {
        DBUser dbUser = db.getUser(event.getAuthor());
        UserData userData = dbUser.getData();
        Map<String, Pet> profilePets = p.getData().getPets();
        final TextChannel channel = event.getChannel();

        //Yes, parser limitations. Natan change to your parser eta wen :^), really though, we could use some generics on here lol
        // NumberFormatException?
        int amount = 1;
        if(arguments.containsKey("amount")) {
            try {
                amount = Integer.parseInt(arguments.get("amount"));
            } catch (NumberFormatException e) {
                channel.sendMessageFormat(languageContext.get("commands.useitem.invalid_amount"), EmoteReference.WARNING).queue();
                return;
            }
        }
        String petName = isPet ? content : "";

        if (isPet && petName.isEmpty()) {
            channel.sendMessageFormat(languageContext.get("commands.useitem.no_name"), EmoteReference.SAD).queue();
            return;
        }

        final PlayerEquipment equippedItems = isPet ? profilePets.get(petName).getData().getEquippedItems() : userData.getEquippedItems();
        PlayerEquipment.EquipmentType type = equippedItems.getTypeFor(item);

        if (amount < 1) {
            channel.sendMessageFormat(languageContext.get("commands.useitem.too_little"), EmoteReference.SAD).queue();
            return;
        }

        if (p.getInventory().getAmount(item) < amount) {
            channel.sendMessageFormat(languageContext.get("commands.useitem.not_enough_items"), EmoteReference.SAD).queue();
            return;
        }


        if (equippedItems.isEffectActive(type, ((Potion) item).getMaxUses())) {
            PotionEffect currentPotion = equippedItems.getCurrentEffect(type);

            //Currently has a potion equipped, but wants to stack a potion of other type.
            if (currentPotion.getPotion() != Items.idOf(item)) {
                channel.sendMessageFormat(languageContext.get("general.misc_item_usage.not_same_potion"),
                        EmoteReference.ERROR, Items.fromId(currentPotion.getPotion()).getName(), item.getName()).queue();

                return;
            }

            //Currently has a potion equipped, and is of the same type.
            if (currentPotion.getAmountEquipped() + amount < 10) {
                currentPotion.equip(amount);
                channel.sendMessageFormat(languageContext.get("general.misc_item_usage.potion_applied_multiple"),
                        EmoteReference.CORRECT, item.getName(), Utils.capitalize(type.toString()), currentPotion.getAmountEquipped()).queue();
            } else {
                //Too many stacked (max: 10).
                channel.sendMessageFormat(languageContext.get("general.misc_item_usage.max_stack_size"), EmoteReference.ERROR, item.getName()).queue();
                return;
            }
        } else {
            //No potion stacked.
            PotionEffect effect = new PotionEffect(Items.idOf(item), 0, ItemType.PotionType.PLAYER);

            //If there's more than 1, proceed to equip the stacks.

            if (amount>=10) {
                //Too many stacked (max: 10).
                channel.sendMessageFormat(languageContext.get("general.misc_item_usage.max_stack_size_2"), EmoteReference.ERROR, item.getName()).queue();
                return;
            }
            if (amount > 1)
                effect.equip(amount - 1); //Amount - 1 because we're technically using one.


            //Apply the effect.
            equippedItems.applyEffect(effect);
            channel.sendMessageFormat(languageContext.get("general.misc_item_usage.potion_applied"),
                    EmoteReference.CORRECT, item.getName(), Utils.capitalize(type.toString()), amount).queue();
        }


        if(amount == 9)
            p.getData().addBadgeIfAbsent(Badge.MAD_SCIENTIST);

        //Default: 1
        p.getInventory().process(new ItemStack(item, -amount));
        p.save();
        dbUser.save();

        return;
    }

    if (!isPet)
        item.getAction().test(event, Pair.of(languageContext, content), false);
}
 
Example 12
Source File: AudioCmdUtils.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public static CompletionStage<Boolean> connectToVoiceChannel(GuildMessageReceivedEvent event, I18nContext lang) {
    VoiceChannel userChannel = event.getMember().getVoiceState().getChannel();
    Guild guild = event.getGuild();
    TextChannel textChannel = event.getChannel();

    //I can't see you in any VC here?
    if (userChannel == null) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.user_no_vc"), EmoteReference.ERROR).queue();
        return completedFuture(false);
    }

    //Can't connect to this channel
    if (!guild.getSelfMember().hasPermission(userChannel, Permission.VOICE_CONNECT)) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.missing_permissions_connect"), EmoteReference.ERROR, lang.get("discord_permissions.voice_connect")).queue();
        return completedFuture(false);
    }

    //Can't speak on this channel
    if (!guild.getSelfMember().hasPermission(userChannel, Permission.VOICE_SPEAK)) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.missing_permission_speak"), EmoteReference.ERROR, lang.get("discord_permissions.voice_speak")).queue();
        return completedFuture(false);
    }

    //Set the custom guild music channel from the db value
    VoiceChannel guildMusicChannel = null;
    if (MantaroData.db().getGuild(guild).getData().getMusicChannel() != null)
        guildMusicChannel = guild.getVoiceChannelById(MantaroData.db().getGuild(guild).getData().getMusicChannel());

    //This is where we call LL.
    JdaLink link = MantaroBot.getInstance().getAudioManager().getMusicManager(guild).getLavaLink();
    if (guildMusicChannel != null) {
        //If the channel is not the set one, reject this connect.
        if (!userChannel.equals(guildMusicChannel)) {
            textChannel.sendMessageFormat(lang.get("commands.music_general.connect.channel_locked"), EmoteReference.ERROR, guildMusicChannel.getName()).queue();
            return completedFuture(false);
        }

        //If the link is not currently connected or connecting, accept connection and call openAudioConnection
        if (link.getState() != Link.State.CONNECTED && link.getState() != Link.State.CONNECTING) {
            log.debug("Connected to channel {}. Reason: Link is not CONNECTED or CONNECTING and we requested a connection from connectToVoiceChannel (custom music channel)", userChannel.getId());
            return openAudioConnection(event, link, userChannel, lang).thenApply(__ -> true);
        }

        //Nothing to connect to, but pass true so we can load the song (for example, it's already connected)
        return completedFuture(true);
    }

    //Assume last channel it's the one it was attempting to connect to? (on the one below this too)
    //If the link is CONNECTED and the lastChannel is not the one it's already connected to, reject connection
    if (link.getState() == Link.State.CONNECTED && link.getLastChannel() != null && !link.getLastChannel().equals(userChannel.getId())) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.already_connected"), EmoteReference.WARNING, guild.getVoiceChannelById(link.getLastChannel()).getName()).queue();
        return completedFuture(false);
    }

    //If the link is CONNECTING and the lastChannel is not the one it's already connected to, reject connection
    if (link.getState() == Link.State.CONNECTING && link.getLastChannel() != null && !link.getLastChannel().equals(userChannel.getId())) {
        textChannel.sendMessageFormat(lang.get("commands.music_general.connect.attempting_to_connect"), EmoteReference.ERROR, guild.getVoiceChannelById(link.getLastChannel()).getName()).queue();
        return completedFuture(false);
    }

    //If the link is not currently connected or connecting, accept connection and call openAudioConnection
    if (link.getState() != Link.State.CONNECTED && link.getState() != Link.State.CONNECTING) {
        log.debug("Connected to voice channel {}. Reason: Link is not CONNECTED or CONNECTING and we requested a connection from connectToVoiceChannel", userChannel.getId());
        return openAudioConnection(event, link, userChannel, lang).thenApply(__ -> true);
    }

    //Nothing to connect to, but pass true so we can load the song (for example, it's already connected)
    return completedFuture(true);
}