簡體   English   中英

如何檢查 discord.js 中是否存在消息

[英]How can I check If a message exists in discord.js

我想在我的機器人中加入某種反應角色。 為此,我必須測試用戶發送給機器人的消息 ID 是否有效。 有人可以告訴我該怎么做嗎?

只要您還知道您正在查看的頻道,您就可以使用.fetch()來做到這一點。

如果消息在用戶發送 ID 的同一頻道中,那么您可以使用message.channel獲取頻道,或者如果它在另一個頻道中,則您必須使用其 ID 使用message.guild.channels.cache.get(CHANNEL_ID)

因此,如果它在同一個頻道中,您的代碼可能是這樣的:

const msg = message.channel.messages.fetch(MESSAGE_ID)

或者如果它在不同的頻道中:

const channel = message.guild.channels.cache.get(CHANNEL_ID)
const msg = channel.messages.fetch(MESSAGE_ID)

這對我有用(Discord.js v12)

首先,您需要定義您希望機器人搜索消息的渠道。
(你可以像這樣找到它)

const targetedChannel = client.channels.cache.find((channel) => channel.name === "<Channel Name>");

然后你需要添加這個function:

async function setMessageValue (_messageID, _targetedChannel) {
    let foundMessage = new String();
    
    // Check if the message contains only numbers (Beacause ID contains only numbers)
    if (!Number(_messageID)) return 'FAIL_ID=NAN';

    // Check if the Message with the targeted ID is found from the Discord.js API
    try {
        await Promise.all([_targetedChannel.messages.fetch(_messageID)]);
    } catch (error) {
        // Error: Message not found
        if (error.code == 10008) {
            console.error('Failed to find the message! Setting value to error message...');
            foundMessage = 'FAIL_ID';
        }
    } finally {
        // If the type of variable is string (Contains an error message inside) then just return the fail message.
        if (typeof foundMessage == 'string') return foundMessage;
        // Else if the type of the variable is not a string (beacause is an object with the message props) return back the targeted message object.
        return _targetedChannel.messages.fetch(_messageID);
    }
}

在此過程之后,只需將 function 值獲取到另一個變量:

const messageReturn = await setMessageValue("MessageID", targetedChannel);

然后你可以隨心所欲地使用它。
例如,您可以使用以下代碼編輯該消息:

messageReturn.edit("<Your text here>");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM