不和谐.js获取用户DM和日志消息



我希望我的bot记录来自特定ID的消息,或者如果不可能记录所有DM消息并发送到不和谐服务器频道。如果特定ID发送"Hello!",机器人就会发送"Hello!"'到指定的通道id。

如果您启用了所有必需的意图,您可以简单地监听messageCreate(DiscordJS v12和更早版本的message)并检查消息来自的通道类型。例如:

const { Client, Intents } = require('discord.js');
// Initializing your client
const client = new Client({
intents: [
// Intent for catching direct messages
Intents.DIRECT_MESSAGES,
// Intents for interacting with guilds
Intents.GUILDS,
Intents.GUILD_MESSAGES
]
});
// Subscribe to the messages creation event
client.on('messageCreate', async (message) => {
// Here you check for channel type
// We only need direct messages here, so skip other messages
if (message.channel.type !== 'DM')
return;

// Now we need guild where we need to log these messages
// Note: It's better for you to fetch this guild once and store somewhere
// and do not fetch it on every new received message
const targetGuild = await client.guilds.fetch('YOUR GUILD ID');
// Here you getting the channel from the list of the guild channels
const targetLoggingChannel = await targetGuild.channels.fetch('LOGGING CHANNEL ID');

// Sending content of the message to the target channel
// You can also cover the message into embed with some additional
// information about sender or time this message was sent
await targetLoggingChannel.send(message.content);
});
// Authorizing
client.login('TOKEN HERE');

这是一个非常简单的例子,如何从bot的dm记录消息到任何你想要的公会的某个频道。您还应该检查日志通道和公会是否存在,以防止出现错误。还要确保bot可以向目标通道发送消息。