JDA – 如何获取机器人自身的用户ID

huangapple go评论94阅读模式
英文:

JDA - How to get the user ID of the bot itself

问题

我正在制作一个使用JDA(Java Discord API)的程序,需要检查消息是否是由机器人自己发送的。我该如何实现这一点?我考虑过通过检查消息发送者的用户ID是否等于机器人的用户ID来实现,但是在程序中如何获取机器人自身的用户ID呢?

英文:

I'm making a JDA (Java Discord API) program that needs to check if a message was sent by the bot itself. How can I achieve this? I thought about checking if the user ID of the message sender equals the bot's user ID, but how can I get the user ID of the bot itself in the program?

答案1

得分: 1

If you use the MessageReceivedEvent, you can just check if the sender is a bot by using:
event.getAuthor.isBot().

You can access the user of the bot itself by accessing JDA and calling getSelfUser() as follows with the MessageReceivedEvent in mind:
event.getJDA().getSelfUser()

On the SelfUser you can call SelfUser#getId() or SelfUser#getIdLong() to access the ID.

Example Code:

public class Listener extends ListenerAdapter {
  @Override
  public void onMessageReceived(MessageReceivedEvent event) {
    boolean isBot = event.getAuthor().isBot(); // 检查消息发送者是否为机器人
    
    long id = event.getJDA().getSelfUser().getIdLong(); // 机器人的ID
  }
}
英文:

If you use the MessageReceivedEvent, you can just check if the sender is a bot by using:
event.getAuthor.isBot().

You can access the user of the bot itself by accessing JDA and calling getSelfUser() as follows with the MessageReceivedEvent in mind:
event.getJDA().getSelfUser()

On the SelfUser you can call SelfUser#getId() or SelfUser#getIdLong() to access the ID.

Example Code

public class Listener extends ListenerAdapter {
  @Override
  public void onMessageReceived(MessageReceivedEvent event) {
    boolean isBot = event.getAuthor().isBot() //Check if the Message Sender is a bot
    
    long id = event.getJDA().getSelfUser().getIdLong() //the bot ID
  }
}

huangapple
  • 本文由 发表于 2020年8月1日 03:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63197812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定