javascript - Discord 机器人不回复消息
问题描述
我一直在尝试设置一个不和谐的机器人,通过遵循文档,我能够设置一个斜杠命令,但无法让机器人回复服务器上的消息。
这是我用来从docs设置斜杠命令的代码。
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
在此之后,我使用以下代码设置了机器人:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('interactionCreate', async interaction => {
// console.log(interaction)
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
// await interaction.reply(client.user + '');
}
});
client.login('BOT_TOKEN');
现在我可以得到 Pong 的响应了!当我说 /ping 时。
但是在我从这个链接添加以下代码后,我没有得到机器人的任何响应。
client.on('message', msg => {
if (msg.isMentioned(client.user)) {
msg.reply('pong');
}
});
我希望机器人回复消息而不仅仅是斜线命令。有人可以帮忙吗。谢谢!!
解决方案
首先,您缺少接收事件的GUILD_MESSAGES
意图。messageCreate
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
其次,该message
事件已被弃用,请messageCreate
改用。
client.on("messageCreate", (message) => {
if (message.mentions.has(client.user)) {
message.reply("Pong!");
}
});
最后,Message.isMentioned()
是 no logner 一个函数,它来自 discord.js v11。用于MessageMentions.has()
检查消息中是否提及用户。
使用 discord.js 测试^13.0.1
。
推荐阅读
- sql - 为什么 PostgreSQL 不使用无符号整数作为 ID?那不会提供两倍的可能记录吗?
- ruby-on-rails - 如何在 ActiveAdmin 的仪表板中使用参数?
- neo4j - 设置关系属性时奇怪的 Neo4J Cypher 行为
- visual-studio-code - 上下移动时停止线移动(Visual Studio Code)
- delphi - 快速更新数组更少的行
- sml - 如何在两个整数范围内进行嵌套 for 循环?
- npm - vscode中的npm版本与安装版本不同
- r - 从 for 循环返回了一个额外的打印结果“[1] 36”:如何删除它?
- javascript - javascript在同一页面上多次
- apache-kafka - Logstash & Kafka - java.io.EOFException: null。节点 -1 断开连接