javascript - Discord.js 获取用户 DM 和日志消息
问题描述
我希望我的机器人记录来自特定 ID 的消息,或者如果无法记录所有 DM 消息并发送到不和谐的服务器通道。如果特定 ID 发送“Hello!”,机器人将发送“Hello!” 到指定的频道 ID。
解决方案
如果您启用了所有必需的意图,您可以简单地侦听messageCreate
(message
对于 DiscordJS v12 和更早版本)并检查您的消息来自的频道类型。例如:
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 的消息记录到您想要的任何公会的某个频道的非常简单的示例。您还应该检查日志通道和公会是否存在以防止错误。还要确保机器人可以将消息发送到目标通道。
推荐阅读
- c# - 如何处理 StackOverflowException
- angular - 电子通知
- php - 如何在 Laravel 中一键更新 MySql 数据库值
- groovy - “即时”创建一个新课程?
- java - react-native-fbsdk错误编译失败找不到common.jar(android.arch.core:common:1.0.0)
- html - 在 Quiz Angular 5 中处理多个单选按钮
- mysql - 从另一个表中的多行更新 MYSQL 表
- python - 通过将 sklearn.predict 传递给 df.apply 对 Pandas 数据帧进行逐行预测
- javascript - 即使在 componentDidMount 之后也无法在未安装的组件上调用 setState
- c# - 在 SQL Server 中,Id Identity 列值有时会突然跳到 1000、10000 等