I'm using JDA 4.4.0_352 and my Discord Bot is unable to send message in the channel

Viewed 54

Here's my code in Bot.java.


import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import javax.security.auth.login.LoginException;

public class Bot {

    private JDA api;

    public Bot() throws LoginException, InterruptedException {
        api = JDABuilder.createDefault("token")
        .addEventListeners(new search()).build()
                .awaitReady();
    }

    public static void main(String[] args) throws LoginException, InterruptedException {
        new Bot();
    }
}

token is replaced with an actual token in my code :)

And here's my code in search.java


package core;

import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;

public class search extends ListenerAdapter {

    @Override
    public void onMessageReceived(MessageReceivedEvent event) {
        String msg = event.getMessage().getContentRaw();

        if (event.getAuthor().isBot())
            return;

        if (msg.equalsIgnoreCase("!search")) {
            event.getPrivateChannel()
                    .sendMessage("Please enter the course name: ").queue();
        }
    }
}

I'm not sure why my bot doesn't send the appropriate message when I put search to my discord channel (tried both private and guild).

Please let me know if you know where the problem is, thank you!

1 Answers

The Bot's intents/permissions need to be set in the createDefault method (and possibly inside the discord developer portal). For direct messages it'd be:

        JDABuilder.createDefault("token", GatewayIntent.DIRECT_MESSAGES)

To handle messages in your guild, I think it'd require Message Content Intent enabled in the discord developer portal; and it'd be:

        JDABuilder.createDefault("token", GatewayIntent.GUILD_MESSAGES)

The GatewayIntent parameter inside the createDefault method uses varargs, so you can tack on any number of intents:

JDABuilder.createDefault("token", GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_MESSAGES)

Also, event.getPrivateChannel() will throw an IllegalStateException in the event that the message is not from a private channel; I'd recommend first checking if event.getChannelType() == ChannelType.PRIVATE, or a try/catch.

Related