why aren't my discord bot commands working - javascript

im new to code and i'm just trying to make a discord bot but i made commands and i made it possible for my bot's status to say something but none of it works. it goes online and it doesn't tell me anything's wrong with my code but none of it works.
code:
const Discord = require("discord.js");
const bot = new Discord.Client();
let prefix=".";
bot.on("ready", () => {
bot.user.setStatus("idle")
console.log("lets gooo")
});
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("#5ED315")
.setThumbnail( `${message.author.avatarURL}`)
.addField("Name", `${message.author.username}#${message.author.discriminator}`)
.addField("ID", message.author.id)
message.reply("check dms");
message.channel.send({embed});
};
if("command" === `${prefix}help`) {
let embed = new Discord.RichEmbed()
.addField(".help", "gives you this current information")
.setTitle("help")
.setColor("#5ED315")
.addField(".user", "gives you info about a user(currently being worked on)")
.addField(".server","gives you info about a server(currently working on it)")
.addField("link to support server","https://discord.gg/cRJk74kDvj")
.addField("invite link for bot","https://discord.com/api/oauth2/authorize?client_id=771489748651868173&permissions=8&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("#5ED315")
.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("bot token");
why isn't anything working?? i really need help

26:
27: if(!message.startsWith(prefix)) return;
28:
29: });
^^^
There's your problem. You're closing the message handler too early, so it doesn't bother to touch the command code. (Well, it does, but not the way you want it to.)
You should move that closing }); to after your command definitons. (before the bot.login)

Related

TypeError: message.reactions.fetch is not a function

client.on('messageCreate', async(message) => {
if (message.author.bot)return
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(message.content.startsWith('!reroll')){
if(!message.member.permissions.has("ADMINISTRATOR")) return;
const content = args.join(' ');
let winner = message.reactions.fetch(content).cache.get("🎉").users.cache.filter((users) => !users.bot).random(winnerCount.toString().slice(0, -1));
const embed = new MessageEmbed()
.setDescription(`${winner}`);
message.channel.send({embeds: [embed]});
message.delete({timeout: 1500}).catch(err => console.log(err));
}
})
I tried to make a giveaway reroll command but I got this error.
TypeError: message.reactions.fetch is not a function
It's because there is no reactions.fetch() method. message.reactions returns a ReactionManager so you can use its cache like this:
let winner = message.reactions.cache
.get('🎉')
.users.cache.filter((user) => !user.bot)
.random(winnerCount.toString().slice(0, -1));
I'm not sure what you want to do with args.join(' ') though.
You can't access the reactions this way. Have a look here: https://maah.gitbooks.io/discord-bots/content/getting-started/awaiting-messages-and-reactions.html

Discord.js database using repl.it

I made a database script in repl.it and it's working but I keep getting null and then users database here is my code:
client.on("message", async (message) => {
if (message.content.toLowerCase().startsWith("#مخالفات")) {
var pfpMember = message.mentions.members.first() || message.member;
const violation = await db.get(`wallet_${message.mentions.members.first()}`);
if (violation === null) violation = "العضو ليس لديه اي مخالفات";
const pembed = new Discord.MessageEmbed()
.setTitle(`شرطة لوس سانتوس`)
.setDescription(`المخالفات المرورية :` + violation)
.setColor("RANDOM")
.setFooter("شرطة لوس سانتوس")
.setThumbnail(pfpMember.user.displayAvatarURL());
message.channel.send(pembed);
}
});
And here is a screenshot:
The issue is that you cannot reassign violation as it is a constant, not a variable.
Using the following should solve the issue:
client.on("message", async (message) => {
if (message.content.toLowerCase().startsWith("#مخالفات")) {
var pfpMember = message.mentions.members.first() || message.member;
let violation = await db.get(`wallet_${message.mentions.members.first()}`);
if (violation === null) violation = "العضو ليس لديه اي مخالفات";
const pembed = new Discord.MessageEmbed()
.setTitle(`شرطة لوس سانتوس`)
.setDescription(`المخالفات المرورية :` + violation)
.setColor("RANDOM")
.setFooter("شرطة لوس سانتوس")
.setThumbnail(pfpMember.user.displayAvatarURL());
message.channel.send(pembed);
}
});

The Discord.js command I wrote does not working

I have an error in these codes.
client.on("message", async message => {
if(message.author.bot || message.channel.type === 'dm') return;
let prefix = botsettings.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = message.content.substring(message.content.indexOf(' ')+1);
if(!message.content.startsWith(prefix)) return;
let commandfile = bot.commands.get(cmd.slice(prefix.lenght)) || bot.commands.get(bot.aliases.get(cmd.slice(prefix.lenght)))
if(commandfile) commandfile.run(bot,message,args)
if(cmd === `${prefix} reactions`){
let embed = new Discord.MessageEmbed()
.setTitle('Reaction Roles')
.setDescription('Kişiliğinize göre bir rol seçiniz.')
.setColor('GREEN')
let msgEmbed = await message.channel.send(embed).
msgEmbed.react(':closed_book:')
}
})
I am encountering this error. I couldn't find the botsettings part.
UnhandledPromiseRejectionWarning: ReferenceError: botsettings is not defined
This means that you didn't define the "botsettings" file anywhere.
Try adding
const botsettings = require ("<path to the file>")
to the top of your code.
If you're trying to make commands, try using this. I use it a lot in my bot (currently v11, too much of a hassle to update to v12. But the same code should work anyway.):
client.on("message", async (message) => {
if(message.author.bot) return;
const args = message.content.slice(botsettings.prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (message.content.indexOf(botsettings.prefix) !== 0) return;
if(command === "reactions"){
let embed = new Discord.MessageEmbed()
.setTitle('Reaction Roles')
.setDescription('Kişiliğinize göre bir rol seçiniz.')
.setColor('GREEN')
let msgEmbed = await message.channel.send(embed).
msgEmbed.react(':closed_book:')
}
});
Before doing this, make sure you have r const botsettings = ("./path/to/your/botsettings.json"); at the top of your entire code.

Discord.js how to make suggest command?

What can I do in Discord.js to make suggest command? My actual code doesn't work, i have 2 types of suggestions: support server and bot.
Here's my code:
if (command === "suggest"){
const type = args.join(" ")
const thing = args.join(" ").slice(6)
const thing2 = args.join(" ").slice(3)
const suggestion = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing}`)
const suggestion2 = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing2}`)
if (!typ){
message.reply("enter suggestion type, which you want to suggest!");
return;
}
if (type === "server"){
if (!thing){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("channel_id").send(suggestion);
return;
}
if (type === "bot"){
if (!suggestion2){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("another_channel_id").send(suggestion2);
return;
}
else if (type !== "bot" || type !== "server"){
message.reply("invalid suggestion type!");
return;
}
}
and it outputs "invalid suggestion type!" when I type !suggestion
I'm not an expert with discord.js but this should work! (It does on my server!)
client.on('message', msg => { //This runs when a message is sent.
const args = msg.content.slice(prefix.length).split(' '); //Get the arguments
const command = args.shift().toLowerCase(); //Making the command non case-sensitive
if (command === 'suggest'){ //if command is suggest
const channel = msg.guild.channels.find(ch => ch.name === 'suggestions'); //finds the channel named suggestions
channel.send('Suggestion:\n ' + args.join(' ')) //Sends the arguments
} //Closes the if (command === 'suggest'){
}); //Closes the client.on('message',msg => {
Great if i can help!
Also you used !== so if user is not a bot it doesn't send message. Try using === instead!
I dont know if you use a command handler or not but if you do, this should work:
if (command === 'suggest'){
const Discord = require('discord.js'); // this should be on top of ur js file, NOT HERE
const { Client, MessageEmbed } = require('discord.js'); // this should be on top of ur js file, NOT HERE
if(!args[0]) return message.reply('You need to type a suggestion..') // bot reply if user only typed !suggest n didnt include any text..
const user_avatar = message.author.avatarURL({ format: 'png', dynamic: true, size: 2048 }); // gets discord user avatar
const user_suggestion = args.slice(0).join(" ") // gets discord user args
let suggestion_channel = message.guild.channels.cache.find(
(cache) => cache.name === "suggestions" // the channel name u want the embed to be sent to..
);
if (!suggestion_channel) return;
const suggestion_emb = new MessageEmbed() // The suggestion embed that will be sent to the "suggestions" channel
.setAuthor(`Suggestion:`, `${user_avatar + "?size=2048"}`)
.setDescription(`${user_suggestion}`)
.setColor("RANDOM") // randomizes the color of the embed, can also be hex n rgb so ".setColor("#3d71e7")" for example.
.setFooter(`Suggested by: ${message.author.tag}`);
const suggestion_reply_emb = new MessageEmbed() // the reply embed so when someone does !suggest suggestion here, it will reply with the embed below
.setAuthor(`${message.author.tag}`, `${user_avatar + "?size=2048"}`)
.setDescription(`:white_check_mark: Your suggestion has been sent to <#CHANNEL_ID_HERE>.`)
.setColor("RANDOM");
message.reply(suggestion_reply_emb) && suggestion_channel.send(suggestion_emb)
};
if u use a command handler just remove the first & last line

ReferenceError: message is not defined - Welcome Message - embed

So I was playing with my welcome message and wanted to make it an embed, I ended up re-writing it all to work with the embed, however after I finished, I got the error message is not defined.
var welcomePath = './Storage/welcome.json';
var welcomeRead = fs.readFileSync(welcomePath);
var welcomeFile = JSON.parse(welcomeRead);
client.on('guildMemberAdd', (member) => {
var serverId = member.guild.id;
if (!welcomeFile[serverId]) {
console.log('Welcome is disabled!');
} else {
let welcomeChannel = welcomeFile[serverId].channel,
let setChannel = message.guild.channels.find(channel => channel.name === welcomeChannel);
const embed = new Discord.RichEmbed()
.setTitle("Test")
.setAuthor("Test")
.setColor(3447003)
.setDescription("Test")
.setThumbnail(message.author.avatarURL);
member.guild.channels.get(setChannel).send({
embed
});
}
});
The error pertains to this line
let setChannel = message.guild.channels.find(channel => channel.name === welcomeChannel);
I do really want to learn JS, and keep finding myself hitting this brick walls where I need to simply ask for help. I am also unsure if you fix my message is not defined that my code will actually do anything.
message is not defined, you should look for member.
let setChannel = member.guild.channels.find(channel => channel.name === welcomeChannel);
client.on('guildMemberAdd', (member) => {
var serverId = member.guild.id;
if (!welcomeFile[serverId]) {
console.log('Welcome is disabled!')
} else {
let welcomeChannel = welcomeFile[serverId].channel
let setChannel = member.guild.channels.find(channel => channel.name === welcomeChannel);
const embed = new Discord.RichEmbed()
.setTitle("Test")
.setAuthor("Test")
.setColor(3447003)
.setDescription("Test")
.setThumbnail(message.author.avatarURL)
member.guild.channels.get(setChannel).send({embed});
}
})

Categories

Resources