Discord.js 向数据库中存储的每个频道 ID 发送消息

时间:2021-04-06 15:11:04

标签: discord.js quick.db

我正在尝试创建一个命令,向使用 quick.db 存储的每个频道 ID 发送一条消息

db.set(`channelID_${message.guıld.ıd}`, message.channel.id)

所以这就是我存储频道 ID 的方式,是否有可能的方法向使用此存储的每个频道 ID 发送消息,我一直在尝试但失败了

编辑:我尝试使用

const channelIDs = db.all() 
  .filter(e => e.ID.startsWith("channeltest"));

channelIDs.forEach(async (id) => {
  try {
    
    const channel = await client.channels.fetch(id);
    channel.send('test');
  }
});

获取错误 channel_id:值“[object Object]”不是雪花。

2 个答案:

答案 0 :(得分:0)

首先,我认为您的代码中有一个小错误。您设置了一个键,但没有数据。这是我的更正:

db.set(`channelID_${message.guıld.ıd}`, message.channel.id)

我建议使用 Array.forEach() 循环遍历您的频道 ID 数据库条目:

array1.forEach(async databaseElement => {
const fetchedChannel = await client.channels.fetch('ENTER CHANNEL ID');
fetchedChannel.send('Test message. It worked!')
});

答案 1 :(得分:0)

您可能应该像 Worthy Alpaca 提到的那样设置一组频道 ID。

db.set(`channelID_${message.guild.id}`, ['859324671543153', '859320171505419'])

您可以稍后使用 push() 方法添加新 ID:

db.push(`channelID_${message.guild.id}`, message.channel.id)

设置好数据库后,您可以使用 .get() 方法获取 ID 数组,并使用 .forEach() 方法对其进行迭代。对于每个频道 ID,您可以使用 .fetch() 来获取频道。它返回一个promise,因此您需要先解决它(这就是await 关键字存在的原因)。获得频道后,您可以使用 channel.send() 方法向该频道发送消息:

// get the array of IDs from the database
const channelIDs = db.get(`channelID_${message.guild.id}`);

// for every ID stored, send a message
channelIDs.forEach(async (id) => {
  try {
    // fetch the channel by its ID
    const channel = await client.channels.fetch(id);
    channel.send('Minus officiis dolore eveniet');
  } catch (error) {
    console.log(error);
  }
});