How can I use the USER ID instead of using the mentions? - javascript

I recently made a discord command called -dm that basically DMs the user mentioned in the message. Something like: -dm #Omega Hello! and it would send "Hello!" to the user mentioned.
But some people find it annoying when they get pinged multiple times, so I want to know if there is a way I could use the USER ID instead of mentioning the user. That would make life a lot more easier. For whom it may concern, my code is given below.
const Discord = require('discord.js')
module.exports = {
name: 'dm',
description: 'DMs the person with the User ID mentioned',
execute(client, msg, args) {
if(!msg.member.permissions.has("ADMINISTRATOR")) return msg.channel.send("You cannot do that!")
//if(msg.author.id !== 'CENSORED') return msg.channel.send("You cannot do that!")
const user = msg.mentions.users.first()
if(!user) return msg.channel.send("That user ID doesn't exist OR that person isn't in the same server as me!")
const str = args.slice(1).join(" ")
user.send(str)
msg.channel.send("Message sent to the user!")
var dmLogger = new Discord.MessageEmbed()
.setTitle("DM Sent")
.setColor("RANDOM")
.addField("MESSAGE SENT BY", msg.author.tag)
.addField("MESSAGE SENT TO", user)
.addField("MESSAGE CONTENT", str)
.setTimestamp()
client.channels.cache.get('CENSORED_2.0').send(dmLogger)
}
}

You could add await message.guild.members.fetch(args[0]) but if you still want to keep the mentions thing you can just add that to your user variable.
const user = msg.mentions.users.first() || await msg.guild.members.fetch(args[0])
If you want only with user ID, remove the mentions part.

Related

discord.js Javascript string manipulation

so i am creating a bot with a kick command and would like to be able to add a reason for said action, i've heard from somewhere that i may have to do string manipulation. currently i have a standalone reason as shown in the code below:
client.on("message", (message) => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
// If the message starts with ".kick"
if (message.content.startsWith(".kick")) {
// Assuming we mention someone in the message, this will return the user
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 server
if (member) {
member
.kick("Optional reason that will display in the audit logs")
.then(() => {
// lets the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch((err) => {
// An error happened
// This is generally due to the bot not being able to kick the member,
// either due to missing permissions or role hierarchy
message.reply(
"I was unable to kick the member (this could be due to missing permissions or role hierarchy"
);
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this server
message.reply("That user isn't in this server!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
Split message.content and slice the first 2 array elements, this will leave you with the elements that make up the reason. Join the remaining elements back to a string.
const user = message.mentions.users.first();
const reason = message.content.split(' ').slice(2).join(' ');
Here is something that could help:
const args = message.content.slice(1).split(" "); //1 is the prefix length
const command = args.shift();
//that works as a pretty good command structure
if(command === 'kick') {
const user = message.mentions.users.first();
args.shift();
const reason = args.join(" ");
user.kick(reason);
//really close to Elitezen's answer but you might have a very terrible problem
//if you mention a user inside the reason, depending on the users' id, the bot could kick
//the user in the reason instead!
}
Here's how you can take away that problem (with regex)
const userMention = message.content.match(/<#!?[0-9]+>/);
//you may have to do some more "escapes"
//this works since regex stops at the first one, unless you make it global
var userId = userMention.slice(2, userMention.length-1);
if(userId.startsWith("!")) userId = userId.slice(1);
const user = message.guild.members.cache.get(userId);
args.shift();
args.shift();
user.kick(args.join(" "))
.then(user => message.reply(user.username + " was kicked successfully"))
.catch(err => message.reply("An error occured: " + err.message))
I assume you want your full command to look something like
.kick #user Being hostile to other members
If you want to assume that everything in the command that isn't a mention or the ".kick" command is the reason, then to get the reason from that string, you can do some simple string manipulation to extract the command and mentions from the string, and leave everything else.
Never used the Discord API, but from what I've pieced from the documentation, this should work.
let reason = message.content.replaceAll(".kick", "")
message.mentions.forEach((mentionedUser) => reason.replaceAll("#" + mentionedUser.username, "")
// assume everything else left in `reason` is the sentence given by the user as a reason
if (member) {
member
.kick(reason)
.then(() => {
// lets the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
}

Send a message to my private channel on join & leave

Heyo,
I want my bot to send a embed message to my private discord server when it joins & leaves a server. But the problem is that it does not send anything anywhere. My code looks like this:
exports.run = async (client, guild) => {
if(!guild.available) return
if(!guild.owner && guild.ownerID) await guild.members.fetch(guild.ownerID);
if(!channel) return;
const embed = new MessageEmbed()
.setTitle(`Bot joined a server`)
.setDescription(`${guild.name}`)
.setColor(0x9590EE)
.setThumbnail(guild.iconURL())
.addField(`Owner", "${guild.owner.user.tag}`)
.addField(`Member Count", "${guild.memberCount}`)
.setFooter(`${guild.id}`)
client.channels.cache.get('ID').send(embed)
}
Your code doesn't activate upon joining the server. For that you have a nice event (that has a misleading name) guildCreate - it is emitted whenever the client joins a guild.
So, your code should look something like this
client.on('guildCreate', async guild => {
let YourChannel = await client.channels.fetch('channelid');
const embed = new Discord.MessageEmbed()
.setTitle(`Bot joined a server`)
.setDescription(`${guild.name}`)
.setColor(0x9590EE)
.setThumbnail(guild.iconURL())
.addField(`Owner`, `${guild.owner.user.tag}`)
.addField(`Member Count`, `${guild.memberCount}`)
.setFooter(`${guild.id}`)
YourChannel.send(embed);
});
Same works for leaving the guild, use guildDelete event.

How to find a member role in a specific server

I have these two lines of code which checks if the message author have a specific role into the main server of the bot :
const main = client.guilds.cache.get(698725823464734852);
// Blacklist Checker :
if (message.author.main.roles.cache.find(r => r.name === "BlackListed.")) message.reply("you are blacklisted...")
I have tried to connect the functions at message.author.main.roles.cache.find however, it didn't work.
There are two issues with the code you have provided us with;
Firstly the guild ID must be a string and secondly message.author.main will give you an error.
Please see the working code I have provided below.
const Discord = require('discord.js'); //Define discord
const client = new Discord.Client(); //Define client
client.on('message', message => {
const guild = client.guilds.cache.get('698725823464734852'); // Define guild (guild ID must be a string)
const member = guild.members.cache.get(message.author.id); //Find the message author in the guild
if (!member) return console.log('Member is not blacklisted'); //If the member is notin the guild
if (member.roles.cache.find(r => r.name.toLowerCase() === 'blacklisted')) return message.reply('Unfortunately, you have been blacklisted.'); //Let the user know they have been blacklisted.
});

discord.js How to revoke a ban of a banned user using code?

Revoking A Ban Using Code
So, I am making a moderation discord bot using VS Code and I have already set up a ban command. I want to make a unban command (revoking a ban) too so that the user can easily unban a user and not have to go into Server Settings to do it.
I know you can do it because I have been using another bot, GAwesomeBot, that is able to do it.
Link to GAwesomeBot: https://gawesomebot.com
I am a little new to Stack Overflow and this is my first question so pardon me if I am doing anything wrong.
Consider using GuildMemberManager#unban
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban
let guildMemberManager, toUnbanSnowflake;
guildMemberManager.unban(toUnbanSnowflake); // Takes UserResolveable as argument
First you want to define the user that you are unbanning.
Because the user is already banned you will have to mention the user by their ID and then unbanning them.
let args = message.content.split(/ +/g); //Split the message by every space
let user = message.guild.members.cache.get(args[1]); //getting the user
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }); //Unbanning the user
The full example:
//Define your variables
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = 'your-prefix-here';
//Add a message event listener
client.on('message', () => {
let args = message.content.split(/ +/g); //Split the message by every space
if (message.content.toLowerCase() === prefix + 'unban') {
let user = message.guild.members.cache.get(args[1]); //getting the user
if (!user) return message.channel.send('Please specify a user ID');
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }).then(() => message.channel.send('Success');
}
});

Banning users using user ID discord.js

I'm kinda new to coding discord bots and I have a problem. I want to have a ban command that would ban the mentioned user in the command or the user that has an ID that was provided in the command. For example:
&ban #User#0001 would ban User#0001
but
if the command looks like this:
&ban 123456789123456789 (let's say that's the ID of User#0001)
it would still ban User#0001 (as it is the user's ID).
I have this code, it works if I mention the user, but it doesn't work if I enter the ID.
const Discord = require('discord.js');
module.exports = {
name: 'testban',
description: "Executer will ban the mentioned user",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Can't ban that one, he also can ban")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban({reason: banReason})
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
The error I get when entering the ID is this:
message.guild.members.get is not a function
How could I make it ban the person even if I only provide the ID?
If you're using the newer versions of discord.js you need to use the cache, you just need to change it to this:
message.guild.members.cache.get(args[0])

Categories

Resources