在 guild.roles 中获取未定义
Posted
技术标签:
【中文标题】在 guild.roles 中获取未定义【英文标题】:fetch undefined in guild.roles 【发布时间】:2021-02-23 23:16:32 【问题描述】:您好,我正在尝试编写一个 discordbot,将公会 A 中成员的角色 A 同步到 guildB
这些角色由 ID 定义
我遇到的问题是var users1 = guild1.roles.fetch(args[2]).members; //guild1role
抛出
(node:54852) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetch' of undefined
at SyncRole.run (D:\git\purgebot\Commands\General\syncrole.js:49:37)
at Message.run (D:\git\purgebot\Events\message.js:49:13)
at Luna.<anonymous> (D:\git\purgebot\Luna.js:92:83)
at Luna.emit (events.js:314:20)
at MessageCreateAction.handle (D:\git\purgebot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (D:\git\purgebot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (D:\git\purgebot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (D:\git\purgebot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (D:\git\purgebot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (D:\git\purgebot\node_modules\ws\lib\event-target.js:132:16)
这里是同步角色部分的源代码(第 1 行 = 第 37 行)
const client = this.client;
if(message.member.guild.me.hasPermission('ADMINISTRATOR'))
var guild1 = client.guilds.fetch(args[0]); //guildid1
var guild2 = client.guilds.fetch(args[1]); //guildid1
var users1 = guild1.roles.fetch(args[2]).members; //guild1role
var users2 = guild2.roles.fetch(args[3]).members; //guild2role
users2.members.forEach(user =>
user.remove(args[3]).catch(console.error);
message.channel.send("removed role " + args[3] + " for " + user.id);
)
users1.members.forEach(user =>
guild2.members.forEach(user2 =>
if(user.id == user2.id)
user2.addRole(args[3]);
message.channel.send("added role " + args[3] + " for " + user.id);
)
)
message.channel.send("roles synced");
else
message.channel.send("https://i.imgur.com/6cpffM4.jpg");
【问题讨论】:
【参考方案1】:GuildManager.fetch()
返回一个Promise
,必须先解决它才能使用Guild
对象。 RoleManager.fetch()
也是如此
// using `Promise.prototype.then()`
client.guilds.fetch(args[0]).then((guildid1) =>
client.guilds.fetch(args[1]).then((guildid2) =>
let users1, users2;
guild1.roles.fetch(args[2]).then((role) => (users1 = role.members));
guild2.roles.fetch(args[3]).then((role) => (users2 = role.members));
// code...
);
);
// using `async/await`
// **make sure your function is `async`**
const guild1 = await client.guilds.fetch(args[0]);
const guild2 = await client.guilds.fetch(args[1]);
const users1 = (await guild1.roles.fetch(args[2])).members;
const users2 = (await guild2.roles.fetch(args[3])).members;
【讨论】:
以上是关于在 guild.roles 中获取未定义的主要内容,如果未能解决你的问题,请参考以下文章