我试图使一个机器人发送消息到一个频道一旦用户发送一个特定的消息。我已经设法使它发送消息一旦机器人登录,但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");
}
});
});
您需要启用GUILD_MESSAGES
意图:
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});
这将使您能够接收MESSAGE_CREATE
事件在公会发送的消息。
一个完整的意图列表可以在Discord开发者文档中找到。
此外,如果您使用的是Discord.js v13,则message
事件已被弃用,因为它已被重命名为messageCreate
。
您没有使用GUILD_MESSAGES
意图。试试这个:
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
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");
}
});
});