我试图编写一个DMS识别的机器人,但我无法根据用户的ID找到用户.

package me.rtx4090;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.events.guild.GuildReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.entities.User;

public class Main extends ListenerAdapter {
    private JDA jda;

    public Main() {
        String botToken = "(censored)";
        jda = JDABuilder.createDefault(botToken).addEventListeners(this).build();
    }

    public static void main(String[] args) {
        new Main();
    }

    @Override
    public void onGuildReady(GuildReadyEvent event) {
        System.out.println("All members in the guild " + event.getGuild().getName() + " have been downloaded.");

        sendPrivateMessage();
    }

    private void sendPrivateMessage() {
        String recipientUserId = "(censored)"; 
        String messageContent = "L";

        User recipient = jda.getUserById(recipientUserId);
        System.out.println(recipient);

        if (recipient != null) {
            recipient.openPrivateChannel().queue(privateChannel -> {
                privateChannel.sendMessage(messageContent).queue();
                System.out.println("Message has been sent to " + recipient.getAsTag() + " successfully");
            });
        } else {
            System.out.println("Can't find the user. Please make sure you've used the correct ID");
        }
    }
}

推荐答案

您可以使用openPrivateChannelById:

jda.openPrivateChannelById(recipientUserId).queue(channel -> {
  User user = channel.getUser();
  channel.sendMessage(messageContent).queue();
  System.out.printf("Message has been sent to %#s successfully\n", user);
});

Java相关问答推荐

是否有一种格式模式,可以在除0之外的数字前面有正负符号?

我想了解Java中的模块化.编译我的应用程序时,我有一个ResolutionException

Character::Emoji不支持带数字的字符吗?

Java .类参数不通过构造函数传递

对某一Hyroby控制器禁用@cacheable

是否在允许数组元素为空时阻止 idea 为空性警告?

使用Mockito进行的Junit测试失败

带有Health Check的Spring Boot BuildPack打破了本机映像构建过程

在添加AdMob时无法为Google Play构建应用程序包:JVM垃圾收集器崩溃和JVM内存耗尽

在Eclipse中调试未导出的JDK模块的Java包

Java Telnet客户端重复的IAC符号

为什么Collectors.toList()不能保证易变性

FETCH类型设置为LAZY,但它仍会发送第二个请求

如何在IntelliJ IDEA的Build.sbt中添加外部JAR文件?

在打开搜索结果时,如何让Eclipse打开整个文件?

没有Tomcat,IntelliJ如何在本地运行API?

在Java中将对象&转换为&q;HashMap(&Q)

如何在右击时 Select 新行?

按长度排序字符串数组

我可以使用一个 PoolingNHttpClientConnectionManager 运行多个 HttpAsyncClient 吗?