我建议使用对象或Map 来存储要向其发送就绪消息的公会 ID 和要发送的消息之间的键值对。例如:
const readyMessages = {
'1901864734235': 'I am online',
'6714589374095': 'Hello it is I, I am here, here I am'
'3876429867467': 'What is up',
};
然后,您可以使用Object.entries()(或Map#forEach(),如果使用地图,这会更容易,但为了简单起见,我将使用对象)遍历这些对。 Object.entries() 将返回一个数组数组,每个内部数组包含两个值。关键和价值。示例:
// in this example, you're associating
// each name with an age
const ages = {
john: 23,
mary: 16,
jack: 24,
};
// this logs an array of arrays, each array representing
// a property of this object
// the structure is [key, value] (in this case: [name, age]);
// all together, it looks like:
// [[name, age], [name, age], [name, age], [name, age]]
console.log(Object.entries(ages));
现在您的对象是一个数组,您可以使用非常方便的Array#forEach() 来遍历每个元素。我将通过继续我们之前的示例向您展示这是如何工作的:
// in this example, you're associating
// each name with an age
const ages = {
john: 23,
mary: 16,
jack: 24,
};
const entries = Object.entries(ages);
// use array destructuring to get the
// name and age
entries.forEach(([name, age]) => {
console.log(`${name} is ${age} years old`);
});
// alternatively, without using array destructuring,
// you could do this for the same result:
// entries.forEach((data) => {
// console.log(`${data[0]} is ${data[1]} years old`);
// });
在您的情况下,解构时的两个参数将是guildID 和message。如果您有公会ID,您可以使用GuildManager#cache#get() 简单地获取公会。
const guild = client.guilds.cache.get(guildID);
然后,您可以让频道将其发送到guild。最后,使用message 参数:
channel.send(message);
然后,你就可以得到guild的频道发送了
这有点模糊。如果他们都共享相同的名称,例如ready-messages,那么获取频道将很容易,这样您就可以为每个公会使用相同的代码。但是,如果每个公会都有一个您要发送到的特定频道 ID,该怎么办?
(如果可以的话,我真的建议对以下所有内容使用 Map,但我会继续使用对象以防万一)
这只是意味着您必须在每个属性中放入更多数据!而不是使用格式:
{
'guildID': 'message'
}
您可以将值 设为另一个 对象。通过这种方式,您可以存储与每个公会的就绪消息相关的任何数量的数据。新结构将如下所示:
{
'guildID': {
'channelID': '324728974398234',
'message': 'I am alive',
}
}
现在,两个解构参数不是server 和message,而是server 和data。然后您可以使用data.channelID 和data.message 来满足各自的需求。
const guild = /* ... */
const channel = guild.channels.cache.get(data.channelID);
channel.send(data.message);