Output increasing every time the command is used - javascript

I tried to make a kick members script in discord.js. My error is, that every time I send the !kick command the message gets displayed one more time. For example, if I send !kick for the first time, it would send this response: "Please specify a user!". If I send it for the second time, it would send that message twice, and so on. My code:
const Discord = require("discord.js")
exports.run = async(client, msg, args) => {
msg.delete();
if(!msg.member.hasPermission('KICK_MEMBERS')) return msg.reply('you don\'t have permission to use this command!')
const user = msg.mentions.users.first() || msg.guild.members.cache.get(args[0]);
if(!user) return msg.reply(`please specify a user you wish to be punished.`).then(msg => msg.delete({timeout: 5000}));
let member;
try {
member = await msg.guild.members.fetch(user)
} catch(err) {
member = null;
}
if(member){
if(member.hasPermission('MANAGE_MESSAGES')) return msg.reply('that user is too cool to be banned.').then(msg => msg.delete({timeout: 5000}));
}
let reason = args.slice(1).join(' ');
if(!reason) return msg.reply('please specify a reason.').then(msg => msg.delete({timeout: 5000}));
let channel = msg.guild.channels.cache.find(c => name.name === '📁┊discord_logs');
let log = new Discord.MessageEmbed()
.setColor('#0088FF')
.setDescription(`${user} has been kicked by ${msg.author} for ${reason}`)
channel.send(log);
let userLog = new Discord.MessageEmbed()
.setColor('#0088FF')
.setDescription(`You have been kicked from Scratta for: ${reason}`)
try {
await user.send(userLog);
} catch(err) {
console.warn(err);
}
member.kick(reason)
let confir = new Discord.MessageEmbed()
.setColor('#0088FF')
.setDescription(`${user} has been kicked from Scratta.`)
msg.channel.send(confir);
msg.delete();
}

You‘re missing this line at the top in your module.exports:
if (msg.author.bot) return;
This will make sure that the bot doesn‘t react to his own message

Related

Discord bot unintentionally spamming messages after user response

I am making a discord bot that basically detects a word the user sends in a message and it will reply with a message. But the problem is that my bot is spamming the message instead of sending the message just once. I am not sure what is happening, I've looked all over the internet for a solution and couldn't find one which is why I came here for help.
let Discord;
let Database;
if(typeof window !== "undefined"){
Discord = DiscordJS;
Database = EasyDatabase;
} else {
Discord = require("discord.js");
Database = require("easy-json-database");
}
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
const s4d = {
Discord,
client: null,
tokenInvalid: false,
reply: null,
joiningMember: null,
database: new Database("./db.json"),
checkMessageExists() {
if (!s4d.client) throw new Error('You cannot perform message operations without a Discord.js client')
if (!s4d.client.readyTimestamp) throw new Error('You cannot perform message operations while the bot is not connected to the Discord API')
}
};
s4d.client = new s4d.Discord.Client({
fetchAllMembers: true
});
s4d.client.on('raw', async (packet) => {
if(['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)){
const guild = s4d.client.guilds.cache.get(packet.d.guild_id);
if(!guild) return;
const member = guild.members.cache.get(packet.d.user_id) || guild.members.fetch(d.user_id).catch(() => {});
if(!member) return;
const channel = s4d.client.channels.cache.get(packet.d.channel_id);
if(!channel) return;
const message = channel.messages.cache.get(packet.d.message_id) || await channel.messages.fetch(packet.d.message_id).catch(() => {});
if(!message) return;
s4d.client.emit(packet.t, guild, channel, message, member, packet.d.emoji.name);
}
});
s4d.client.login('tokenNumber').catch((e) => { s4d.tokenInvalid = true; s4d.tokenError = e; });
s4d.client.on('message', (s4dmessage) => {
if (s4dmessage.content.includes('oranges')) {
s4dmessage.channel.send(String('Yum! I love eating oranges!'));
}
}
);
s4d;
Your bot checks if the message contains the word "orange" and if it does, sends a response that it loves eating oranges. As the response also contains the word "orange", your bot repeats this function until you're rate limited.
Make sure you check if the message author is a bot, and if it is, simply exit by using return:
s4d.client.on('message', (s4dmessage) => {
if (s4dmessage.author.bot) return;
if (s4dmessage.content.includes('oranges')) {
s4dmessage.channel.send(String('Yum! I love eating oranges!'));
}
});

Discord.js embed edit description with users reply

So I would like to know if it is possible to edit a message Embed with the user's reply. I will post the code below and the example.
module.exports.run = async (Client, message, args) => {
let battleChannel = message.channel;
const filter = (m) => !m.content.length === 3;
message.reply("Please enter your alliance name... Will expire in 10 seconds...");
message.channel
.awaitMessages(filter, { max: 1, time: 10000 })
.then((collected) => {
let game = new Listing();
let editLast3 = null;
let startMessage = new Discord.MessageEmbed().setTitle("1657 Battles").setDescription("Please write your alliance.").setColor("#0099ff").setTimestamp().setFooter(`Maintained by UKzs`);
message.delete();
message.channel.send(new Discord.MessageEmbed().setTitle("1657 Battles").setDescription("").setColor("#0099ff").setTimestamp().setFooter(`Maintained by UKzs`));
})
.catch((err) => {
console.log(err);
});
};
So as you can see I have the first part then I am waiting for a response from the user so I would type the following command !start = The bot will them bot the above info and wait for me to reply = I then reply with 57kl = Is there a way to then update the embed with 57kl instead of "Please write your alliance."
Thank you Ukzs
You can store the embed/message you send initially:
const original = await message.channel.send(embed);
then edit it after you collected the message:
original.edit(newEmbed);

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

Is there a way to get channels by name? (Discord.js v12)

I was creating a lock command where the channel name/id would be passed as the 1st argument. The command use case would be something like this: .lock #[channel-name]/[channel_id]. This works with a channel id, however, it returns undefined when I attempt to use a channel name instead (e.g .lock #test). Would there be a way to achieve this?
const channel =
bot.channels.cache.find(
(channel) => channel.name == `#${args.slice(0).join('-')}`
) || bot.channels.cache.get(args[0]);
if (!channel) {
console.log(channel);
return message.reply('Please provide a channel name/id!');
}
if (!args[1]) {
return message.reply('Please set the lock type!');
}
if (!channel.permissionsFor(message.guild.roles.everyone).has('VIEW_CHANNEL')) {
const errorEmbed = new Discord.MessageEmbed()
.setDescription(
`❌ \`VIEW_CHANNEL\` for \`${channel.name}\` is already disabled.`
)
.setColor('RED');
return message.channel.send(errorEmbed);
}
channel
.updateOverwrite(channel.guild.roles.everyone, { VIEW_CHANNEL: false })
.then(() => {
const msgEmbed = new Discord.MessageEmbed()
.setDescription(`✅ The channel\`${channel.name}\` has been locked.`)
.setColor('GREEN');
message.channel.send(msgEmbed);
})
.catch((error) => {
console.log(error);
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`❌ Unable to lock \`${channel.name}\`.`)
.setColor('RED');
message.channel.send(errorEmbed);
});
discord.js parses channel mentions (#channel-name) as <#channelID>, not #channel-name.
You can use:
bot.channels.cache.get(args[0].match(/<#(\d+)>/)[1])
to get a channel from a mention.

discord.js bot won't mention a user

I'm creating a discord bot using the discord.js v12.2.0+ library. Im creating a !enslave command which gets the bot to ping the target person once every 2 seconds 60 times. So for example !enslave #Hello123 gets the bot to spam this "Torturing #Hello123 :evil:" but the bot doesn't if I do !enslave 35203573250237 and it sends "Torturing undefined :evil:". The long number being the discord user's id.
This is my enslave.js code:
module.exports = {
run: async(client, message, args) => {
if(!message.member.hasPermission('ADMINISTRATOR')) {
message.channel.send("You don't have permission to use that command.");
}
else {
try {
let counter = 0;
message.delete()
let user = message.mentions.members.first() || await message.guild.members.fetch(args[0])
console.log(args[0])
let i = setInterval(function(){
const bot = client.emojis.cache.get('712787936734609419');
message.channel.send(`Torturing ${user} ${bot}`);
counter++;
if(counter === 60) {
clearInterval(i);
}
}, 2000);
}
catch(err) {
console.log(err);
}
}
},
aliases: [],
description: 'Make ImmortusMC torture someone'
}
This is my message.js code:
const PREFIX = process.env.PREFIX;
module.exports = (client, message) => {
if(message.author.bot) return;
if(!message.content.startsWith(PREFIX)) return;
let cmdName = message.content.substring(message.content.indexOf(PREFIX)+1).split(new RegExp(/\s+/)).shift();
let argsToParse = message.content.substring(message.content.indexOf(' ')+1);
if(client.commands.get(cmdName))
client.commands.get(cmdName)(client, message, argsToParse);
else
console.log("Command does not exist.");
};
Use message.guild.members.fetch(args[0]) instead of message.guild.members.cache.get(args[0]).
The reason why you're getting undefined is that the member has not been cached yet so you can't get them using the members cache.
let user = message.mentions.members.first() || await message.guild.members.fetch(args[0])
Sorry for the late answer, but ry:
let user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
You should use .get() when you are going to use the IDs. I also removed the await and added the ; at the end.

Categories

Resources