discord.js bot won't mention a user - javascript

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.

Related

Output increasing every time the command is used

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

Discord.js send message then wait until you reply

I've been trying to code a Discord bot and I can't figure out how to make it wait until you say Y or N. Right now, I'm trying to code the ban command and it works pretty well until it asks you to say Y or N. Then once it asks that and you answer, nothing happens.
Here's the code:
module.exports = {
name: 'ban',
description: 'This bans a member!',
execute (message, args){
var member = message.mentions.users.first();
if(member){
var memberTarget = message.guild.members.cache.get(member.id);
message.channel.send(`Are you sure you want to ban ${member}? (Y or N)`);
var messagethingy = message.first()
var askingBan = ('1')
do { if (messagethingy.content.toLowerCase === 'y' || messagethingy.content.toLowerCase === 'yes' || messagethingy.content.toLowerCase === 'n' || messagethingy.content.toLowerCase === 'no'); {
if (messagethingy.content.toLowerCase === 'no' || messagethingy.content.toLowerCase === 'n') {
message.channel.send('The Action has been cancelled')
var askingBan = ('0')
return
} else if (messagethingy.content.toLowerCase === 'y' || messagethingy.content.toLowerCase === 'yes') {
message.channel.send(`You have banned ${member}!`)
memberTarget.ban();
var askingBan = ('0')
}}
}
while (askingBan = '1');
} else {
message.channel.send("You couldn't ban that member!");
}
}
}
FYI these commands are in a different thingy. The main commands are in main.js and the command that senses when you say ban works perfectly fine.
Instead of a do-while loop, you can use a message collector. You can send a confirmation message and in the same channel set up a collector using createMessageCollector.
For its filter, you can check if the incoming message is coming from the same user who want to ban the member, and check if the message content is one of the accepted answers (y, yes, n, no). You can convert the message to lowercase to make it case insensitive.
You can also add some options, like the maximum number of accepted answers, and the maximum time the collector is collecting messages. I set it to one minute, and after a minute it sends a message letting the original poster know that the action is cancelled.
module.exports = {
name: 'ban',
description: 'This bans a member!',
async execute(message, args) {
const member = message.mentions.members.first();
if (!member) {
return message.channel.send('You need to mention a member you want to ban!');
}
// TODO: check if message.author can ban users
const confirmation = await message.channel.send(`Are you sure you want to ban ${member}? (Y or N)`);
const answers = ['y', 'yes', 'n', 'no'];
const filter = (m) =>
answers.includes(m.content.toLowerCase()) &&
m.author.id === message.author.id;
const collector = confirmation.channel.createMessageCollector(filter, {
max: 1,
time: 60000,
});
collector.on('collect', async (m) => {
if (
m.content.toLowerCase() === answers[2] ||
m.content.toLowerCase() === answers[3]
) {
return message.channel.send(
`The action has been cancelled, ${member} is not banned.`
);
}
try {
await member.ban();
return message.channel.send(`You have banned ${member}!`);
} catch (error) {
return message.channel.send(`Oops, error: ${error}`);
}
});
collector.on('end', (collected, reason) => {
if (reason === 'time') {
message.channel.send(
`${message.author}, it's been a minute without confirmation. The action has been cancelled, ${member} is not banned.`
);
}
});
},
};

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.

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources