簡體   English   中英

使用 discord.js 邀請獲得公會機器人

[英]Getting guilds bot is in with invites using discord.js

我正在嘗試使用邀請制作命令列表服務器。 我想要的是該命令輸出服務器邀請數組。
所以,第一件事是我不能在.then()塊中使用.push() ,因為數組返回空並且與回調有關。 我會嘗試使用Promise ,特別是Promise.all.map以便機器人可以返回行會列表,但如果我嘗試定義輸出[undefined, undefined]的邀請服務器。 也許是因為我沒有指定要返回什么或者我做錯了?

下面是代碼:

// headers, client.on and switch statement...
   case "getservers":
      var ServersEmbed = new discord.MessageEmbed()
          .setColor(theme.theme.embedColours[0])
          .setAuthor("Getting server list...")
      ;
      var m = await msg.channel.send(ServersEmbed);
      var l = await Promise.all(client.guilds.cache.map(guild => {
          var inv = guild.channels.cache.filter(i => i.type != "category").random().createInvite();
          return inv.url;
      }));
      console.log(l);
      // m.edit(...
      break;
// more cases and fun...

也許在Promise.all塊中使用return是錯誤的。 client.on("message"...在我的源代碼中也是異步的。

You don't have to use Promise.all() on the map, if you don't have something to await inside the map function, and you aren't using async on the function, so you can't even use await if你想。

OP的問題是他們正在分配 Promise.all() 的結果,但試圖在 Promise.all() 完成之前讀取該變量。

使用 await 時,如果您希望代碼停止繼續運行,直到 Promise 實際完成,您必須在某個時候關閉 promise。 另外,我建議不要依賴緩存來處理邀請之類的事情,因此請改用 guild Object's.fetchInvites() 方法並進行迭代

這是我用來獲得所有公會邀請的方法:

// Discord.js v12 API - later versions may use different method/property names.
async function getGuildInvites(guildOBJ) {
  let invites = [];
  await guildOBJ.fetchInvites()
  .then((invite_arr) => {
    invite_arr.forEach((i)=>{
      invites.push(JSON.parse(JSON.stringify(i)));
    });
  });
  return invites;
}

var guild_invites = await getGuildInvites(guild);

只需像您一樣構建一個公會對象數組,但不要嘗試映射/過濾和使用客戶端 guild.cache,而是積極等待獲取,將每個 object 放入數組中,然后您可以循環每個數組元素,調用getGuildInvites() function,它將等待每次迭代完成,從而允許您使用其邀請數組覆蓋 guildObject 元素,或者您可以將其分配給由 guild.id 字符串索引的 Object。 不要忘記依賴任何 Object 在它的承諾/獲取器之外保持活力是不安全的; 將生成的 Object 分配為 ByRef 並且可能會丟失,這就是為什么我使用 JSON.parse(JSON.stringify(obj)) 到深度克隆...或者您可以返回自己的 ZA8CFDE6331BD59EB6AC96F8911ZC4首先只需要 4 個邀請屬性)。

但請注意,Discord.js 文檔警告您,唯一保證可用的邀請屬性是代碼、頻道和 url。

順便說一句,我個人認為 url 屬性是為了方便程序員,因為 url 只是字符串“https://discord.gg/”+invite.code。 當我將邀請信息存儲在數據庫記錄中時,我會存儲代碼而不是 url,因為如果需要,我可以隨時重建 url。

暫無
暫無

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

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