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)
Related
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);
};
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.
I am trying to make a jail command when the members who has this role leave the server and rejoin again the role stay with them ,i want when new members enter the server to compare their ID with the one in the database, if is it true it gives a role again. my code:
client.on("guildMemberAdd",async (member)=>{
let injail = await db.fetch(`ja_${member.guild.id}`)
let role = msg.guild.roles.cache.find(n => n.name === 'Jail');
if(member.guild.id = injail){
member.roles.remove(user.roles.cache)
member.roles.add(role)
}
});
client.on('message', msg => {
if(msg.content.startsWith(prefix + 'jail')){
if(!owners.includes(msg.author.id)) return msg.channel.send("**You Dont Have Perms 📛**")
if(!msg.channel.guild) return;
var logChannel = msg.guild.channels.cache.find(channel => channel.id === logID)//LOG
let jailRole = msg.guild.roles.cache.find(n => n.name === 'Jail');
let user = msg.mentions.members.first() //You can change this to an ID
let args = msg.content.split(" ").slice(1).join(" ")
if(!args[0]) return msg.channel.send('**:x: Please Mention A User**')
if(user.hasPermission("ADMINISTRATOR")) return msg.channel.send("**Im NOT Allowed To Do This 📛**")
let there = db.get(`jl_${msg.guild.id}_${user}`, user.id)
if (there) return msg.channel.send('**This User AlREADY In Jail â›”**')
msg.channel.send(`**ADDED ${user} to the Jail! ✅**`)
db.set(`jl_${msg.guild.id}_${user}`, user.id)
user.roles.remove(user.roles.cache)
user.roles.add(jailRole)
let embed = new Discord.MessageEmbed()
.setTitle('Jail System')
.setAuthor(msg.author.tag,msg.author.avatarURL({dynamic:true}))
.addField("Status",`JOINED THE JAIL 🔴`)
.addField("User",`<#${user.id}> (ID: ${user.id})`)
.addField("By",`<#${msg.author.id}> (ID: ${msg.author.id})`)
.setTimestamp()
logChannel.send(embed)
}
});
Whenever people gets "jail" role, save "yes" to database.
and check condition as you did above.
here I'll give sample code:
// when people gets jail role, add following code:
db.set(`ja_${msg.guild.id}_${user}`, "yes") // or you can simply use boolean operator
// when guildMemberAdd event triggers check condition:
let condition = db.fech(`ja_${member.guild.id}_${member.user.id}`)
if(condition === "yes"){
// write code to add "jail" role to the member
}
else{
// your other code
}
Also don't forget to set "no" in the database whenever you remove jail role from member.
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.
i am tring to do that every time someone that joins my server blocks dms the bot will open a channel and send a verify link instead of a dm
what I stuck on (store the channel and stuff like that)
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
channel = client.channels.cache.get(`${logschannel}`);
channel.send('user has joined if you dont get another message in a few minutes please check if the user has verifyed ');
member.send(embed).catch(() => {message.guild.channels .create(member.id, { type: "text" }), channel.send('#here'); const errore = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`The user with the id ${member.id} is blocking dms please check on that!`)
.setColor('RED')
channel.send(errore)})
what I had
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
channel = client.channels.cache.get(`${logschannel}`);
channel.send('user has joined if you dont get another message in a few minutes please check if the user has verifyed ');
member.send(embed).catch(() => {channel.send('#here'); const errore = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`The user with the id ${member.id} is blocking dms please check on that!`)
.setColor('RED')
channel.send(errore)})
To create the channel you can just use GuildChannelManager#create (aka guild.channels.create).
member.guild.channels.create(`${member.author.username}-verification`, {
permissionOverwrites: [
{
id: member.author.id,
allow: ['VIEW_CHANNEL'],
},
{
id: member.guild.id,
deny: ['VIEW_CHANNEL'],
},
]
});
To send a message to the channel there are two ways you can do it.
A: Store the channel object.
const verifyChannel = member.guild.channels.create(`channel`);
verifyChannel.send('Message!')
B: Use .then() as creating as channel returns a promise.
member.guild.channels.create(`channel`)
.then(chan => {
chan.send('Message!');
});