Reputation: 77
I'm trying to make a very simple discord bot and it is my first time making one in java (with the IntelliJ IDE). It logs in and goes online correctly, but won't receive any messages that I send in the guild. The code is below:
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class Main extends ListenerAdapter {
public static void main(String[] args) throws Exception{
JDABuilder bot = new JDABuilder(AccountType.BOT);
String token = "token";
bot.setToken(token);
bot.build();
}
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
System.out.println("message received");
event.getChannel().sendMessage("reeeeeeee");
super.onMessageReceived(event);
}
}
I think that the flawed part is somewhere around "public void onMessageReceived". I have tried many things such as rearranging my code or rewriting it, but nothing seems to work.
Upvotes: 0
Views: 2810
Reputation: 6134
You didn't call queue()
on the MessageAction
returned by sendMessage
.
Nothing happens when using X
In JDA we make use of async rate-limit handling through the use of the common RestAction class. When you have code such as channel.sendMessage("hello"); or message.delete(); nothing actually happens. This is because both sendMessage(...) as well as delete() return a RestAction instance. You are not done here since that class is only an intermediate step to executing your request. Here you can decide to use async queue() (recommended) or submit() or the blocking complete() (not recommended).
You might notice that queue() returns void. This is because it's async and uses callbacks instead. Read More
From the JDA Troubleshooting Wiki
You also never registered your event listener. And you're using the deprecated constructor for JDABuilder.
public class Main extends ListenerAdapter {
public static void main(String[] args) throws Exception{
JDABuilder.createDefault(token) // don't use the deprecated constructor
.addEventListeners(new Main()) // register your listener
.build();
}
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
System.out.println("message received");
event.getChannel().sendMessage("reeeeeeee").queue(); // call queue
}
}
And you should never leak your bot token anywhere!
Upvotes: 2