我正在尝试创建一个Discord机器人,该机器人可以使用
来响应#feedback
中发送的所有消息
“感谢您的反馈,USERNAME!它已发送给管理员。'
到目前为止,这是我的代码:
const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');
client.on('ready',() => {
console.log('FBB Online!');
});
client.on('message', msg => {
if (msg.channel != '#feedback') return;
if (msg.author === client.user) return;
client.channels.get('488795234705080320').send('Thanks for your feedback, '+msg.sender+'! It has been sent to the admins.');
});
client.login(settings.token);
但是,在测试漫游器时,它不会响应任何通道中的消息。为什么会这样,我该如何解决?
答案 0 :(得分:0)
我注意到您对消息使用了错误的语法。此代码应该可以工作:
if(message.author.equals(client.user)) return;
if(message.channel.name.equals("feedback")){
message.channel.send(`Thank you for your feedback ${message.author.username}! It has been sent to the admins.`);
// two `s allows you to add an object in a string. To add the object, put it inside this -> ${}
}
让我知道这是否有帮助。
编辑:自从我第一次将其写入到仅适用于一台服务器的位置以来,我就对其进行了修复以搜索通道的名称,因为那正是我的目的。
答案 1 :(得分:0)
您正在使其变得不必要的复杂。
要在同一频道中回复用户,只需使用:
message.channel.send(`hi ${message.author}`);
一些提示
通过使用`${variable}`
,您可以轻松地将变量放入字符串中。
有关here的更多信息。
要检查用户是否是机器人,我建议使用if (msg.author.bot) return;
而不是if (msg.author === client.user) return;
( msg.author.bot 是布尔属性)
This帖子也可能会对您有所帮助。
总的来说,我会这样更改您的代码。
client.on('message', msg => {
if (msg.author.bot) return;
if(msg.channel.id === "488795234705080320") //This would be the channelID of '#feedback'.
{
msg.channel.send(`Thanks for your feedback, '${msg.author}'! It has been sent to the admins.`);
}
});
如果您不知道 #feedback 的channelID,那么this发布可能会有所帮助。
希望对您有帮助!
答案 2 :(得分:0)
为了识别通道,我们可以使用 message.channel.name
或使用 find 函数。使用 message.channel.name
,我们可以查看或检查频道名称。我们可以用一个 find 函数来做同样的事情,为整个客户端或仅在公会中寻找频道,就像这样:
let chan = message.guild.channels.cache.find(channel => channel.name === "feedback")
(要搜索存在机器人的所有服务器,只需使用客户端而不是消息或 msg)
完整代码,适合您的代码,在 Discord.js v.12 中使用“msg”而不是“message”:
const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');
client.on('ready',() => {
console.log('FBB Online!');
});
client.on('message', msg => {
if (msg.channel.name != "feedback") return;
if (msg.author === client.user) return;
let chan = client.channels.cache.find(ch => ch.id == "488795234705080320")
chan.send(`Thanks for your feedback, ${msg.author}! It has been sent to the admins.`);
});
client.login(settings.token);
代码很好,但我们可以改进它,连接if:
const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');
client.on('ready',() => {
console.log('FBB Online!');
});
client.on('message', msg => {
if (msg.channel.name != "feedback" || msg.author === client.user) return;
let chan = client.channels.cache.find(ch => ch.id == "488795234705080320");
chan.send(`Thanks for your feedback, ${msg.author}! It has been sent to the admins.`);
});
client.login(settings.token);