discord.js Running a command sends a duplicate text - javascript

Here is my code, whenever I run the $dm command it runs it but also runs the $help command.
I know its probably a newbie question but if someone could help me out it will be appreciated
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
const { MessageEmbed } = require('discord.js');
client.once('ready', () => { client.user.setActivity('Use $help for a list of commands!', { type: "PLAYING" }); });
console.log('Ready!');
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (message.content.startsWith(`${prefix}ping`)) {
message.channel.send('Pong.');
} else if (message.content.startsWith(`${prefix}beep`)) {
message.channel.send('Boop.');
} else if (message.content === `${prefix}server`) {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
} else if (message.content === `${prefix}user-info`) {
message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
console.log(message.content);
} else if (message.content === (`${prefix}dm`)) {
message.author.send("string");
} else if (message.content === "$help") {}
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
}
,
)
client.login(token)

else if (message.content === "$help") {} <- The issue
You're closing the curly braces too early and so the execution of your code below isn't actually dependant on the if statement.
It should look like this
else if (message.content === "$help") {
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
}

You must place this code:
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("$help, $ping, $beep, $server, $user-info, $dm")
.setColor("RANDOM")
message.channel.send(embed)
within these curly braces:
} else if (message.content === "$help") {}
Tip: Use switch statements instead

Related

Declaration Or Statment expected Javascript/Discord.js

So Im coding in javascript a discord bot and then what happens is i get an Declaration Or Statment expected error even if its not needed
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
});
client.login("not showing token ");```
You have a wrong synatax. Your code should be
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
};
});
client.login("not showing token ");

TypeError: command.execute is not a function. (After typing !rps on discord channel)

When I try to use !rps, discord shows me that there is no command and I get somethink like that in the console
I don`t know do I need to change something in my index.js code or in my rps.js code
https://imgur.com/sGjGR4t
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
client.command = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.command.set(command.name, command);
}
}
const prefix = '!';
client.once('ready', () => {
console.log('Bot jest online');
client.user.setActivity('Minecraft')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.command.has(commandName)) return;
const command = client.command.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Nie ma takiej komendy!')
}
});
client.login("TOKEN");
And the rps.js code, I tried to move rps.js to other folder but it does not solve the problem
const Discord = require('discord.js')
module.exports = {
name: "rps",
description: "rock paper scissors command",
usage: "!rps",
async run(bot, message, args) {
let embed = new Discord.MessageEmbed()
.setTitle("RPS")
.setDescription("React to play!")
.setTimestamp()
let msg = await message.channel.send(embed)
await msg.react("🗻")
await msg.react("✂")
await msg.react("📝")
const filter = (reaction, user) => {
return ['🗻', '✂', '📝'].includes(reaction.emoji.name) && user.id === message.author.id;
}
const chices = ['🗻', '✂', '📝']
const me = choices[Math.floor(Math.random() * choices.lenght)]
msg.awaitReactions(filter, { max: 1, time: 60000, error: ["time"] }).then(async (collected) => {
const reaction = collected.first()
let result = new Discord.MessageEmbed()
.setTitle("Result")
.addFields("Your Choice", `${reaction.emoji.name}`)
.addField("Bots choice", `${me}`)
await msg.edit(result)
if ((me === "🗻" && reaction.emoji.name === "✂") ||
(me === "✂" && reaction.emoji.name === "📝") ||
(me === "📝" && reaction.emoji.name === "🗻")) {
message.reply('You lost!');
} else if (me === react.emoji.name) {
return message.reply(`It's a tie!`);
} else {
return message.reply('You won!');
}
})
.catch(collected => {
message.reply('Process has been canceled, you failed to respond in time!');
})
}
}
In your rps.js file, you are defining the function to be run as run but in your index.js file, you are using the execute function so you can either change how you run the command in your main file or you can change the function name in your command file. Another place where you could get an error is the arguments you pass. In your main file, you are passing two arguments to your command file, message and args while in your command file, you are expecting three, bot, message and args. So you can either change the order of the arguments you pass or you can just remove the bot parameter in the command file:

How do i fix the error ReferenceError: prefix is not defined?

My code:
const Discord = require('discord.js')
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!')
})
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.content === '>ping') {
message.channel.send('Pong.');
} else if (message.content === '>beep') {
message.channel.send('Boop.');
} else if (message.content === '>serverinfo') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
} else if (message.content === '>userinfo') {
message.channel.send(`Your username: ${message.author.username}\nYour id: ${message.author.id}`);
}
});
client.login('lmao no');
my post is most likely code so this is so i can post it pls pls pls pls pls help i need this bot finished in an hour
To be using prefix checking when message event is fired you need to defined it first.
example : const prefix = ".";
const Discord = require('discord.js')
const config = require('./config.json');
const client = new Discord.Client();
const prefix = ".";
client.once('ready', () => {
console.log('Ready!')
})
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.content === '>ping') {
message.channel.send('Pong.');
} else if (message.content === '>beep') {
message.channel.send('Boop.');
} else if (message.content === '>serverinfo') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
} else if (message.content === '>userinfo') {
message.channel.send(`Your username: ${message.author.username}\nYour id: ${message.author.id}`);
}
});
client.login('lmao no');

Message not defined discord.js chatbot

So I'm trying to get my bot to work but the code says message not defined. I have tried everything I know to do:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
client.login('my-bot-token');
You forgot to add a event listener for a message, I think.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ready!');
});
client.on("message", (message) => {
if (message.content === '!ping') {
message.channel.send('Pong.');
}
if (command === "!hug") {
let user = message.mentions.users.first();
message.channel.send("You have been hugged " + user);
}
}
client.login('my-bot-token');

Discord.js/javascript issue with a error. ReferenceError: command not defined

const Discord = require("discord.js");
const bot = new Discord.Client();
let prefix="!"
bot.on("ready", () => {
bot.user.setStatus("idle");
console.log(`Demon Is Online`)
const update = () => {
bot.user.setActivity("!help | residing on " + bot.guilds.size + " Servers", { type: 'WATCHING' });
};
bot.on('ready', update);
bot.on('guildCreate', update);
bot.on('guildRemove', update);
bot.on("message", message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(!command.startsWith(prefix)) return;
});
if(command === `${prefix}userinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor("#3498db")
.setThumbnail( `${message.author.avatarURL}`)
.addField("Name", `${message.author.username}#${message.author.discriminator}`)
.addField("ID", message.author.id)
message.reply("I've Sent Your User Info Through DM!");
message.channel.send({embed});
}});
if("command" === `${prefix}help`) {
let embed = new Discord.RichEmbed()
.addField("!help", "gives you this current information")
.setTitle("Help")
.setColor("#3498db")
.addField("!userinfo", "gives you info about a user(currently being worked on)")
.addField("!serverinfo","gives you info about a server(currently working on it)")
.addField("link to support server","https://discord.gg/NZ2Zvjm")
.addField("invite link for bot","https://discordapp.com/api/oauth2/authorize?client_id=449983742224760853&permissions=84993&scope=bot")
message.reply("here's a list of commands that i'm able to do")
message.channel.send({embed});
messageArray = message.content.split("");
let command = messageArray[0];
if(command === `${prefix}serverinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor("#3498db")
.addField("Name", `${message.guild.name}`)
.addField("Owner", `${message.guild.owner.user}`)
.addField("Server ID" , message.guild.id)
.addField("User Count", `${message.guild.members.filter(m => m.presence.status !== 'offline').size} / ${message.guild.memberCount}`)
.addField("Roles", `${message.guild.roles.size}`);
message.channel.send({embed});
}
};
bot.login("token goes here")
I have this code that I need help with its stopping my discord bot from coming online. I use javascript and discord.js and node.js and could use help I tried searching youtube and also servers on discord and asking some friends but they all tell me to learn the language which I been trying. but anyways here's my error
output
command doesnt exist in the context that its being referenced.
you have
bot.on("message", message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(!command.startsWith(prefix)) return;
});
and then youre referencing command below here. which means it is out of scope, since it is defined int eh scope of bot.on('message' ...
paste the command snippet into the bot.on('message' code and, reset ur bot and try sending it a message, i think you'll see desired results.
full example will look like this:
bot.on('ready', update)
bot.on('guildCreate', update)
bot.on('guildRemove', update)
bot.on('message', message => {
if (message.author.bot) return
if (message.channel.type === 'dm') return
let messageArray = message.content.split(' ')
let command = messageArray[0]
let args = messageArray.slice(1)
if (!command.startsWith(prefix)) return
if (command === `${prefix}userinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor('#3498db')
.setThumbnail(`${message.author.avatarURL}`)
.addField(
'Name',
`${message.author.username}#${message.author.discriminator}`
)
.addField('ID', message.author.id)
message.reply("I've Sent Your User Info Through DM!")
message.channel.send({ embed })
}
if (`${prefix}help` === 'command') {
let embed = new Discord.RichEmbed()
.addField('!help', 'gives you this current information')
.setTitle('Help')
.setColor('#3498db')
.addField(
'!userinfo',
'gives you info about a user(currently being worked on)'
)
.addField(
'!serverinfo',
'gives you info about a server(currently working on it)'
)
.addField('link to support server', 'https://discord.gg/NZ2Zvjm')
.addField(
'invite link for bot',
'https://discordapp.com/api/oauth2/authorize?client_id=449983742224760853&permissions=84993&scope=bot'
)
message.reply("here's a list of commands that i'm able to do")
message.channel.send({ embed })
messageArray = message.content.split('')
let command = messageArray[0]
if (command === `${prefix}serverinfo`) {
let embed = new Discord.RichEmbed()
.setAuthor(message.author.username)
.setColor('#3498db')
.addField('Name', `${message.guild.name}`)
.addField('Owner', `${message.guild.owner.user}`)
.addField('Server ID', message.guild.id)
.addField(
'User Count',
`${
message.guild.members.filter(m => m.presence.status !== 'offline')
.size
} / ${message.guild.memberCount}`
)
.addField('Roles', `${message.guild.roles.size}`)
message.channel.send({ embed })
}
}
})
bot.login('token goes here')
Note i didnt fix ALL your issues, there seems to be a few more stragglers left, i just tried to answer your specific question :)

Categories

Resources