Multiple Message Problem with JDA Bot
I’m having trouble with my Discord bot built using JDA. Every time I restart my application, the bot sends one additional duplicate message. So first run sends 1 message, second run sends 2 copies, third run sends 3 copies, and so on.
Main Bot Class
package com.mybot.discord;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
public class BotApplication {
public static JDA botInstance;
public static String commandPrefix = "!";
public static void main(String[] args) throws LoginException {
botInstance = JDABuilder.createDefault("bot_token_here").build();
botInstance.getPresence().setStatus(OnlineStatus.ONLINE);
Activity watching = Activity.watching("Naruto");
botInstance.getPresence().setActivity(watching);
MessageHandler handler = new MessageHandler();
botInstance.addEventListener(handler);
}
}
Event Handler Class
package com.mybot.discord;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class MessageHandler extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent msg) {
String[] parts = msg.getMessage().getContentRaw().split("\\s+");
if(parts[0].startsWith(BotApplication.commandPrefix)) {
parts[0] = parts[0].substring(1);
switch (parts[0]) {
case "about":
msg.getChannel().sendTyping().queue();
msg.getChannel().sendMessage("Hello! I'm a helpful Discord bot").queue();
break;
case "welcome":
msg.getChannel().sendTyping().queue();
msg.getChannel().sendMessage(msg.getAuthor().getName()+" says hello to "+parts[1]).queue();
break;
default:
msg.getChannel().sendTyping().queue();
msg.getChannel().sendMessage("Sorry, I don't recognize that command yet").queue();
break;
}
}
}
}
The Issue
When I type !about the bot responds like:
- “Hello! I’m a helpful Discord bot”
- “Hello! I’m a helpful Discord bot”
- “Hello! I’m a helpful Discord bot”
- “Hello! I’m a helpful Discord bot”
- “Hello! I’m a helpful Discord bot”
I think each time I restart the program it adds another event listener somehow. How can I fix this duplicate message problem?