Skip to main content

JDA 抓取 Discord Forum Channel 內的 Thread 清單

Code 範例

public class Main extends ListenerAdapter {

    public static final String TOKEN = "<BOT_TOKEN_HERE>";
    public static final String SERVER_ID = "<SERVER_ID_HERE>";
    public static final String PROJECT_FORUM_ID = "<FORUM_ID_HERE>";

    public static void main(String[] args) throws InterruptedException {
        JDA jda = JDABuilder.createDefault(Main.TOKEN).build();

        jda.addEventListener(new Main());
    }

    @Override
    public void onReady(ReadyEvent event) {
        System.out.println("Bot is ready");
        JDA jda = event.getJDA();

        Guild server = jda.getGuildById(SERVER_ID);
        assert server != null;
        ForumChannel channel  = server.getForumChannelById(PROJECT_FORUM_ID);
        assert channel != null;
        System.out.printf("Channel name: %s%n", channel.getName());
        List<ThreadChannel> threadChannels = channel.getThreadChannels();

        for(ThreadChannel thread : threadChannels){
            System.out.printf("Thread: %s%n", thread.getName());
        }
//        如果要正常關閉 Bot 的話需要以下指令
//        jda.shutdown();
    }
}

解釋

  • 用 JDA 物件取得 Guild 物件 (這邊先當作 Discord Server 的代表),再用 Guild 物件取得 ForumChnnel 物件
  • 接下來就好辦了:使用 getThreadChannels() 方法取得裡面充滿 ThreadChannel 的 List
  • 有了 List 物件,想要幹嘛都很方便,這邊以 for 迴圈做例子

注意

  • 範例的 TOKEN、Channel ID 都是寫死的 (Hardcode),正式環境不要這樣寫
  • JDA 是可以正常關機的 (JDA.shutdown()),強制關閉 Gradle 會提示回傳錯誤碼