discordjs how to console log message without dms - discord

I would my bot to print messages sent to a server, but when that bot has been sent a dm it prints it.
client.on('message', message => {
console.log(chalk.yellow(`[CHAT] `) +
chalk.bold.magentaBright(`[${message.guild.name}] `) +
chalk.bold.white(`User: ${message.author.username} ` +
`Said: ${message.content} In: ${message.channel.name}`))
}
});

you can ignore all DM message from users
if (message.channel.type === 'dm') return;
Add it to bot on message block
client.on('message', message => {
if (message.channel.type === 'dm') return;
console.log(chalk.yellow([CHAT]) + chalk.bold.magentaBright([${message.guild.name}]) + chalk.bold.white(User: ${message.author.username} Said: ${message.content} In: ${message.channel.name})) }
});

Related

When using a variable inside an embed I get [object Object] returned not the value (discord.js)

I am attempting to create a kick command for a bot and its working fine however when the bot logs the embed it doesn't display the data in the variable but [object Object]
The Embed Output
My code is as following
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if(!member) return message.reply("Please mention a valid member of this server");
if(!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(' ');
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor('#1773BA')
.setTitle('User Kicked')
.setDescription({username} + "had been kicked for " + {reason})
;
client.channels.cache.get("771835493305286688").send(kickedmessage)//output the embed
member.kick(reason);
I am using discord.js v12
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(" ");
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor("#1773BA")
.setTitle("User Kicked")
.setDescription(username + "had been kicked for " + reason);
client.channels.cache.get("771835493305286688").send(kickedmessage); //output the embed
member.kick(reason);
};

Discord bot join/leave channel change separately per guild

I am trying to find out how to make a command that detects a channel from separate guilds (etc. $setwelcome #channel). I have made the command but, instead of setting it for one guild its setting it for all guilds. this is my code
client.on('guildMemberAdd', member => {
console.log("New member joined.");
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel){
console.log("The joinChannel does not exist.");
}else{
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
member.roles.add(member.guild.roles.cache.find(i => i.name === 'member'));
}
});
/*const channel = member.guild.channels.cach.find((ch) => {
console.log(ch.name);
return ch.name === joinChannel;*/
client.on('guildMemberRemove', member =>{
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Goodbye ${member}, we will miss you :cry:`);
})
client.on("message", message => {
if (!message.author.bot){
const content = message.content;
if (content.toLowerCase().startsWith(`${prefix}setwelcome`)){
joinChannel = content.substring((`${prefix}setwelcome`).length).trim();
console.log(`Join channel changed to ${joinChannel}`);
}
}
});
I guess you could use JSON, best in a database, or different file:
//how the JSON should look like
{
"G123456789012345678": "123456789012345678"
}
//first part is the guild ID, second, is the id the channel you choose
Now you have to somehow modify this data, for this I will use fs, which assumes that this is in the file system. I’ll reference it as if it was in the same folder, and is named: welcomeChannels.json
const fs = require('fs');
//maybe other "requires"
client.on('message', msg => {
//checking message content etc
let ChansString = fs.readFileSync('./welcomeChannels.json');
let chans = JSON.parse(ChansString);
//you can get the channel for the guild with chans['G'+guild.id]
chans['G'+msg.guild.id] = msg.mentions.channels.first().id || msg.channel.id;
fs.writeFileSync('./welcomeChannels.json', JSON.stringify(chans));
})
//use chans[`G${guild.id}`] to get the welcome channel id
Warning: this could fill up your storage. You should use a database instead.

Send Server Message after Track Users Status (discord.js)

I try to send a Message in a Server. This Server ID is logged in MongoDB and the Channel ID too. But everytime i'll try it, it does not working. Here's my Code:
The Error is the return console.log Text
//This is the guildMemberUpdate file
const client = require("../index.js")
const {MessageEmbed} = require("discord.js")
const {RED, GREEN, BLUE} = require("../commands/jsons/colors.json")
const Schema = require("../models/StatusTracker.js")
client.on("guildMemberUpdate", async(member) => {
const data = await Schema.findOne({Guild: member.guild.id})
let channel = member.guild.channels.cache.get(data.Channel)
if(!channel) return console.log("Es wurde kein Channels gefunden");
if(member.user.presence.status === "offline") {
let offlineEmbed = new MessageEmbed()
.setColor(RED)
.setDescription(member.user.toString() + " ist jetzt offline!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(offlineEmbed)
} else if(member.user.presence.status === "dnd" || member.user.presence.status === "online" || member.user.presence.status === "idle"){
let onlineEmbed = new MessageEmbed()
.setColor(GREEN)
.setDescription(member.user.toString() + " ist jetzt online!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(onlineEmbed)
}
})```
//This is the MongoDB File
"Guild": "851487615358337065",
"Channel": "859444321975009290"
The problem is that you're using the guildMemberUpdate event, but that only tracks nickname and role changes. The one that you're looking for is presenceUpdate. That'll trigger when any user goes offline etc.
Check the docs for more details: here
Note: You'll probably need to enable 'Presence intent' in 'Privileged Gateway Intents' in your bot's settings page for this to work. (https://discord.com/developers/applications)

Unban is not defined

const Discord = require('discord.js');
module.exports = {
name: 'unban',
aliases: ['uban', 'unban'],
category: 'misc',
permissions: ['BAN_MEMBERS'],
description:
'Use this command to permanately or temporary ban a server member from Sekai.',
/**
* #param {Discord.Message} message
* #param {Array} args
*/
async execute(message, args) {
if (message.mentions.users.size === 0)
return message.reply('Please mention a user to unban ❌');
const targetid = message.mentions.users.first().id;
if (targetid === message.client.user.id)
return message.reply(
"Me? Really? That's not very nice, I guess you failed 🤡"
);
const targed = await message.guild.members.cache.get(targetid);
let reason = [];
if (args.length >= 2) {
args.shift();
reason = args.join(' ');
} else reason = 'No Reason provided';
try {
let extra = '';
try {
const embed = new Discord.MessageEmbed()
.setTitle('Moderation message regarding on your **BAN**')
.setAuthor("Joony's Den")
.setDescription(
`you have been banned from **${message.guild.name} ✅ **\nReason for ban: **${reason}\n${extra}**`
)
.addField('Contact','If you believe that your ban was unjustified, please feel free to contact any of these staff members. **JOONY#9513** or any of administrators online.')
.setColor('#2243e6')
.addField('Appeal Accepted?','if your appeal was accepted, please join using this link. your link will expire after 1 use. **https://discord.gg/4yuCzUC7aw**')
.addField(
'Appeal',
'Because you have been banned from the server, you will have one chance to appeal 🔨. Your appeal will be processed to the administrators or appeal managers ✅ **[CLICK HERE TO APPEAL](https://forms.gle/atc75ZftpdfJhfH56)**'
);
targed.send(embed);
} catch (error) {
extra = 'Messaging the user has failed! ❌';
}
setTimeout(() => {
targed.unban(targed, [reason])
const embed = new Discord.MessageEmbed()
.setTitle('User unbanned')
.setDescription(
`${
targed.tag || targed.user.username
} has been sucessfully unbanned from **${
message.guild.name
} ✅ **\nReason for unban: **${reason}\n${extra}**`
)
.setColor('#FA2657');
message.channel.send(embed);
}, 2000);
} catch (error) {
message.channel.send(
`I could not unban the given member, make sure that my role is above member! ❌`
);
}
},
};
Hello! how do I unban the user using this format, it has an error saying "guild.unban is undefined"
it has an error saying
targed.unban([reason])
^
TypeError: targed.unban is not a function
at Timeout._onTimeout (C:\Users\Joon\Documents\GitHub\Discord-Bot\commands\misc\unban.js:49:16)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
You cannot unban a GuildMember (a banned user is not a member of a Guild). You should call unban on GuildMemberManager. See https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban

discord.js can not read property'id' of undefined when bulk delete messages

I have been working on a bulk delete message logs, but for whatever reason it can not get the ID of the channel from the guild in a seperate file. so it returns that ID is undefined.
THE CODE
module.exports = async (bot, messages) => {
const length = messages.array().length
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
let mEmbed = new MessageEmbed()
.setAuthor(messages.guild.name, messages.guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
In the index file I specified the
messageDeleteBulk
When trying to send the message to the messageChannel it does not send because 'id' is undefined. Is there something I am missing?
So, the command works fine all I forgot was that earlier when I defined length I used
messages.first()so where I just put messages I have to add .first()
THE NEW CODE
module.exports = async (bot, messages) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.first().guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
const length = messages.array().length;
let mEmbed = new MessageEmbed()
.setAuthor(messages.first().guild.name, messages.first().guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.first().channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
Now it logs the bulk deleted messages and does not return any errors.

Resources