[精讚] [會員登入]
688

【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

你可能感興趣的文章

【CoreProtect】[SpigotMC] (進階篇) 如何直接存取資料 大家好,這裡是準備要去參加FF38的小編過路君子 本來只要自己去,結果臨時有人說要一起去,那...好吧!走~ 對於一般人

【自製-製作epub輔助工具】(Sigil) content產生器 能交給程式快速結束的地方就不要自己手動浪費時間了吧。

【C++】一些好用的C++小功能 —— 貳 承襲上一篇的C++小功能,筆記下來以免自己以後忘記了。

【C】(%c, %d)解決讀取字元時的緩衝區殘留 不解決就會莫名其妙地冒出一些莫名其妙的東西

【JDA/discord bot】刪除事件或slash(斜槓)指令的reply訊息 如何正確的等待 Async 的結束,在進行接下來的刪除訊息動作

【Linux】[CentOS 8]如何更新sudo指令 上次會想要更新sudo這個指令的時間應該是2017年了吧?轉眼間就2021了耶

我有話要說

>>

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

訪客留言

[無留言]

隨機好文

【手遊介紹】小品手遊─寶箱是我的!(SUMMONER'S GREED) 輕鬆無腦的塔防遊戲,殺時間本小編推薦的遊戲之一

高捷少女:布拉格體驗㊤ 「可……可以去歐洲玩?而且還有人出錢?太棒囉!」婕兒忍不住歡呼起來,把扳手拋呀拋的,旁邊的客人紛紛轉過來看。「好了啦!」耐耐忍不住害羞起來,輕輕敲了一下婕兒的頭

高捷少女:小穹與果仁巧克力㊤ 阿敏突然輕笑一聲,從櫃臺拿來一個塑膠餐盒,打開給大家看。「這是小穹烤的餅乾,妳們吃吃看就知道她為什麼不想講了。」小穹變得緊張起來。「阿敏,妳怎麼還留著呀?」艾米莉亞、婕兒與耐耐各自拿了一塊,把夾著奶油

高捷少女:小穹與果仁巧克力㊥ 艾咪臉上泛起笑容說:「妳知道嗎?就跟花語一樣,每一種巧克力也都有各自的涵義:薄荷巧克力代表初戀;卡通巧克力代表天真爛漫;而果仁巧克力代表的是窩心,還有想陪伴對方的心情,這在德國是女生之間在慶生時會彼此

高捷少女:購票大作戰① 「各位乘客,本班機即將降落,感謝各位乘客的搭乘……」隨著空中小姐的廣播音,那架飛機逐漸降落在地面,裡面的乘客們也紛紛開始整理自己的行李。 那個有著歐美人五官的少女抓緊包包,看著外面的小港機場,臉上緩緩