简体   繁体   English

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

[英]Discord.js get user DM & log message

I want that my bot to log messages from a specific ID or if its not possible to log all DM messages and send to a discord server channel.我希望我的机器人记录来自特定 ID 的消息,或者如果无法记录所有 DM 消息并发送到不和谐服务器通道。 If specific ID sends 'Hello!', the bot will send 'Hello!'如果特定 ID 发送“你好!”,机器人将发送“你好!” to the specified channel id.到指定的频道 ID。

If you have all required intents enabled, you can simply listen for messageCreate ( message for DiscordJS v12 and older) and check for the channel type your message is coming from.如果您启用了所有必需的意图,您只需监听messageCreate (DiscordJS v12 及更早版本的message )并检查您的消息来自的频道类型。 For example:例如:

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');

This is very minimal example of how to log messages from the DMs of the bot to some channel on any guild you want.这是如何将来自机器人的 DM 的消息记录到您想要的任何公会的某个频道的最小示例。 You should also check for logging channel and guild existence to prevent errors.您还应该检查日志记录通道和公会的存在以防止错误。 Also make sure that bot can send messages to the target channel.还要确保机器人可以向目标频道发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM