Why isn't my code working? Discord.js index.js client.on - discord.js

It's not sending a message, there are no errors I tried modifying the code nothing is working the bot welcome message still works I think that it's not updating with replit.
I tried modifying the code switching some stuff around basically doing stuff if I see any flaws I made.
client.on('message', message => {
// We'll want to check if the message is a command, and if it is, we'll want to handle it
if (!message.content.startsWith(prefix) || message.author.bot) return;
// Split the message into an array of arguments, with the command being the first element
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
// Check if the command is "privatevc"
if (command === 'Privatevc') {
// Check if the member is in a voice channel
if (!message.member.voice.channel) {
// If the member is not in a voice channel, send a message letting them know they need to be in one to use the command
return message.channel.send('You need to be in a voice channel to use this command.');
}
// If the member is in a voice channel, create a private voice channel for them
message.member.voice.createChannel({type: 'Voice'}).then(channel => {
// Send a message to the member letting them know the private voice channel has been created
message.channel.send(`Private voice channel created for you: ${channel}`);
}).catch(console.error); // If there was an error creating the private voice channel, log it to the console
}
});

This code is for Discord.js v12. If using the newest (v14) you need to use the messageCreate event instead of message. So the code would be:
client.on('messageCreate', message => {
You might also enable the MessageContent and GuildMessages intents.
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent
To make it all work you need to enable at least the third option, as you might see in the screenshot.

Related

Redirect to a channel as well as ping a role then post a message using args

I'm making an announcement command for my bot and want it to go to the announcements channel automatically, then ping the first role mentioned and finally display the message.
For now I have it going to staff commands as a placeholder to get it working, this does not work or throw an error. It properly pings the role, but nothing after that shows up, even the "Debug". What am I missing. I've seen the channel part work but it doesn't for me, and I can't find a similar situation online for the message itself.
module.exports.run = async (client, message, args) => {
if (message.author.bot) return;
let prefix = config.prefix;
if(!message.content.startsWith(prefix)) return;
const channel = message.guild.channels.cache.find(c => c.name === '🚔|staff-cmds');
let pingRole = message.mentions.roles.first();
let messageContent = args.slice(1).join(' ');
channel.send(pingRole, messageContent, "Debug");
This is what happens when the command is run
Try this channel.send(`${pingRole} ${messageContent}`)
The channel.send() function takes only two parameter "content" and "options" you can read more about it here

How to not send bots message edit discord.js

I have a message edit log but I want to stop sending the log if a mobs message was updated, I tried a few codes like
if(bot.oldMessage.content.edit()){
return;
}
It showed and error
cannot read property 'edit' of undefined
I then removed edit then content was undefined. The code for the message update is below.
The Code
module.exports = async (bot, oldMessage, newMessage) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[oldMessage.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
if (oldMessage.content === newMessage.content){
return;
}
let mEmbed = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL({dynamic: true}))
.setColor(cyan)
.setDescription(`**Message Editied in <#${oldMessage.channel.id}>**`)
.addField(`Before`, `${oldMessage.content}`)
.addField(`After`, `${newMessage.content}`)
.setFooter(`UserID: ${oldMessage.author.id}`)
.setTimestamp()
msgChannel.send(mEmbed)
}
How would I stop it from sending the embed if a bots message was updated.
Making a really simple check will resolve this issue. In Discord.js there is a user field that tells you if the user is a bot or not.
In fact, it is really recommended you add this in the "onMessage" part of your code as it stops other bots from using your bot, this is to make sure things are safe and no loopbacks/feedbacks happen, either way, you don't want a malicious bot taking advantage of your bot, which can get your bot in trouble too.
Here is what you want to do;
if (message.author.bot) return;
What this code specifically does is check if the message's author is a bot, if it returns true, it will break the code from running, if it returns a false, the code continues running.
You can do the same if you want to listen to bots ONLY by simply adding a exclamation mark before the message.author.bot like this;
if (!message.author.bot) return;
It is also possible to see what other kinds of information something holds, you can print anything to your console. For example, if you want to view what a message object contains, you can print it into your console with;
console.log(message) // This will show everything within that object.
console.log(message.author) // This will show everything within the author object (like ID's, name, discriminators, avatars, etc.)
Go ahead and explore what you can do!
Happy developing! ^ -^
That is really easy to do. All you need to do is check if the author of the message ist a bot and then return if true. You do that like this
if (oldMessage.author.bot) return;

How to make my discord bot only work in a chat?

I am using discord.js to implement a bot in the discord. When I use a command in any channel in my server, my bot responds to it, but I would like that my bot only worked if someone was sending the commands inside a private chat with the bot, how do I do that?
If you only want it to work between DMs, do
if (!message.channel.type == `dm`) return;
//other commands
You can check if the message was sent in a certain channel by checking the Message.channel.id property.
client.on("message", message => {
if (message.channel.id !== "ChannelID") return false;
// Execute your commands here
});

Discord js TypeError: Cannot read property members

Hello i have this code,
user = message.guild.members.fetch(id2).then((use,err)
And i have this error
TypeError: Cannot read property 'members' of null
Please can yuo help me ?
Thank you
message.guild is not initialized. You could check if it is null before use eg
if(message.guild){
user = message.guild.members.fetch(id2).then((use,err) ...
}else{
//do something when it is not initialized
}
Your error occurs because the message object refers to a message that was received as a DM. Because of how DMs work, there is no guild or member property for such message (they are left as nulls).
To avoid that, you should handle direct messages slightly differently. The easiest and most commonly used way is to completely stop direct messages from running your message event code. This can be done by adding
if (message.channel.type === 'dm') return;
at the very top of your event.
As that makes it impossible to initiate commands in DMs, even if they don't need to be executed in a guild to work (like ping command for example), this might be not what you want. In such case, you should implement a way to determine if command someone tried to run in DM is "allowed" to be executed there. Implementations for that vary depending on command handling implementation, but snippet below is basic princinple.
client.on('message', message => {
if (message.author.bot || !message.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/ /g);
const command = args.shift().toLowerCase();
if (command === 'memberinfo') {
if (message.channel.type === 'dm') return message.reply('this command cannot be run in DMs.');
// Actual command code
}
});

how to send a message to every channel in every guild?

similar to this question however I want to be able to send it to every channel it has access to!
inside the on message event after I verify myself by ID and the issued command I was using this code:
const listedChannels = [];
msg.guild.channels.forEach(channel => {
//get all channels
client.channels.get(channel.id).send("you like bred? (message) ");
//send a message to every channel in this guild
});
however I get the error that .send is not a function...
I have been told to use .send after getting the ID of the channels
If you are looping through all of the channels, you simpily need to send your content to the channel, which you've already gotten from msg.guild.channels.forEach(channel => {//code}).
Replace what you have inside the .forEach block with;
channel.send("You like bred? (message)");
Although this will send You like bred? (message)
If you're trying to get a response back, perhaps look at this answer that explains collecting responses via reactions to a discord message.
The following explanation pertains only to v11 (stable).
Client.channels is a Collection of Channels your bot is watching. You can only send messages to text channels, and this Collection will include DM channels as well. For this reason, we can use Collection.filter() to retrieve a new Collection of only text channels within a guild. Finally, you can iterate over the channels and call TextChannel.send() on each. Because you're dealing with Promises, I'd recommend a Promise.all()/Collection.map() combination (see hyperlinked documentation).
For example...
// assuming "client" is your Discord Bot
const channels = client.channels.filter(c => c.guild && c.type === 'text');
Promise.all(channels.map(c => c.send('Hello, world!')))
.then(msgs => console.log(`${msgs.length} successfully sent.`))
.catch(console.error);
You can use client.channels for this. Check if channel type is guild text channel and then try send a message.
client.channels.forEach(channel => {
if(channel.type === 'text') channel.send('MSG').catch(console.error)
})

Resources