Reputation: 309
I'm trying to create a discord bot that will respond to all messages sent in #feedback
with
'Thanks for your feedback, USERNAME! It has been sent to the admins.'
This is my code so far:
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);
However, when testing the bot, It doesn't respond to messages in any channel. Why is this and how can I fix this?
Upvotes: 0
Views: 3833
Reputation: 64
To identify the channel, we can use message.channel.name
or use a find function. Using the message.channel.name
, we can see or check a channel name. We can do the same with a find function, looking for the channel for the entire client or just in the guild, like this:
let chan = message.guild.channels.cache.find(channel => channel.name === "feedback")
(to search all servers where the bot is present, just use client instead of message or msg)
Complete code, adapted to your code, which uses "msg" and not "message", in Discord.js v.12:
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);
The code is good, but we can improve it, connecting the if's:
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);
Upvotes: 0
Reputation: 82
I noticed you used the wrong syntax for the message. This bit of code should work:
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 -> ${}
}
Let me know if this helped.
EDIT: I fixed this up to search for the name of the channel since I first wrote this to where it would only work for one server since that's what mine was for.
Upvotes: 1