JDA-发送消息

时间:2018-11-26 15:43:11

标签: java discord discord-jda

我有自己的基于JDA的Discord BOT。我需要向特定频道发送短信。我知道如何将消息作为onEvent响应发送,但是在我的情况下,我没有此类事件。

我有:作者(BOT),令牌和频道号。

我的问题是:如何在没有事件的情况下将消息发送到该频道

2 个答案:

答案 0 :(得分:2)

好吧,我想我知道你的意思。您无需进行任何事件即可获取频道ID和发送消息。您唯一需要做的就是实例化JDA,调用awaitReady(),从实例中可以获取所有通道(MessageChannels,TextChannels,VoiceChannels,可以通过调用

  • get [Text] Channels()
  • get [Text] ChannelById(id = ..)
  • 获取[文本] ChannelsByName(名称,忽略大小写)

所以1.实例化JDA

    JDABuilder builder; 
    JDA jda = builder.build();
    jda.awaitReady();
  1. 获取频道

    List<TextChannel> channels = jda.getTextChannelsByName("general", true);
    for(TextChannel ch : channels)
    {
        sendMessage(ch, "message");
    }
    
  2. 发送消息

    static void sendMessage(TextChannel ch, String msg) 
    {
        ch.sendMessage(msg).queue();
    }
    

希望有帮助。

答案 1 :(得分:1)

您只需要做一件事,即JDA的一个实例。可以从大多数实体(例如User / Guild / Channel和每个Event实例)中检索到此信息。这样,您可以使用JDA.getTextChannelById来检索TextChannel实例以发送消息。

class MyClass {
    private final JDA api;
    private final long channelId;
    private final String content;

    public MyClass(JDA api) {
        this.api = api;
    }

    public void doThing() {
         TextChannel channel = api.getTextChannelById(this.channelId);
         if (channel != null) {
             channel.sendMessage(this.content).queue();
         }
    }
}

如果您没有JDA实例,则必须手动执行HTTP请求以发送消息,为此查询discord documentationjda source code。 JDA源代码可能有点太复杂,以至于无法作为示例,因为它的抽象性允许使用任何端点。

相关问题