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

The following examples show how to use net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent#getGuild() . 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: MessageListener.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean doAutoModChecks(@Nonnull GuildMessageReceivedEvent event, GuildSettings settings, String rw) {
    final Guild guild = event.getGuild();
    if (guild.getSelfMember().hasPermission(Permission.MESSAGE_MANAGE)
        && !Objects.requireNonNull(event.getMember()).hasPermission(Permission.MESSAGE_MANAGE)) {

        checkMessageForInvites(guild, event, settings, rw);

        final Message messageToCheck = event.getMessage();
        final DunctebotGuild dbG = new DunctebotGuild(event.getGuild(), variables);

        if (blacklistedWordCheck(dbG, messageToCheck, event.getMember(), settings.getBlacklistedWords())) {
            return true;
        }

        if (checkSwearFilter(messageToCheck, event, dbG)) {
            return true;
        }

        checkSpamFilter(messageToCheck, event, settings, dbG);
    }

    return false;
}
 
Example 2
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 3
Source File: AudioEchoExample.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
{
    Message message = event.getMessage();
    User author = message.getAuthor();
    String content = message.getContentRaw();
    Guild guild = event.getGuild();

    // Ignore message if bot
    if (author.isBot())
        return;

    if (content.startsWith("!echo "))
    {
        String arg = content.substring("!echo ".length());
        onEchoCommand(event, guild, arg);
    }
    else if (content.equals("!echo"))
    {
        onEchoCommand(event);
    }
}
 
Example 4
Source File: MusicCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean channelChecks(GuildMessageReceivedEvent event, AudioUtils audioUtils, boolean reply, String prefix) {

        if (!event.getMember().getVoiceState().inVoiceChannel()) {
            sendMsg(event, "Please join a voice channel first");
            return false;
        }

        final LavalinkManager lavalinkManager = getLavalinkManager();
        final Guild guild = event.getGuild();

        if (!lavalinkManager.isConnected(guild)) {
            if (reply) {
                sendMsg(event, "I'm not in a voice channel, use `" + prefix + "join` to make me join a channel\n\n" +
                    "Want to have the bot automatically join your channel? Consider becoming a patron.");
            }

            return false;
        }

        if (lavalinkManager.getConnectedChannel(guild) != null &&
            !lavalinkManager.getConnectedChannel(guild).getMembers().contains(event.getMember())) {
            if (reply) {
                sendMsg(event, "I'm sorry, but you have to be in the same channel as me to use any music related commands");
            }

            return false;
        }

        getMusicManager(guild, audioUtils).setLastChannel(event.getChannel().getIdLong());

        return true;
    }
 
Example 5
Source File: CommandContext.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public CommandContext(String invoke, List<String> args, GuildMessageReceivedEvent event, Variables variables) {
    this.invoke = invoke;
    this.args = Collections.unmodifiableList(args);
    this.event = event;
    this.variables = variables;
    this.duncteBotGuild = new DunctebotGuild(event.getGuild(), variables);
}
 
Example 6
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 7
Source File: GameLobby.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public GameLobby(GuildMessageReceivedEvent event, I18nContext languageContext, List<String> players, LinkedList<Game<?>> games) {
    super(event.getGuild().getId(), event.getChannel().getId());
    this.guild = event.getGuild();
    this.event = event;
    this.players = players;
    this.languageContext = languageContext;
    this.gamesToPlay = games;
}
 
Example 8
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 9
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 10
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 11
Source File: TempMuteCommand.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final GuildMessageReceivedEvent event = ctx.getEvent();
    final List<String> args = ctx.getArgs();
    final GuildSettings settings = ctx.getGuildSettings();
    final List<Member> mentioned = ctx.getMentionedArg(0);

    if (mentioned.isEmpty()) {
        sendMsg(ctx, "I could not find any members with name " + args.get(0));
        return;
    }

    if (settings.getMuteRoleId() <= 0) {
        sendMsg(event, "No mute/spamrole is set, use `" + ctx.getPrefix() + "spamrole <Role>` to set it");
        return;
    }

    final User author = event.getAuthor();
    final Member mod = ctx.getMember();
    final Member toMute = mentioned.get(0);
    final User mutee = toMute.getUser();
    final Guild guild = event.getGuild();
    final Role role = guild.getRoleById(settings.getMuteRoleId());
    final Member self = ctx.getSelfMember();

    if (canNotProceed(ctx, event, mod, toMute, role, self)) {
        return;
    }

    String reason = "No reason given";
    final var flags = ctx.getParsedFlags(this);

    if (flags.containsKey("r")) {
        reason = String.join(" ", flags.get("r"));
    }

    final Duration duration = getDuration(args.get(1), getName(), event, ctx.getPrefix());

    if (duration == null) {
        return;
    }

    final String fReason = reason;
    final String finalDate = AirUtils.getDatabaseDateFormat(duration);

    ctx.getDatabaseAdapter().createMute(
        author.getIdLong(),
        mutee.getIdLong(),
        mutee.getAsTag(),
        finalDate,
        guild.getIdLong(),
        (mute) -> {
            if (mute != null) {
                final String modId = mute.getModId();
                final User oldMuteMod = guild.getJDA().getUserById(modId);
                String modName = "Unknown";

                if (oldMuteMod != null) {
                    modName = oldMuteMod.getAsTag();
                }

                sendMsg(event, String.format(
                    "Previously created muted for %#s removed, mute was created by %s",
                    mutee,
                    modName
                ));
            }

            return null;
        }
    );


    guild.addRoleToMember(toMute, role)
        .reason("Muted by " + author.getAsTag() + ": " + fReason)
        .queue(success -> {
                ModerationUtils.modLog(author, mutee, "muted", fReason, duration.toString(), ctx.getGuild());
                sendSuccess(event.getMessage());
            }
        );
}
 
Example 12
Source File: UserInfoCommand.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 query) {
    DateTimeFormatter formatter = DateTimeFormat.mediumDateTime()
            .withLocale(contextService.getLocale())
            .withZone(context.getTimeZone());

    LocalMember localMember = reference.getLocalMember();
    LocalUser localUser = reference.getLocalUser();

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.user.title", reference.getEffectiveName()));
    builder.setThumbnail(reference.getEffectiveAvatarUrl());
    builder.setFooter(messageService.getMessage("discord.command.info.identifier", reference.getId()), null);

    StringBuilder commonBuilder = new StringBuilder();
    getName(commonBuilder, reference);

    if (reference.getMember() != null) {
        Member member = reference.getMember();
        getOnlineStatus(commonBuilder, member);
        if (CollectionUtils.isNotEmpty(member.getActivities())) {
            getActivities(commonBuilder, member);
        }
        if (member.getOnlineStatus() == OnlineStatus.OFFLINE || member.getOnlineStatus() == OnlineStatus.INVISIBLE) {
            if (localUser != null && localUser.getLastOnline() != null) {
                getLastOnlineAt(commonBuilder, localUser, formatter);
            }
        }
        getJoinedAt(commonBuilder, member, formatter);
        getCreatedAt(commonBuilder, member.getUser(), formatter);
    }

    builder.addField(messageService.getMessage("discord.command.user.common"), commonBuilder.toString(), false);

    Guild guild = event.getGuild();

    if (localMember != null) {
        RankingConfig config = rankingConfigService.get(event.getGuild());
        if (config != null && config.isEnabled()) {
            RankingInfo info = rankingService.getRankingInfo(event.getGuild().getIdLong(), reference.getId());
            rankCommand.addFields(builder, config, info, guild);
        }
    }

    MemberBio memberBio = bioRepository.findByGuildIdAndUserId(guild.getIdLong(), reference.getId());
    String bio = memberBio != null ? memberBio.getBio() : null;
    if (StringUtils.isEmpty(bio)
            && Objects.equals(event.getAuthor(), reference.getUser())
            && !commandsService.isRestricted(BioCommand.KEY, event.getChannel(), event.getMember())) {
        String bioCommand = messageService.getMessageByLocale("discord.command.bio.key",
                context.getCommandLocale());
        bio = messageService.getMessage("discord.command.user.bio.none", context.getConfig().getPrefix(),
                bioCommand);
    }
    if (StringUtils.isNotEmpty(bio)) {
        builder.setDescription(CommonUtils.trimTo(bio, MessageEmbed.TEXT_MAX_LENGTH));
    }
    messageService.sendMessageSilent(event.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 13
Source File: CustomCommandsServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean sendCommand(GuildMessageReceivedEvent event, String content, String key, GuildConfig config) {
    Guild guild = event.getGuild();
    Member self = guild.getSelfMember();
    CustomCommand command = commandRepository.findByKeyAndGuildId(key, guild.getIdLong());
    if (command == null) {
        return false;
    }

    if (command.getCommandConfig() != null) {
        CommandConfig commandConfig = command.getCommandConfig();
        if (commandConfig.isDisabled() || isRestricted(event, commandConfig)) {
            return true;
        }
        if (commandConfig.isDeleteSource()
                && self.hasPermission(event.getChannel(), Permission.MESSAGE_MANAGE)) {
            messageService.delete(event.getMessage());
        }
    }

    if (!moderationService.isModerator(event.getMember())) {
        content = DiscordUtils.maskPublicMentions(content);
    }

    if (workerProperties.getCommands().isInvokeLogging()) {
        log.info("Invoke custom command [id={}]: {}", command.getId(), content);
    }

    if (command.getType() == CommandType.CHANGE_ROLES) {
        contextService.queue(guild, event.getChannel().sendTyping(), e -> changeRoles(event, command));
        return true;
    }

    MessageTemplateCompiler templateCompiler = templateService
            .createMessage(command.getMessageTemplate())
            .withGuild(guild)
            .withMember(event.getMember())
            .withFallbackChannel(event.getChannel())
            .withResolver(new ContentPlaceholderResolver(content));

    switch (command.getType()) {
        case ALIAS:
            String commandContent = templateCompiler.processContent(command.getContent(), true);
            if (StringUtils.isEmpty(commandContent)) {
                return true;
            }
            if (commandContent.startsWith(config.getPrefix())) {
                commandContent = commandContent.substring(config.getPrefix().length());
            }
            String[] args = commandContent.split("\\s+");
            if (args.length > 0) {
                commandContent = commandContent.substring(args[0].length()).trim();
                return internalCommandsService.sendCommand(event, CommonUtils.trimTo(commandContent, 2000), args[0], config);
            }
            break;
        case MESSAGE:
            templateCompiler.compileAndSend().whenComplete(((message, throwable) -> {
                if (message != null) {
                    registerReactions(message, command);
                }
            }));
            break;
    }
    return true;
}
 
Example 14
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);
}