I'm trying to do is whenever someone joins the server, the bot sends a rich embed with their ID, their user creation date and the new total members, but whenever i run it and test it, it says that .createdAt() is not a valid function, so i'm completely lost as to what to do.
client.on("guildMemberAdd", member => {
let mlogchannel = member.guild.channels.find((channel => channel.name === "member-logging"));
if (mlogchannel) {
console.log(client.users.find(user => user.id === member.id).createdAt())
var cdate = moment.utc(User.createdAt()).format("dddd, MMMM Do YYYY, HH:mm");
const sInfo = new Discord.RichEmbed()
.setTitle(`Member joined`)
.setAuthor(`${member.displayName}`)
.setColor(8528115)
.setFooter(`User ID: ${member.id}`)
.setTimestamp()
.setThumbnail(member.user.createdAt())
.addField("Total members", `${Guild.members.filter(member => !member.user.bot).size}`, true)
.addField("Creation Date:", `${cdate}`, true);
let ageS = moment(cdate).fromNow(true)
let ageA = ageS.split(" ");
if (ageA[1] = "days" && ageA[2] >= 30) {
Guild.channels.find((channel => channel.name === "member-logging").send(sInfo));
mlogchannel.send("**WARNING!**\nThis account is less than 30 days old and may have been made to bypass a server mute or ban!")
}
if (ageA[1] != "days") {
mlogchannel.send(sInfo)
}
if (!mlogchannel) {
return console.log(`${Guild.name}:${Guild.ID} Has not set up a member log channel!`)
}
}
})
User.createdAt is a property of User, not a method. So instead of .setThumbnail(member.user.createdAt()), it would be .setThumbnail(member.user.createdAt).
Related
I am working on a React Js, Firebase BIRTHDAYS web app which allows login using firebase. Users can add their friends birthdays in there. It will show the personalized list of birthdays.
So, Here I want to send notifications every day at some specific time for all the users using Firebase Cloud Messaging. And also the body of it should be different for every user and should contain the list of birthdays they are having that day(when the notification is sent) from Firebase Database. I tried a lot. But none of them worked. Is there a way that I can achieve this?
Thanks.
Things I tried
Used only React to send notification. But the problem here is that we should not close the web app and for Mobiles addEventListener("visibilitychange", () => {}) is not working.
let notification
let interval
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
let date = new Date()
let dateNumber = date.getDate()
let monthId = date.getMonth() + 1
let hours = date.getHours()
let minutes = date.getMinutes()
if (hours === 0) {
let requiredNames = []
if (allBirthdays.length !== 0) {
requiredNames = allBirthdays
.filter((p) => p.monthId == monthId && p.day == dateNumber)
.map((p) => {
return `${p.name}`;
})
}
notification = new Notification(`Today's Birthdays(${dateNumber}-${monthId})`, {
body: `${requiredNames.length !== 0 ? requiredNames : "No Birthdays"}`,
icon: logo,
tag: "Same Time"
})
}
interval = setInterval(() => {
date = new Date()
dateNumber = date.getDate()
monthId = date.getMonth() + 1
hours = date.getHours()
minutes = date.getMinutes()
if (hours === 0 && minutes < 15) {
let requiredNames = []
if (allBirthdays.length !== 0) {
requiredNames = allBirthdays
.filter((p) => p.monthId == monthId && p.day == dateNumber)
.map((p) => {
return `${p.name}`;
})
}
notification = new Notification(`Today's Birthdays(${dateNumber}-${monthId})`, {
body: `${requiredNames.length !== 0 ? requiredNames : "No Birthdays"}`,
icon: logo,
tag: "Next Interval"
})
}
}, 900000);
} else {
if (interval) clearInterval(interval)
if (notification) notification.close()
}
})
I found some videos on it but all explain only till we Test push notification from firebase but not the real-time implementation.
FCM basically just a service that you can send message from server to client no matter app is in background or terminated. The server need to know which device you want to deliver.
The way can achive this is:
Register all users token to server
Setup a scheduled cloud functions for run once per day
Run query from rtdb to get which users friend today is his birthday, Also grab these users token then deliver message to device.
So i am trying to make a command that mute a member. I want my bot to check if there is role name Muted and if there is not, to create a role for Muted members.
This is the code:
module.exports = {
name: 'mute',
description: 'mutes a member',
execute(message, args, Discord, bot) {
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted')
if(!mutedRole) {
Guild.roles.create({
data: {
name: 'Muted',
color: 'BLACK'
}
})
}
}
}
and the error is this:
C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\mute.js:10
Guild.roles.create({
^
TypeError: Cannot read property 'create' of undefined
I don't think you should create a role via code. I think you should create a role in your Discord server (like actually just making one without code). Download the ms package. (npm i ms) Then, paste this code in:
const ms = require('ms');
module.exports = {
name: "mute",
description: "Mutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
if (!args[1]){
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted.`);
return;
}
if (isNaN(args[1]) || !args[1] === ' '){
message.channel.send("Please enter a real number! (If you have a space after the username and you don\'t want to set a time limit, delete the space. YOU HAVE TO.)");
return;
}
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
setTimeout(function(){
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
}, ms(args[1]));
} else {
message.channel.send("Can't find that member!");
}
}
}
Thanks to CodeLyon for this code. Hope this works for you! It even includes a time limit.
format 1: !mute #User
format 2: !mute #User 1000 (1000 can be changed, just make sure it's in milliseconds)
module.exports = {
name: "unmute",
description: "Unmutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unmuted.`);
} else {
message.channel.send("Can't find that member!");
}
}
}
format: !unmute #User
Remember, this code only works if you have a role Member and a role Muted. So, in your server, add the role Member to everybody and add a role Muted (not to everybody).
Hope this works! If there's any need for clarification, please tell me in the comments.
Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.
I am creating a role reaction bot and I want that if a member has already clicked on a reaction and clicks another it removes the previous one and the role associated with it and gives him the role that corresponds to the last one clicked (there are 15 reactions available) , I was writing code similar to this:
let msg = reaction.message;
let msgGuild = msg.guild;
let userGuild = msgGuild.members.cache.get(user.id);
let userRole = userGuild.roles;
if(reaction.message.channel.id === "764148072498200589") {
if(reaction.emoji.name === "RedRoleID") {
if(userRole.cache.has("BaseRoleID")) {
userRole.remove("BaseRoleID");
userRole.add("RedRoleID");
} else if(userRole.cache.has("OrangeRoleID")) {
userRole.remove("OrangeRoleID");
userRole.add("RedRoleID");
}
};
};
is there an easier and shorter way to do what I want without creating an else if for each role?
I think you could probably make an array of all the emoji names, then use Array.prototype.forEach to check all of them.
let { emoji, message, message: { guild, channel }} = reaction;
let { roles } = guild.member(user.id);
const emojis = ['BaseRoleID', 'RedRoleID', 'OrangeRoleID', 'etc'];
if (channel.id === '764148072498200589') {
emojis.forEach((id) => (roles.cache.has(id) ? roles.remove(id) : id));
roles.add(emoji.name);
}
Edit: My mistake, I thought you had named the emojis as the corresponding role IDs. Here's an alternate method if you do not want to do that:
let { emoji, message, message: { guild, channel }} = reaction;
let { roles } = guild.member(user.id);
const emojis = [
{ emote: 'EmojiID', role: 'RoleID' },
'continue this pattern for all roles and emotes'
];
if (channel.id === '764148072498200589') {
emojis.forEach(({ emote, role }) => {
if (roles.cache.has(role))
return roles.remove(role)
if (emoji.id === emote) roles.add(role)
});
};
I want to set guild icon as the thumbnail of embed but neither guild.icon nor guild.iconURL() work
bot.on('message', message => {
if(message.author.bot) return;
if(message.channel.name === 'verify') {
if(message.content === '!verify') {
message.delete()
let dm = message.author;
let server = message.guild.name;
let servericon = message.guild.iconURL();
console.log(servericon)
let attachment = new Discord.MessageAttachment(this.choose , 'chosen.png')
let embed = new Discord.MessageEmbed()
.setTitle(`**Welcome to ${server}**\n\nCaptcha`)
.setDescription("Please complete the captcha given below to gain access to the server.\n**Note:** This is case sensitive")
.setAuthor('Mr.Verifier', "https://i.ibb.co/nckjDjG/hmm.png")
.setThumbnail(servericon)
.addField(
{ name: '**Why all this?**', value: 'This is to protect the servers from\nmalicious raids of automated bots'}
)
.setImage(`attachment://chosen.png`)
dm.send(embed)
}else{
message.delete();
}
};
})
You need to use guild.iconURL().