[精讚] [會員登入]
731

【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

你可能感興趣的文章

【MEGAcmd】[Linux] 如何解決Unable to connect to service: error=2 用了好久的軟體突然停止一切的運作了。

【Wicket】[Header]如何讀取來自客戶端地檔頭和傳送自訂擋頭至客戶端 當需要設定檔頭或是讀取來自客戶端的檔頭時,這些程式碼就很好用

【Kali Linux】[history -c]如何清除歷史記錄 非bash環境會使history部分功能變的非法

【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

【教程】(進階版)如何用Sigil製作一本高質量的epub 下載好了Sigil之後除了直接把文字貼進去以外,還有:變更字型、著色、導入CSS……等等功能,不知道你有沒有發現呢?

【C++】如何解決TLE,換句話說便是加速cin, cout的執行速度 [ZERO JUDGE](UVa) a159: 11743 - Credit Check 題目練習和副程式練習

我有話要說

>>

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

訪客留言

[無留言]

隨機好文

高捷少女:布拉格體驗㊦ 「各位想到盧卡站的乘客,請到我們左手邊排隊!」婕兒大聲地喊道。     「這孩子怎麼穿著地鐵站制服?童工嗎?」一位大嬸歪頭問道。

高捷少女:購票大作戰② 一個不好的預感浮現,艾米莉亞開始檢查屋子四處。窗戶跟陽台都有關好,也沒有被打開的跡象。但一股無形的壓力,開始在寂靜的公寓中蔓延,她不安地嚥一下喉嚨。最後,她走向那扇窗戶,那前天晚上,白龍為了逃脫,而撞

高捷少女:美麗島的守護者⑤  雖然暫時不用怕牠們了,可是一直躲在這裡終究不是辦法,小雅心想。她看看四周,這間更衣室沒有窗戶或後門,她不禁著急起來,不可能一直躲在這裡面,但從門出去只會被群貓圍攻而已。小雅低下頭苦思該怎麼辦,過了不

高捷少女:耐耐的新年驚喜③ 即使如此,夫人仍然每年都會問老爺是否能空出一週時間,但總是被回絕,除了前年以外。老爺答應夫人一定會排出空檔,他們在去年的二十三日前往澳洲。」耐耐嘆了口氣。「那一天的晚上,我打電話給媽媽時,她很高興地告

婕兒──她的青春② 艾米直搖頭。「我真不敢相信,小穹妳都二十幾歲了,為什麼能想出這種故事呀?」「婕兒也是二十幾歲啊,妳想想她現在是什麼樣子?」小穹不滿地指向火車的方向。