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.
Related
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.
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}`);
})
}
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.
});
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');
}
});
im trying to make my discord.js bot send an embed when someone joins, with as thumbnail their pfp, but it always leaves the same error.
code:
bot.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const WelcomeChannel = member.guild.channels.cache.find(ch => ch.name === config.WelcomeChannelVar);
var newMember = member
// Do nothing if the channel wasn't found on this server
if (!WelcomeChannel) return;
const welcomeEmbed = new Discord.MessageEmbed()
.setTitle(newMember + 'joined!')
.addField('username', member)
.setColor(0x348a58)
.setThumbnail(newMember.showAvatarURL())
.setFooter('wow very nice profile bro')
WelcomeChannel.send(welcomeEmbed);
member.send("welcome to frogpond! read the rules :)");
});
error:
TypeError: newMember.showAvatarURL is not a function
I've tried everything. can somebody help plz?
thanks!
I'm pretty sure that showAvatarURL() is not a function and you mean avatarURL() instead, so you should change your code to be like this:
const welcomeEmbed = new Discord.MessageEmbed()
// your stuff before thumbnail
.setThumbnail(newMember.user.avatarURL())
// your stuff after thumbnail
edit: the .user is important, because avatarURL is only a User function
It's because you wrote showAvatarURL() instead of displayAvatarURL().