首页 > 解决方案 > 使用 Discord.js 向频道发送消息时遇到问题

问题描述

我正在尝试制作一个机器人,一旦用户发送特定消息,就会向频道发送消息。一旦机器人登录,我已经设法让它发送一条消息,但该client.on()功能不会做任何事情。如果我做错了什么,请告诉我,提前谢谢!

const { Client, Intents } = require("discord.js");

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.login("<bot token>");

client.once("ready", () => {
console.log("Ready!");

channel.send("hello world"); //This works

const guild = client.guilds.cache.get("<server id>");
const channel = guild.channels.cache.get("<channel id>");

//This is the issue. Nothing happens when I send "!ping" in the server
client.on("message", message => {
    if (message.content === "!ping") {
        channel.send("pong");
    }
});
});

标签: javascriptdiscorddiscord.jsbots

解决方案


您需要启用GUILD_MESSAGES意图:

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});

这将使您能够接收MESSAGE_CREATE在公会中发送的消息的事件。

完整的意图列表可以在 Discord 开发者文档中找到。

此外,如果您使用的是 Discord.js v13,则该message事件已被弃用,因为它已重命名为messageCreate.


推荐阅读