My discord bot won't respond to my command - javascript

So I'm pretty new to javascript, trying to get a bot to work. I get no errors, but when I try to use the bot in the server it is added in, it won't respond. I tried putting a console input in between the client.on and the if statement to see if I got input into my console, but no luck.
This tells me the issue is there, but after hours of editing and searching the web I didn't find anything. Thanks for the help!
const Discord = require("discord.js")
const fetch = require("node-fetch")
const client = new Discord.Client({ intents: [8] })
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", Message => {
if (msg.content === "Test") msg.reply("Success")
})
client.login(process.env['TOKEN'])

See this Image
Where did you define "msg". You have taken the argument as Message and then you are trying to use "msg" to get the content of it. You can replace "Message" to be msg then It may work
#2)
If this isn't working, you can check if you have other instances of the BOT running. This happened to me also!

The reason your bot is not responding to your messages is first of all, likely caused by incorrect intents provided.
The intents [8] resolves to a single intent (GUILD_EMOJIS_AND_STICKERS), which is why the message event is not executing. Do not confuse intents with permissions. You need to subscribe to the right intents:
const client = new Discord.Client({
intents: [
"GUILD_MESSAGES"
]
});
Secondly, your message listener takes a Message parameter, but the body of it is using a msg variable. Ensure you use the correct variables in your code:
// "message" is deprecated, "messageCreate" is preferred
client.on("messageCreate", (msg) => {
if (msg.content === "Test") {
msg.reply("Success");
}
})

Already found the issue, Discord.js v13 does NOT support content anymore. This was supported up to V12.

Related

How can I make bot receive DM on Discord js v14? [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed 4 months ago.
module.exports = {
name: 'messageCreate',
execute(message) {
if (message.channel.type == 'DM') {
console.log('Dm recieved')
client.channels.get('1026279100626767924').send(message);
}
}
};
I created event handling by referring to the Discord JS guide. I want my bot to receive a DM and send that message to my admin channel.
But the bot is not recognizing the DM
What should I do
(I'm using a translator)
You can use messageCreate event for listening your bot's DMs.
client.on("messageCreate", async message => {
if (message.guild) return;
console.log(`Someone sent DM to me => ${message.content}`);
await client.channels.cache.get(CHANNEL_ID).send(messsage.content);
});
You need to include partials Channel and Messages configurations on creating client:
const client = new Client({
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent
],
partials: [
Partials.Channel,
Partials.Message
]
})
That solved it for me!
There could be a couple problems with this.
First off, it could be your Intents.
Intents allow your bot to process certain events.
The intents that you will want are:
DirectMessages
MessageContent (this one may not be required, I am unsure).
So, go to where you initialize your client. It should look something like this:
const Discord = require("discord.js");
const client = new Discord.Client();
and change it into this:
const Discord = require("discord.js");
const { GatewayIntentBits, Client } = Discord;
const client = new Client({
intents: [
GatewayIntentBits.DirectMessages
GatewayIntentBits.MessageContent
]
});
The second issue could be that your message handler isn't detecting it properly.
Like the other answer says, you should just determine if there is no Guild attached to the message.
client.on("messageCreate", async(message) => {
if(!message.guild) {
client.channels.cache.get("YOUR_ID").send(message);
}
});
There could be other issues, but those two are the most probable. Considering you're not getting any errors, I'd presume it's the first one, the issue with Intents.
Hope this helps!

How do I logout my Discordbot in JS savely with a command

I built a basic Discord bot which I want to go offline when I type the corresponding command on the Discord server "!logout". I searched for answers, but those who used discord.js weren't responsed...
If I use client.logout() it throws an error and crashs with
TypeError: client.logout is not a function
and it won't even call my error function.
Maybe the answer is simple but I can't find it anywhere.
Here's my basic code:
require('dotenv').config()
const Discord = require('discord.js')
const client = new Discord.Client({
intents: ["GUILDS", "GUILD_MESSAGES"],
})
client.on('ready', () => {
console.log('Bot is ready');
});
client.on("messageCreate", msg => {
if (msg.content === '!logout'){
client.logout(() => {
msg.reply('couldn^t go offline')
})
}
})
client.login(process.env.BOT_TOKEN)
Thank you! :)
Try using the function <Client>#destroy()
If you want to exit Node.js, you can then use process.exit(0)
Documentation
process.exit(0)
From the docs:
process.exit([exitcode])
Ends the process with the specified code. If
omitted, exit uses the 'success' code 0.
To exit with a 'failure' code:
process.exit(1); The shell that executed node should see the exit code
as 1.

discord.js - guildMemberRemove doesn't work, guildMemberAdd works perfectly fine

Sorry if this is poorly formatted, I've never written a question on here before.
First of all, this is my first time writing anything in JavaScript, so this might be some dumb mistake I'm making that's causing my problem.
What I want to do is send a message when a member joins the server, and send a different message when a member leaves. When someone joins the server, the join message is sent and everything works perfectly fine, but when a member leaves, absolutely nothing happens. I put in some console.logs in the joinMessage and leaveMessage functions, and I get an output for joinMessage but nothing for remove. I have enabled Presence Intent and Server Members Intent on the Discord developer portal.
The join and leave message functions are down at the bottom, but I went ahead and added the entire thing so people could help me better. The bot token and channel IDs have been removed, and they are correct in my version of the code.
console.log('Starting');
const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const commandHandler = require("./commands");
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
client.login('token');
var server = client.guilds.cache.get('server');
client.on('ready', ready);
function ready()
{
console.log('Authenticated');
server = client.guilds.cache.get('server');
}
client.on('messageCreate', receivedMessage);
function receivedMessage(msg)
{
commandHandler(msg);
}
client.on('guildMemberAdd', joinMessage);
function joinMessage(member)
{
let channelWelcome = server.channels.cache.get('welcome');
let channelIntro = server.channels.cache.get('intro');
channelWelcome.send(`Welcome to the server, ${member}! Head over to ${channelIntro} and introduce yourself!`);
}
client.on('guildMemberRemove', leaveMessage);
function leaveMessage(member)
{
let channelWelcome = server.channels.cache.get('welcome');
channelWelcome.send(`${member} has left the server.`);
}
I've been trying to figure this out for about an hour, so I'd really appreciate it if someone could help me solve this. Thanks!
You need to include following intent: GUILD_PRESENCES
So your code needs to look like this:
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] });
Now your bot will detect if a member leaves the guild.
Try calling the function directly in the event parameters. There might be some sort of confliction when extracting the function
client.on("guildMemberAdd", (member) => {
let channelWelcome = server.channels.cache.get('welcome');
let channelIntro = server.channels.cache.get('intro');
channelWelcome.send(`Welcome to the server, ${member}! Head over to ${channelIntro} and introduce yourself!`);
}
client.on("guildMemberRemove", (member) => {
let channelWelcome = server.channels.cache.get('welcome');
channelWelcome.send(`${member} has left the server.`);
}
Also make sure you have set the right intents (if you are running V13), and gave the bot the correct privileged intents in the developer portal
This question/answer is rather old, but I found that the selected answer here is not fully correct, at least in the current version.
You do not in fact need the Presences Intent to receive guildMemberRemove event. The event is actually not firing in cases when the member data is not cached and will therefore not emit the event.
In order to resolve this, you will need to enable Partials on the client, specifically Partials.GuildMember. This will enable the event to emit on un-cached data.

Event messageCreate not firing/emitting when I send a DM to my bot (discord.js v13)

I made this code for logging the DMs that are sent to my bot:
client.on('messageCreate', async message => {
if (message.author.bot) return;
const attachment = message.attachments.first()
if (message.channel.type === 'DM') {
console.log(message.content)
const dmLogEmbed = new MessageEmbed()
.setColor("RANDOM")
.setTitle(`${message.author.tag} dmed the bot and said: `)
.setDescription(message.content)
.setFooter(`User's id: ${message.author.id}`)
if (message.attachments.size !== 0) {
dmLogEmbed.setImage(attachment.url)
}
client.channels.fetch("852220016249798756").then((channel) => {
channel.send({ embeds: [dmLogEmbed] })
})
}
});
But when updating to discord.js v13 it didn't work anymore, for what I understood the only change is that the 'dm' channel type isn't 'dm' anymore but 'DM', so I changed it in my code, but it is still not working and I don't really know why.
Make sure you have DIRECT_MESSAGES in your client's intents.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"] });
There is a breaking change in the Discord API v8. For reference see here.
On Discord API v8 and later, DM Channels do not emit the CHANNEL_CREATE event, which means discord.js is unable to cache them automatically. In order for your bot to receive DMs, the CHANNEL partial must be enabled.
So we need to enable the partial CHANNEL as well. Keep in mind that when dealing with partial data, you often want to fetch the data, because it is not complete. However this doesn't seem to be your case, if you are using the messageCreate event. The message received is not partial nor message.channel. To check if something is partial, you can use the .partial property. For example Message.partial or Channel.partial.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] });
Now it should work as good old discord.js v12.

How do I make my command not mention the user?

I just started coding my Discord bot and I made a command that replies to every message that isn’t sent by a bot. When I tried it in DMs it works fine, but when I tried it in my server it would mention the user before the command. In the DM it would say just “test”, but in the server it would say something like “#ExampleUser, test”.
Is there a way I can fix this? Here’s my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
if (message.author.bot) return;
return message.reply("test")
});
Instead of message.reply('test') use message.channel.send('test') that sends a message to the channel the original message was sent to.
Solution
use message.channel.send('string'); instead of .reply()
It's very easy :)
Instead of saying message.reply('message') you just have to say message.channel.send('message')

Categories