[精讚] [會員登入]
485

【JDA/discord bot】刪除事件或slash(斜槓)指令的reply訊息

如何正確的等待 Async 的結束,在進行接下來的刪除訊息動作

分享此文連結 //n.sfs.tw/16362

分享連結 【JDA/discord bot】刪除事件或slash(斜槓)指令的reply訊息@小編過路君子
(文章歡迎轉載,務必尊重版權註明連結來源)
2024-02-15 16:33:03 最後編修
2024-02-15 15:03:48 By 過路君子
 

哈囉大家好,這裡是在回顧自己舊文章的小編過路君子

小編正在回顧自己以前寫的 Wicket 系列文章,恩,沒錯,仍是 Java 這個程式語言

 

 

 

小編所使用的 JDA 版本是:5.0.0-beta.20

小編之前一直都是使用 discord.py 的 command_prefix 來實現命令的,而小編也比較喜歡這個方式,但似乎 JDA 並未提供相關的設置可以使用,小編目前也在慎重的考慮是否手動實現相關的功能,目前有考慮使用 Map 來達成快速索引以重現相關的功能。

但有一點是可以肯定的,就是那個 reply 是真的很醜,還不如直接 sendMessage() 來的好看。

 

所以小編就想在 reply 之後刪除剛剛 reply 的訊息並重新傳送一段新的訊息到聊天室內。

但這個時候就又遇到新的問題了,就是如果直接去呼叫 getIterableHistory() 的話,有可能會取得使用者的命令訊息而非機器人的 reply 訊息。

為了解決這個問題,我們勢必得等到整個 reply 或 sendMessage 的 Async 完成之後,再去取得頻道的訊息才行。

 

那在這邊小編提供兩種情況下的使用。

分別是使用 sendMessage() 和事件的響應,例如 onSlashCommandInteraction 等等事件,順手再各提供一種 onSuccess() 的變體寫法。

刪除sendMessage的訊息

使用 queue()

import java.util.List;
import net.dv8tion.jda.api.JDA;
import java.util.stream.Collectors;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;

public void deleteSentMessage(JDA bot)
{
    // Get the channel
    long channelID = 9000000000L;
    TextChannel channel = bot.getTextChannelById(channelID);

    // Callback values class type is:
    // net.dv8tion.jda.internal.interactions.InteractionHookImpl
    channel.sendMessage("will delete").queue(interactionHookImpl ->
    {
        try
        {
            // Try to get the last message on that channel.
            List<Message> message = channel.getIterableHistory().takeAsync(1).thenApply(list -> list.stream().collect(Collectors.toList())).get();
         
            // If successful, get the corresponding message.
            if(message.isEmpty()) return;
            Message last = message.get(0);
         
            // Delete it.
            last.delete().queue();
        }
        catch(Exception error) {System.out.println(error);}
    });
}

使用 onSuccess()

import java.util.List;
import net.dv8tion.jda.api.JDA;
import java.util.stream.Collectors;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;

public void deleteSentMessage(JDA bot)
{
    // Get the channel
    long channelID = 9000000000L;
    TextChannel channel = bot.getTextChannelById(channelID);

    // Callback values class type is:
    // net.dv8tion.jda.internal.interactions.InteractionHookImpl
    channel.sendMessage("will delete").onSuccess(interactionHookImpl ->
    {
        try
        {
            // Try to get the last message on that channel.
            List<Message> message = channel.getIterableHistory().takeAsync(1).thenApply(list -> list.stream().collect(Collectors.toList())).get();
         
            // If successful, get the corresponding message.
            if(message.isEmpty()) return;
            Message last = message.get(0);
         
            // Delete it.
            last.delete().queue();
        }
        catch(Exception error) {System.out.println(error);}
    }).queue();
}

大同小異,就是呼叫函數的時機不同而已,整體結構都一樣,依照個人喜好使用即可。

 

刪除由事件回應(event reply)的訊息

小編在此同樣提供兩種寫法,以供各位自行取用。

由於 JDA 內的事件眾多,而每個事件之間又有些微的差異,這邊小編僅以 onSlashCommandInteraction 這個事件作為範例。

更詳細的訊息可以參考 javadoc 的 ListenerAdapter 說明頁面

(所有圖片點擊都可以放大、變高清)

使用 queue()

import java.util.stream.Collectors;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;

public class DiscordEvents extends ListenerAdapter
{
    @Override
    public void onSlashCommandInteraction(SlashCommandInteractionEvent event)
    {
        // callback values class type is:
        // net.dv8tion.jda.internal.interactions.InteractionHookImpl
        event.reply("Test!").queue(interactionHookImpl ->
        {
            try
            {
                // Try to get the message that just replied
                Message message = event.getChannel().getIterableHistory().takeAsync(1).thenApply(list -> list.stream().collect(Collectors.toList())).get().get(0);

                // If the user is not the bot itself,
                // the delete command is not executed.
                if(last.getAuthor().getIdLong() != event.getJDA().getSelfUser().getIdLong()) return;

                // Delete it.
                last.delete().queue();
            }
            catch(Exception error) {System.out.println(error);}
        });
    }
}

使用 onSuccess()

import java.util.stream.Collectors;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;

public class DiscordEvents extends ListenerAdapter
{
    @Override
    public void onSlashCommandInteraction(SlashCommandInteractionEvent event)
    {
        // callback values class type is:
        // net.dv8tion.jda.internal.interactions.InteractionHookImpl
        event.reply("Test!").onSuccess(interactionHookImpl ->
        {
            try
            {
                // Try to get the message that just replied
                Message message = event.getChannel().getIterableHistory().takeAsync(1).thenApply(list -> list.stream().collect(Collectors.toList())).get().get(0);

                // If the user is not the bot itself,
                // the delete command is not executed.
                if(last.getAuthor().getIdLong() != event.getJDA().getSelfUser().getIdLong()) return;

                // Delete it.
                last.delete().queue();
            }
            catch(Exception error) {System.out.println(error);}
        }).queue();
    }
}

 

 

 

後記

細心的人應該已經發現了,小編提供的程式碼之中都有些微的差異,而非完全相同,是小編故意的。

不同的寫法因應不同的場景,依照個人需求斟酌使用吧。

END

你可能感興趣的文章

【C++】class練習 — 檢測該字串是否為迴圈 第一次的C++結構式寫法,雖然以後應該會見怪不怪,但畢竟是第一次所以還是想保存下來

【Linux】[CentOS 8] How to update sudo instruction The last time I wanted to update the sudo command should be 2017, right? It's 2021 in a blink of an

【Javascript】(Event)常用的網頁事件 不寫下來絕對下又會忘記,然後每次又都要回到MDN去查,麻煩

【教程】[HTML](進階版)如何在手機上編輯電子書(epub)預覽介面 可能會有人認為電子書(epub)只能用電腦來開啟、編輯,其實不是的,手機也可以編輯喔!

【Stable Diffusion web UI】[AI 作畫](Linux)無 NVIDIA 顯卡之伺服器運行測試 凡事就是要試試看,才知道最後的結果

【PaperMC - API】如何發送指令到伺服器內 How to sending or executing commands to server

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

高捷少女:地下城的探險少女② 「等我一下喔,我好像有帶去漬的清潔噴霧。」婕兒翻翻飛揚,拿出噴霧劑給小穹,小穹趕緊對著汙漬噴了噴,紅茶漬果然乾淨了許多。「婕兒,謝謝妳。來,還妳。」小穹感謝地把噴霧還給她,卻發現婕兒盯著打開的飛揚,一

婕兒──她的青春① 「各位乘客,本列車即將抵達拉里奧哈自治區,並在此地停留三天兩夜,後天的中午十二點將搭乘班機返回臺灣,感謝各位乘客對本次旅程的配合。」火車上的廣播器朗誦道。「時間過得真快呢,這次的歐洲之旅就這樣結束了,

【歌評】蓮台野夜行 - 魔術師梅莉(魔術師メリー)  對於同一首歌每一個人都有不同的見解,看看別人對於這一首歌的看法,說不定就可以聽出這首歌想要表達的事情!

【專輯介紹】蓮台野夜行 ~ Ghostly Field Club,れんだいのやこう 就讓我們隨著音樂跟著秘封俱樂部一起探詢那不可思議的未知和神秘,若處理不好,說不定會招來奇怪的靈呦(・ω<)☆

【國文】虬髯客傳 大綱① (無本文、無翻譯) 本書被稱為唐人小說最高傑作 本書是一本符合小說五要素的,所以我們來看看其中的時間、空間以及人物。何謂小說五要素?