I have created a discord bot using spring boot with discord4j dependency. The bot appears as online at the discord server, but doesn't respond to the command !todo which should have printed a to do list. The project compiles without any errors.
CONFIGURATION CLASS:
package com.example.demo;
import discord4j.core.DiscordClientBuilder;
import discord4j.core.GatewayDiscordClient;
import discord4j.core.event.domain.Event;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class ConfigurationClass {
@Value("${token}")
private String token;
@Bean
public <T extends Event> GatewayDiscordClient gatewayDiscordClient(List<EventListener<T>> eventListeners) {
GatewayDiscordClient client = DiscordClientBuilder.create(token)
.build()
.login()
.block();
for (EventListener<T> listener : eventListeners) {
client.on(listener.getEventType())
.flatMap(listener::execute)
.onErrorResume(listener::handleError)
.subscribe();
}
return client;
}
}
MESSAGE CREATED CLASS:
import com.austinv11.servicer.Service;
import discord4j.core.event.domain.message.MessageCreateEvent;
import reactor.core.publisher.Mono;
@Service
public class MessageCreateListener extends MessageListener implements EventListener<MessageCreateEvent> {
@Override
public Class<MessageCreateEvent> getEventType() {
return MessageCreateEvent.class;
}
@Override
public Mono<Void> execute(MessageCreateEvent event) {
return processCommand(event.getMessage());
}
}
MESSAGE LISTENER CLASS:
package com.example.demo;
import discord4j.core.object.entity.Message;
import reactor.core.publisher.Mono;
public abstract class MessageListener {
public Mono<Void> processCommand(Message eventMessage) {
return Mono.just(eventMessage)
.filter(message -> message.getAuthor().map(user -> !user.isBot()).orElse(false))
.filter(message -> message.getContent().equalsIgnoreCase("!todo"))
.flatMap(Message::getChannel)
.flatMap(channel -> channel.createMessage("Things to do today:\n - write a bot\n - eat lunch\n - play a game"))
.then();
}
}
EVENT LISTENER INTERFACE :
package com.example.demo;
import discord4j.core.event.domain.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
public interface EventListener<T extends Event> {
Logger LOG = LoggerFactory.getLogger(EventListener.class);
Class<T> getEventType();
Mono<Void> execute(T event);
default Mono<Void> handleError(Throwable error) {
LOG.error("Unable to process " getEventType().getSimpleName(), error);
return Mono.empty();
}
}
CodePudding user response:
You are using com.austinv11.servicer.Service
instead of org.springframework.stereotype.Service
so MessageCreateListener
will not be picked up by classpath scanning.