(Discord.js) Bot does not respond - discord

I've made a bot, and I have this purge function, it worked before i added the if that checked for the user's role. It gives me no errors and doesnt reply at all, no matter if i have the roles or not.
Code:
client.on("message", message => {
if (message.content.startsWith(prefix("purge"))) {
if (!message.guild.member.roles.cache.get('703727486009213048') || !message.guild.member.roles.cache.get('702847833241550859') || !message.guild.member.roles.cache.get('703727579328151562')) {
console.log('ssadd')
return message.reply('you can\'t use that command!')
};
const args = message.content.slice(prefix.length).split(" ");
const amount = args[1];
if (!amount) {
return message.reply("please specify the number of messages to purge!");
}
if (isNaN(amount * 1)) {
return message.reply(
"you'll need to specify a number, not whatever \"" +
`${amount}` +
'" is.'
);
}
message.delete();
message.channel.bulkDelete(amount * 1 + 1);
};
});
client.login(process.env.token);```

If it never replied to anything that either means the bot didn't log in or it never passed the first if condition. To check if the bot logged in, just do client.on("ready", () => console.log("ready"))
But I think it's more likely it just failed the first condition, is prefix a function?
prefix("purge") should be prefix + "purge".
There are some other flaws in your code too. Heres just the redo, if you need me to explain anything just lmk.
client.on("message", msg => {
if (msg.author.bot || !msg.content.startsWith(prefix)) return;
const args = msg.content.slice(1).split(" ");
//later on you should move to modules but for now this is fine ig
if (args[0] === "purge") {
//other flags here https://discord.js.org/#/docs/main/stable/class/Permissions?scrollTo=s-FLAGS
if (!msg.member.hasPermission("ADMINISTRATOR")) {
return msg.reply("you can't use that command!")
}
const amount = args[1] && parseInt(args[1]);
if (!amount) {
return msg.reply("please specify an integer of messages to purge!");
}
msg.delete();
msg.channel.bulkDelete(amount);
};
});
client.login(process.env.token);

Related

Discord.JS bot not responding to several commmands

My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there

I need help I am trying to put a kick and ban command inside the code but I don't know where I need put it

client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
This is the code of kick and ban.^^
https://sourceb.in/2e6ba31dc3 - this is my discord bot code where I want to put the ban and kick command code
You want to put the command inside of the client.on("message", (message) block.
I'll use it in your code as an example:
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
// Kick start
if (command === 'kick') {
// Only check if the command caller has permission,
// AFTER the command is called, not before.
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
// Define which member needs to get kicked by grabbing the first mentioned guild member
let member = message.mentions.members.first();
// If the tagged member is not found in your guild,
// throw this message
if(!member) return message.channel.send('Cannot find this member');
// Proceed to kick the member
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
});
I hope this answers your question. Check the discordjs docs here if you haven't checked them already. They feature a nice tutorial on setting up your bot.

How to check if members having a particular role are present in a particular voice channel in discord.js

I'm trying to find if any member having a particular role id is present in a particular voice channel. If even 1 member having the particular role id is present in that particular voice channel, then only those members can use the commands of music bot.
From my research, I have came to know that voiceStateUpdate may help but the problem is I don't know how to use it in my codes(cause I am new to JavaScript). Here is the link to the documentation:
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate .
Here is a part of my code:
client.on('voiceStateUpdate', (oldMember, newMember) => {
});
client.on('message', async message => {
if (message.author.bot) return
if (!message.content.startsWith(prefix)) return
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
const args = message.content.substring(prefix.length).split(' ');
const searchString = args.slice(1).join(' ')
const url = args[1] ? args[1].replace(/<(._)>/g, '$1') : ''
const serverQueue = queue.get(message.guild.id)
if() { //the conditional statement I am trying to put here but I don't know how to do it properly
if (message.content.startsWith(`${prefix}play`)) {
const voiceChannel = message.member.voice.channel
if (!voiceChannel) return message.channel.send("You need to be in a voice channel to play music")
.......
So the main thing is that I don't know what to write their exactly in the if statement that would make my code work properly.
client.on("message", async message => {
// Checking if the message author is a bot.
if (message.author.bot) return false;
// Checking if the message was sent in a DM channel.
if (!message.guild) return false;
// The role that can use the command.
const Role = message.guild.roles.cache.get("RoleID");
// The voice channel in which the command can be used.
const VoiceChannel = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
// Checking if the GuildMember is in a VoiceChannel.
if (!message.member.voice.channel) return message.reply("You need to be in a voice channel.");
// Checking if the GuildMember is in the required VoiceChannel.
if (message.member.voice.channelID !== VoiceChannel.id) return message.reply("You are in the wrong VoiceChannel.");
// Checking if the GuildMember has the required Role.
if (!message.member.roles.cache.has(Role.id)) return message.reply("You are not allowed to execute this command.");
// Execute your command.
return message.reply("Command executed");
};
});
So from what I can understand, you want the command to only execute when a user with the role 'Example Role' is in the channel 'Example Channel'
For this you will need the role id and the channel id.
client.on("message", async message => {
if (message.author.bot) return;
if (!(message.guild)) return;
var roleID = 'RoleID';
var vc = message.guild.channels.cache.get("VoiceChannelID");
if (message.content.toLowerCase() == "test") {
canUse = false;
vc.members.forEach((member) => {
if (member.roles.has(roleID)) {
canUse = True;
}
})
if (!(canUse)) { // nobody in the voice channel has the role specified.
return;
}
console.log("A member of the voice channel has the role specified")
}
});

How to get the specific discord bot channel with channelid?

My bot returns undefined when using bot.channels.get(channelid).
Here's a sample of my code:
//this is executed in a guild with id 416809320513011713
const Discordjs = require("discord.js");
const bot = new Discordjs.Client();
const auth = require('./auth.json');
const FileSys = require("fs");
bot.on('messageDelete', async function (message) {
console.log('message deleted')
let currentguildsettings = JSON.parse(FileSys.readFileSync('./DatStore/GuildDat/' + message.guild.id + '.dat', 'UTF8'));
if (currentguildsettings[0] == 1) {
if (currentguildsettings[1] != 0) {
let channelid = currentguildsettings[1].toString()
let channel = bot.channels.get(channelid);
console.log('settings on true, channelid ' + channelid)
if (channel) {
console.log('channel found')
}
}
}
}
bot.login(auth.token)
file ./DatStore/GuildDat/416809320513011713.dat contains:
[1,424085503361417200,0]
Here's the output:
message deleted
settings on true, channelid 424085503361417200
If the channel was found it should've logged 'channel found' in the output.
What should I change to make it return the channel?
The channel id key is a string, you must enclose it as a string in your array.
let c1 = bot.channels.get(424085503361417200); // Will produce undefined
let c2 = bot.channels.get('424085503361417200'); // Will produce a channel object (if available)
The channel wasn't available since I used the wrong id:
I saved the id's at my server settings command in int format instead of string, parseInt() broke the exact number.
if (logchannelaction == 'set') {
if (currentguildsettings[1] == message.channel.id) return message.reply("logchannel was already set to this channel");
currentguildsettings[1] = parseInt(message.channel.id);
message.reply("logchannel has set to #" + message.channel.name);
if (currentguildsettings[0] == 0) {
currentguildsettings[0] = 1
message.reply("logchannel has automatically enabled");
}
FileSys.writeFileSync(guilddatpath, JSON.stringify(currentguildsettings));
return
}
Thank you for trying to help me.

Is there a way to toggle an event with command?

Is there any way to make an event toggleable with a command?
I'm trying to make a welcome/farewell event but I don't want it to be active on default.
This is how my event looks right now:
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
let memberTag = member.user.tag;
guild.channels.sort(function(chan1, chan2) {
if (chan1.type !== `text`) return 1;
if (!chan1.permissionsFor(guild.me).has(`SEND_MESSAGES`)) return -1;
return chan1.position < chan2.position ? -1 : 1;
}).first().send(memberTag + " just joined <:floshed:533687801741443082>");
});
As requested here is an example of my comment:
One way to do it is to store a variable for a guild in some database which has a value of either true or false. Then you'd grab that variable and check if said guild has the option turned on or off
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
let memberTag = member.user.tag;
// Code here to get the guild from database, this is just a non-working example
let dbGuild = database.get('Guild', guild.id);
// Check if the guild has the welcome command disabled
if (dbGuild.enableWelcomeCmd === false) {
// Breaks the function, no further message will be send
return;
}
guild.channels.sort(function(chan1,chan2){
if(chan1.type!==`text`) return 1;
if(!chan1.permissionsFor(guild.me).has(`SEND_MESSAGES`)) return -1;
return chan1.position < chan2.position ? -1 : 1;
}).first().send(memberTag + " just joined <:floshed:533687801741443082>");
});
client.on("message", async message => {
// Check if the msg has been send by a bot
if(message.author.bot) return;
// Check if message has correct prefix
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Code for actually changing the guild variable
if (command === 'toggleWelcome') {
// Code here to get the guild from database, this is just a non-working example
let dbGuild = database.get('Guild', message.guild.id);
dbGuild.enableWelcomeCmd = !dbGuild.enableWelcomeCmd;
// Save the new variable for the guild (also a non-working example)
database.save('Guild', message.guild.id, dbGuild);
}
});
You'll have to look into databases and such yourself, there is a wide variety of (free) options which all have a different syntax. That part is something for you to figure out but I hope this can give you a general idea.

Resources