net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent Java Examples

The following examples show how to use net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent. 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: InvestigateCmd.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
private static void investigateChannel(GuildMessageReceivedEvent event, TextChannel channel, boolean file) {
    if (channel == null) {
        event.getChannel().sendMessage("Unknown channel").queue();
        return;
    }
    Investigation investigation = new Investigation(file);
    channel.getIterableHistory().takeAsync(200)
            .thenAccept(messages -> {
                List<InvestigatedMessage> res = investigation.get(channel);
                messages.forEach(m -> res.add(0, InvestigatedMessage.from(m)));
            })
            .thenRun(() -> investigation.result(channel.getGuild(), event))
            .exceptionally(e -> {
                e.printStackTrace();
                event.getChannel().sendMessage("Unable to execute: " + e).queue();
                return null;
            });
}
 
Example #2
Source File: CustomCommandCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private void listCustomCommands(String arg, GuildMessageReceivedEvent event, CommandManager manager, CommandContext ctx) {
    if (arg.equalsIgnoreCase("list")) {
        final GuildSettings s = ctx.getGuildSettings();
        final StringBuilder sb = new StringBuilder();

        manager.getCustomCommands().stream()
            .filter(c -> c.getGuildId() == event.getGuild().getIdLong())
            .forEach(cmd -> sb.append(s.getCustomPrefix())
                .append(cmd.getName())
                .append("\n")
            );

        sendMsg(event, new MessageBuilder().append("Custom Commands for this server").append('\n')
            .appendCodeBlock(sb.toString(), "ldif").build());
    } else {
        sendMsg(event, "Insufficient arguments use `" + ctx.getPrefix() + "help customcommand`");
    }
}
 
Example #3
Source File: ServerInfoCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String query) {
    Guild guild = message.getGuild();

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.server.title", guild.getName()));
    builder.setThumbnail(guild.getIconUrl());
    builder.setFooter(messageService.getMessage("discord.command.info.identifier", guild.getId()), null);

    builder.addField(getMemberListField(guild));
    builder.addField(getChannelListField(guild));
    builder.addField(getShard(guild));
    builder.addField(getVerificationLevel(guild.getVerificationLevel()));
    builder.addField(getRegion(guild));
    builder.addField(getOwner(guild));
    builder.addField(getCreatedAt(guild, context));

    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example #4
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 #5
Source File: UnlockEmoteCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
static boolean cannotInteractWithEmote(GuildMessageReceivedEvent event, Emote emote) {
    if (emote == null) {
        sendMsg(event, "I cannot access that emote");

        return true;
    }

    if (emote.getGuild() == null || !emote.getGuild().equals(event.getGuild())) {
        sendMsg(event, "That emote does not exist on this server");
        return true;
    }

    if (emote.isManaged()) {
        sendMsg(event, "That emote is managed unfortunately, this means that I can't assign roles to it");
        return true;
    }

    return false;
}
 
Example #6
Source File: TempMuteCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
static boolean canNotProceed(@Nonnull CommandContext ctx, GuildMessageReceivedEvent event, Member mod, Member toMute, Role role, Member self) {
    if (role == null) {
        sendMsg(event, "The current mute role does not exist on this server, please contact your server administrator about this.");

        return true;
    }

    if (!canInteract(mod, toMute, "mute", ctx.getChannel())) {
        return true;
    }

    if (!self.canInteract(role)) {
        sendMsg(event, "I cannot mute this member, is the mute role above mine?");

        return true;
    }

    return false;
}
 
Example #7
Source File: DogCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doCommandAsync(GuildMessageReceivedEvent message, BotContext context, String query) {
    try {
        DogImage image;
        synchronized (images) {
            if (images.isEmpty()) {
                images.addAll(dogApiService.search(DogSearchQuery.builder()
                        .limit(25)
                        .order(DogSearchQuery.Order.RANDOM)
                        .build()));
            }
            image = images.poll();
        }

        if (image != null) {
            sendImage(message, image);
            return;
        }
    } catch (Exception e) {
        log.warn("Could not get dog", e);
    }
    messageService.onEmbedMessage(message.getChannel(), "discord.command.dog.error");
}
 
Example #8
Source File: Utils.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
public static TextChannel findChannelSelect(GuildMessageReceivedEvent event, String content, Consumer<TextChannel> consumer) {
    List<TextChannel> found = FinderUtil.findTextChannels(content, event.getGuild());
    if (found.isEmpty() && !content.isEmpty()) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot find any text channel with that name :(").queue();
        return null;
    }

    if (found.size() > 1 && !content.isEmpty()) {
        event.getChannel().sendMessage(String.format("%sToo many channels found, maybe refine your search?\n**Text Channel found:** %s",
                EmoteReference.THINKING, found.stream().map(TextChannel::getName).collect(Collectors.joining(", ")))).queue();

        return null;
    }

    if (found.size() == 1) {
        return found.get(0);
    } else {
        DiscordUtils.selectList(event, found,
                textChannel -> String.format("%s (ID: %s)", textChannel.getName(), textChannel.getId()),
                s -> ((SimpleCommand) optsCmd).baseEmbed(event, "Select the Channel:").setDescription(s).build(), consumer
        );
    }

    return null;
}
 
Example #9
Source File: YodaSpeakCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final GuildMessageReceivedEvent event = ctx.getEvent();

    try {
        final QueryBuilder builder = new QueryBuilder()
            .append("yoda")
            .append("sentence", ctx.getArgsDisplay());
        final JsonNode response = ctx.getApis().executeDefaultGetRequest(builder.build(), false);

        logger.debug("Yoda response: " + response);

        if (!response.get("success").asBoolean()) {
            sendMsg(event, "Could not connect to yoda service, try again in a few hours");
            return;
        }

        final String yoda = ctx.getRandom().nextInt(2) == 1 ? "<:yoda:578198258351079438> " : "<:BABY_YODA:670269491736870972> ";

        sendMsg(event, yoda + response.get("data").asText());
    }
    catch (Exception e) {
        Sentry.capture(e);
        sendMsg(event, "Could not connect to yoda service, try again in a few hours");
    }
}
 
Example #10
Source File: AudioEchoExample.java    From JDA with Apache License 2.0 6 votes vote down vote up
/**
 * Handle command without arguments.
 *
 * @param event
 *        The event for this command
 */
private void onEchoCommand(GuildMessageReceivedEvent event)
{
    // Note: None of these can be null due to our configuration with the JDABuilder!
    Member member = event.getMember();                              // Member is the context of the user for the specific guild, containing voice state and roles
    GuildVoiceState voiceState = member.getVoiceState();            // Check the current voice state of the user
    VoiceChannel channel = voiceState.getChannel();                 // Use the channel the user is currently connected to
    if (channel != null)
    {
        connectTo(channel);                                         // Join the channel of the user
        onConnecting(channel, event.getChannel());                  // Tell the user about our success
    }
    else
    {
        onUnknownChannel(event.getChannel(), "your voice channel"); // Tell the user about our failure
    }
}
 
Example #11
Source File: FilterBase.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final GuildMessageReceivedEvent event = ctx.getEvent();

    if (!passesNoArgs(event, false)) {
        return;
    }

    final String url = getImageFromCommand(ctx);

    if (url == null) {
        sendMsg(ctx, "Could not find image, please mention a user, upload an image, or put an image url after the command");
    } else {
        final byte[] image = ctx.getApis().getFilter(this.getFilterName(), url);
        handleBasicImage(event, image);
    }
}
 
Example #12
Source File: CoinCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String query) {
    String headsKeys[] = messageService.getMessage("discord.command.coin.heads", context.getCommandLocale())
            .split(",");
    String tailsKeys[] = messageService.getMessage("discord.command.coin.tails", context.getCommandLocale())
            .split(",");

    if (!ArrayUtil.containsIgnoreCase(headsKeys, query) && !ArrayUtil.containsIgnoreCase(tailsKeys, query)) {
        messageService.onMessage(message.getChannel(), "discord.command.coin.help", headsKeys[0], tailsKeys[0]);
        return false;
    }

    boolean headsBet = ArrayUtil.containsIgnoreCase(headsKeys, query);
    boolean headsOutcome = Math.random() < 0.5;

    String outCome = headsOutcome ? (headsBet ? query : headsKeys[0]) : tailsKeys[0];
    String resultMessage = headsBet == headsOutcome ? "discord.command.coin.result.win" : "discord.command.coin.result.lose";
    messageService.onMessage(message.getChannel(), resultMessage, query, outCome);
    return true;
}
 
Example #13
Source File: Item.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
public Item(ItemType type, String emoji, String name, String alias, String translatedName, String desc, long value, boolean sellable, boolean buyable, boolean hidden, long maxSize, TriPredicate<GuildMessageReceivedEvent, Pair<I18nContext, String>, Boolean> action, String recipe, boolean petOnly, int... recipeTypes) {
    this.emoji = emoji;
    this.name = name;
    this.desc = desc;
    this.value = value;
    this.price = value;
    this.sellable = sellable;
    this.buyable = buyable;
    this.maxSize = maxSize;
    this.hidden = hidden;
    this.action = action;
    this.itemType = type;
    this.recipe = recipe;
    this.recipeTypes = recipeTypes;
    this.translatedName = translatedName;
    this.alias = alias;
    this.petOnly = petOnly;
    log.debug("Registered item {}: {}", name, this.toVerboseString());
}
 
Example #14
Source File: ForwardCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean doInternal(GuildMessageReceivedEvent message, TrackRequest request, long millis) {
    PlaybackInstance instance = playerService.get(message.getGuild());

    AudioTrack track = request.getTrack();
    long duration = track.getDuration();
    long position = instance.getPosition();

    millis = Math.min(duration - position, millis);

    if (instance.seek(position + millis)) {
        messageManager.onMessage(message.getChannel(), "discord.command.audio.forward",
                messageManager.getTitle(track.getInfo()), CommonUtils.formatDuration(millis));
        request.setResetMessage(true);
        return true;
    }
    return fail(message);
}
 
Example #15
Source File: ShitCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final GuildMessageReceivedEvent event = ctx.getEvent();

    if (!passes(event, false)) {
        return;
    }

    final String text = parseTextArgsForImage(ctx);

    if (ctx.getParsedFlags(this).containsKey("p")) {
        ctx.getBlargbot().getShit(text, true).async((image) -> handleBasicImage(event, image));
        return;
    }

    ctx.getBlargbot().getShit(text).async((image) -> handleBasicImage(event, image));
}
 
Example #16
Source File: BonusCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String content) {
    if ("-".equals(content)) {
        if (patreonService.removeBoost(message.getAuthor().getIdLong(), message.getGuild().getIdLong())) {
            messageService.onEmbedMessage(message.getChannel(), "discord.command.bonus.disabled");
        } else {
            messageService.onEmbedMessage(message.getChannel(), "discord.command.bonus.not-applied");
        }
    } else if (patreonService.tryBoost(message.getAuthor().getIdLong(), message.getGuild().getIdLong())) {
        String bonusCommand = messageService.getMessageByLocale("discord.command.bonus.key",
                context.getCommandLocale());
        messageService.onEmbedMessage(message.getChannel(), "discord.command.bonus.applied",
                context.getConfig().getPrefix(), bonusCommand);
    }
    return true;
}
 
Example #17
Source File: MessageListener.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void checkSpamFilter(Message messageToCheck, GuildMessageReceivedEvent event, GuildSettings settings, DunctebotGuild g) {
    if (settings.isEnableSpamFilter()) {
        final long[] rates = settings.getRatelimits();

        spamFilter.applyRates(rates);

        if (spamFilter.check(new Triple<>(event.getMember(), messageToCheck, settings.getKickState()))) {
            modLog(event.getJDA().getSelfUser(), event.getAuthor(),
                settings.getKickState() ? "kicked" : "muted", "spam", g);
        }
    }
}
 
Example #18
Source File: MusicCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isAbleToJoinChannel(GuildMessageReceivedEvent event) {
    if (isUserOrGuildPatron(event, false)) {
        //If the member is not connected
        if (!event.getMember().getVoiceState().inVoiceChannel()) {
            return false;
        }

        return !getLavalinkManager().isConnected(event.getGuild());
    }

    return false;
}
 
Example #19
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void runNormalCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    if (cmd.getCategory() == CommandCategory.NSFW && !event.getChannel().isNSFW()) {
        sendMsg(event, "Woops, this channel is not marked as NSFW.\n" +
            "Please mark this channel as NSFW to use this command");
        return;
    }

    MDC.put("command.class", cmd.getClass().getName());

    LOGGER.info("Dispatching command \"{}\" in guild \"{}\" with {}", cmd.getClass().getSimpleName(), event.getGuild(), args);

    cmd.executeCommand(
        new CommandContext(invoke, args, event, variables)
    );
}
 
Example #20
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void dispatchCommand(String invoke, String invokeLower, List<String> args, GuildMessageReceivedEvent event) {
    ICommand cmd = getCommand(invokeLower);

    if (cmd == null) {
        cmd = getCustomCommand(invokeLower, event.getGuild().getIdLong());
    }

    if (cmd == null) {
        return;
    }

    dispatchCommand(cmd, invoke, args, event);
}
 
Example #21
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public void dispatchCommand(@Nonnull ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    this.commandThread.submit(() -> {
        MDC.put("command.invoke", invoke);
        MDC.put("command.args", args.toString());
        MDC.put("user.tag", event.getAuthor().getAsTag());
        MDC.put("user.id", event.getAuthor().getId());
        MDC.put("guild", event.getGuild().toString());
        setJDAContext(event.getJDA());

        final TextChannel channel = event.getChannel();

        if (!channel.canTalk()) {
            return;
        }

        // Suppress errors from when we can't type in the channel
        channel.sendTyping().queue(null, (t) -> {});

        try {
            if (!cmd.isCustom()) {
                runNormalCommand(cmd, invoke, args, event);
            } else {
                runCustomCommand(cmd, invoke, args, event);
            }
        }
        catch (Throwable ex) {
            Sentry.capture(ex);
            ex.printStackTrace();
            sendMsg(event, "Something went wrong whilst executing the command, my developers have been informed of this\n" + ex.getMessage());
        }
    });
}
 
Example #22
Source File: MentionableModeratorCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected boolean checkTarget(MemberReference reference, GuildMessageReceivedEvent event) {
    Member member = reference.getMember();
    if (member != null && (moderationService.isModerator(reference.getMember())
            || Objects.equals(member, event.getMember()))) {
        messageService.onTempEmbedMessage(event.getChannel(), 5, "discord.command.mod.ban.otherMod");
        return false;
    }
    return true;
}
 
Example #23
Source File: CommandHandlerFilter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public void doInternal(GuildMessageReceivedEvent event, FilterChain<GuildMessageReceivedEvent> chain) {
    for (CommandHandler handler : handlers) {
        try {
            if (handler.handleMessage(event)) {
                break;
            }
        } catch (Throwable e) {
            log.warn("Could not handle command", e);
        }
    }
    chain.doFilter(event);
}
 
Example #24
Source File: ClearCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void showHelp(GuildMessageReceivedEvent event, BotContext context) {
    String clearCommand = messageService.getMessageByLocale("discord.command.mod.clear.key",
            context.getCommandLocale());
    messageService.onEmbedMessage(event.getChannel(), "discord.command.mod.clear.help",
            context.getConfig().getPrefix(), clearCommand);
}
 
Example #25
Source File: InteractiveOperations.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onEvent(@Nonnull GenericEvent e) {
    if (!(e instanceof GuildMessageReceivedEvent))
        return;

    GuildMessageReceivedEvent event = (GuildMessageReceivedEvent) e;

    //Don't listen to ourselves...
    if (event.getAuthor().equals(event.getJDA().getSelfUser()))
        return;

    long channelId = event.getChannel().getIdLong();
    List<RunningOperation> l = OPS.get(channelId);

    if (l == null || l.isEmpty())
        return;

    l.removeIf(o -> {
        try {
            int i = o.operation.run(event);
            if (i == Operation.COMPLETED) {
                o.future.complete(null);
                return true;
            }
            if (i == Operation.RESET_TIMEOUT) {
                o.resetTimeout();
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    });
}
 
Example #26
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 #27
Source File: BaseCommandsService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public boolean isRestricted(GuildMessageReceivedEvent event, CommandConfig commandConfig) {
    if (isRestricted(commandConfig, event.getChannel())) {
        resultEmotion(event, "✋", null);
        messageService.onTempEmbedMessage(event.getChannel(), 10, "discord.command.restricted.channel");
        return true;
    }
    if (isRestricted(commandConfig, event.getMember())) {
        resultEmotion(event, "✋", null);
        messageService.onTempEmbedMessage(event.getChannel(), 10, "discord.command.restricted.roles");
        return true;
    }
    if (event.getMember() != null && commandConfig.getCoolDownMode() != CoolDownMode.NONE) {
        if (CollectionUtils.isEmpty(commandConfig.getCoolDownIgnoredRoles()) ||
                event.getMember().getRoles().stream().noneMatch(e -> commandConfig.getCoolDownIgnoredRoles().contains(e.getIdLong()))) {
            ModerationConfig moderationConfig = moderationConfigService.get(event.getGuild());
            if (!moderationService.isModerator(event.getMember())
                    || (moderationConfig != null && !moderationConfig.isCoolDownIgnored())) {
                CoolDownHolder holder = coolDownService.getCoolDownHolderMap()
                        .computeIfAbsent(event.getGuild().getIdLong(), CoolDownHolder::new);
                long duration = holder.perform(event, commandConfig);
                if (duration > 0) {
                    resultEmotion(event, "\uD83D\uDD5C", null);
                    String durationText = PrettyTimeUtils.print(duration, contextService.getLocale());
                    messageService.onTempEmbedMessage(event.getChannel(), 10,
                            "discord.command.restricted.cooldown", durationText);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #28
Source File: GroovyCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private GroovyShell getShell(GuildMessageReceivedEvent event) {
    GroovyShell shell = groovyService.createShell();
    shell.setProperty("sm", discordService.getShardManager());
    shell.setProperty("message", event.getMessage());
    shell.setProperty("channel", event.getChannel());
    shell.setProperty("guild", event.getGuild());
    shell.setProperty("member", event.getMember());
    shell.setProperty("author", event.getAuthor());
    return shell;
}
 
Example #29
Source File: RemoveWarnCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void showHelp(GuildMessageReceivedEvent event, BotContext context) {
    String warnsCommand = messageService.getMessageByLocale("discord.command.mod.warns.key",
            context.getCommandLocale());
    String removeWarmCommand = messageService.getMessageByLocale("discord.command.mod.removeWarm.key",
            context.getCommandLocale());
    messageService.onEmbedMessage(event.getChannel(), "discord.command.mod.removeWarm.help",
            context.getConfig().getPrefix(), warnsCommand, removeWarmCommand);
}
 
Example #30
Source File: TheSearchCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {

    final GuildMessageReceivedEvent event = ctx.getEvent();

    if (!passes(event)) {
        return;
    }

    ctx.getBlargbot().getTheSearch(parseTextArgsForImage(ctx)).async((image) -> handleBasicImage(event, image));
}