首頁  >  問答  >  主體

在斜線指令中,如何透過使用者ID取得使用者?

我一直在編寫一個Discord機器人,根據需要參考教程,因為我是新手,但是我遇到了一個問題,儘管聽起來很簡單,但我似乎無法解決。我正在嘗試繪製一個排行榜,並且對於排行榜上的每個位置,我想獲取用戶的頭像來繪製到排行榜上。為了做到這一點,我希望能夠僅透過用戶ID獲取用戶。然而,我正在一個單獨的斜杠命令中完成所有這些操作。以下是一個非常簡化的範例,以提供一些背景和/或更好的解釋:

const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
// ... some functions and what not go here
module.exports = {
   //... lines for setting up the command go here

   async execute(interaction){
       const data = fetchData();  //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary
       // ... a bunch of stuff, ordering my data, etc.
       data.forEach(async (userData, index) => {
          // And here begins my issue. The line below is just what I have attempted to do
          const target = interaction.guild.members.cache.get(userData.UserId); 
       });
   };
}

我已經進行了相當多的研究,而我找到的唯一可行的解​​決方案(你可以在上面的範例程式碼中看到)是使用const target = interaction.guild.members.cache.get("User_ID "); 然而,儘管我可以在控制台中記錄返回值,但如果我嘗試執行類似"target.user" 的操作,它會顯示target 未定義。如果有幫助的話,是的,我在我的意圖中包含了 GuildMembers。

P粉368878176P粉368878176460 天前479

全部回覆(2)我來回復

  • P粉029327711

    P粉0293277112023-07-19 15:38:14

    如果你只想取得執行斜線指令的使用者的ID,你可以使用 interaction.user.id。

    要透過ID取得用戶,你可以執行以下程式碼:

    //Inside the execute function of the slash command
    
    interaction.guild.members.cache.get("user_id").then(function(user){
        //Do something with user
    } 

    回覆
    0
  • P粉006977956

    P粉0069779562023-07-19 12:06:11

    你需要使用 members.fetch,因為它是非同步的,所以你需要將你的 forEach 改為 for...of,因為 forEach 是同步的。

    const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
    // ... some functions and what not go here
    module.exports = {
       //... lines for setting up the command go here
    
       async execute(interaction) {
           const data = fetchData();  //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary
           // ... a bunch of stuff, ordering my data, etc.
           for (const userData of data) {
             const target = await interaction.guild.members.fetch(userData.UserId)
           }
       };
    } 

    回覆
    0
  • 取消回覆