不和谐的机器人即时通讯可以正确识别一个命令,但忽略另一个命令
该机器人应将dm发送给指定的用户,并进行适当处理。但是,该漫游器不会响应help命令。
@SubscribeEvent
public void onMessageRecived(GuildMessageReceivedEvent event) {
Member member = event.getMessage().getMentionedMembers().get(0);
System.out.println("message recived");
event.getAuthor().getName();
event.getMessage().getContentDisplay();
if (event.getMessage().getContentRaw().equals("!help")) {
event.getChannel().sendMessage("!help: displays this messgae" +
"!love (@user): Sends a dm to specified user that says 'I love you' in one of 102 languages").queue();
}
if (event.getMessage().getContentRaw().toLowerCase().startsWith("!love")) {
event.getChannel().sendMessage(member.getUser().getName() + " has been loved").queue();
机器人应该输出:
!help: Displays this message
!love (@user): Sends a dm to specified user that says 'I love you' in one of 102 languages
但是在提示!help时不输出任何内容
最佳答案
我注意到样本中可能有误的第一件事是方法名称的拼写。它被称为已接收但未接收。请注意,GuildMessageReceivedEvent仅针对公会中接收到的消息触发,如果您使用直接消息,则不会触发。
JDA实现事件处理的方式有两种,您可以从中选择。
InterfacedEventManager(默认)
文档:InterfacedEventManager,ListenerAdapter
创建一个监听器类
public class MessageListener extends ListenerAdapter {
@Override // this is good practice, it fails compilation if the method doesn't overeride
public void onMessageReceived(MessageReceivedEvent event) {
// your code here
}
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
// your code here
}
}
您的方法必须具有相同的名称,可见性和参数,以便正确覆盖
ListenerAdapter
中的定义。 @Override
的使用通过在格式错误的情况下生成编译错误来确保这一点。注册ListenerAdapter
JDABuilder builder = new JDABuilder(BOT_TOKEN);
builder.setEventManager(new InterfacedEventManager()); // this can be omitted, its the default
builder.addEventListener(new MessageListener());
JDA api = builder.build();
要求每个侦听器都为此事件管理器实现
EventListener
接口。这是由ListenerAdapter
可传递地完成的。AnnotatedEventManager
文档:AnnotatedEventManager,SubscribeEvent
创建侦听器方法
public class MessageSubscriber {
@SubscribeEvent // required annotation
public void onMessage(MessageReceivedEvent event) {
// your code here
}
@SubscribeEvent // required annotation
public void onGuildMessage(GuildMessageReceivedEvent event) {
// your code here
}
}
您可以在成员方法和类方法(静态方法)上添加
@SubscribeEvent
批注。注册订户
JDABuilder builder = new JDABuilder(BOT_TOKEN);
builder.setEventManager(new AnnotatedEventManager());
builder.addEventListener(new MessageSubscriber());
JDA api = builder.build();
如果为类方法添加了注释,则可以简单地使用
addEventListener(MessageSubscriber.class)
,对于成员方法,它必须是新实例new MessageSubscriber()
!如果这不能回答您的问题,则您可能有一些无法从当前问题中解释的问题。请通过调试代码并创建MCVE将其限制为特定问题。