Im finding myself stuck with defining the "channel" and i keep getting channel not defind im definetly
new to JS but i thought i covered defining could someone help me out here ive tried to define it with a var channel = , and a let channel but cant seem to get any to work.
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
newUsers.set(member.id, member.user);
if (newUsers.size > 1) {
const defaultChannel = guild.channels.find(channel => channel.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Welcome to the server!\n" + userlist);
newUsers.clear();
}
});
That repo you are using is not updated. Try with this
const defaultChannel = guild.channels.cache.find(channel => channel.name === "NAME");
Related
I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.
According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.
The whole command looks like this:
client.on('messageCreate', (message) => {
if (
message.content.toLowerCase() === prefix + 'test' &&
GuildMemberRoleManager.cache.has(AdminRole)
)
message.reply('test');
});
You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).
Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:
client.on('messageCreate', (message) => {
let adminRole = 'ADMIN_ROLE';
let isAdmin = message.member.roles.cache.has(adminRole);
if (message.content.toLowerCase() === prefix + 'test' && isAdmin)
message.reply('test');
});
Define the variables which will make you easy to understand as you are new
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
and make if statement like
if(member.roles.cache.has(role.id)) {
return message.channel.send("test")
}
if you want bot to check if user have administrator perm than
message.member.hasPermission('ADMINISTRATOR')
Check all perm flags on Discord Perm Flags
So according to your code it will be
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
client.on("messageCreate",(message) => {
if(message.content.toLowerCase() === prefix + "test" && member.roles.cache.has(role.id))
message.reply("test")
})
I'm trying to make an autorole code using quick.db, but it returns the error: UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes
My "setautorole" command:
const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0])
if(!role) return message.channel.send('I couldnt find the role')
db.set(`autorole`, role)
message.channel.send('The process worked fine!')
This is on index of bot:
client.on("guildMemberAdd", (member) => {
let few = db.get(`autorole_${member.guild.id}`)
if(few === null) return;
member.roles.add(few)
})
Well, I don't know what to do to fix this error, I need a little help
It's better just to save the role ID in Database
BTW you're doing it all wrong. It should be like
setautorole.js
const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0]);
if(!role){
return( message.channel.send('I couldnt find the role') );
}
db.set(`autorole_${message.guild.id}`, role.id);
message.channel.send('The process worked fine!');
index.js
client.on("guildMemberAdd", (member) => {
let roleID = db.get(`autorole_${member.guild.id}`)
if(!roleID) return;
role = member.guild.roles.find(roleID);
if(!role){
console.log("That role dosen't exist");
return (false);
}
member.roles.add(role)
})
Thanks for the idea Akio, but, i i did something like:
client.on("guildMemberAdd", (member) => {
let roleID = db.get(`autorole_${member.guild.id}`)
if(!roleID) return;
let role = member.guild.roles.cache.find(r => r.id === roleID);
if(!role){
console.log("That role dosen't exist");
return (false);
}
member.roles.add(role)
})
and worked, thanks for help :)
client.on("roleCreate", role => {
const channel = role.guild.channels.cache.find(ch => ch.name === "welcome");
const embed = new Discord.MessageEmbed()
.setColor("DEFAULT")
.setDescription(`A new role has been created\nPermissions List: ${role.permissions}`)
channel.send(embed)
});
I am trying out different events from the Discord.JS Docs, however, when I came across the roleCreate event, I tried it out and when I create a new role, it works. But for the role.permissions; I am not quite sure why I'm getting [object Object]. How could I possibly fix this?
Discord.JS: v12.2.0
That's because role.permissions is an object:
https://discord.js.org/#/docs/main/stable/class/Permissions
Use the .toArray() method combined with join():
client.on("roleCreate", role => {
const channel = role.guild.channels.cache.find(ch => ch.name === "welcome");
const perms = role.permissions.toArray().join("\n");
const embed = new Discord.MessageEmbed()
.setColor("DEFAULT")
.setDescription(`A new role has been created\nPermissions List:\n${perms}`)
channel.send(embed)
});
To get it from CREATE_INSTANT_INVITE into Create Instant Invite
const perms = role.permissions.toArray().map(e => {
const words = e.split("_").map(x => x[0] + x.slice(1).toLowerCase());
return words.join(" ");
}).join("\n");
I have an avatar command in my discord bot. When the user uses h.avatar, it outputs their avatar, which works fine. Whenever they try to use h.avatar #user, nothing happens.
Here is my code:
} if (message.content.startsWith(config.prefix + "avatar")) {
if (!message.mentions.users.size) {
const avatarAuthor = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(message.author.username)
.setImage(message.author.avatarURL)
message.channel.send(avatarAuthor);
let mention = message.mentions.members.first();
const avatarMention = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(mention.user.username)
.setImage(mention.user.avatarURL)
message.channel.send(avatarMention);
You have a check if (!message.mentions.users.size) { which makes the command run only if you do not mention somebody. You either need to use an else { in your code or do:
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = message.mentions.users.first() || message.author;
const avatarEmbed = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(user.username)
.setImage(user.avatarURL);
message.channel.send(avatarEmbed);
}
The const user = message.mentions.users.first() || message.author; tries to get the user that was mentioned but if it does not find anyone it will use the author's used.
This can also be used like this:
if (!message.mentions.users.size) {
message.channel.send('Nobody was mentioned');
return;
}
// continue command here, after guard clause
There's nothing like avatarUrl unless you have defined it.
Use this code to get the url of a user:
message.channel.send("https://cdn.discordapp.com/avatars/"+message.author.id+"/"+message.author.avatar+".jpeg");
Just replacemessage.author with the user who is mentioned
These is the updated version of the answer that works
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor(0x333333)
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.lineReply(avatarEmbed);
}
This uses discord's avatar url, and msg.lineReply(avatarEmbed); is a function that sends the embed as a reply to the message
My
if (msg.content.startsWith(prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor('')
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.reply(avatarEmbed);
}
if(message.content.startsWith(prefix+'av')){
if(message.mentions.users.size){
let member=message.mentions.users.first()
if(member){
const emb=new Discord.MessageEmbed().setImage(member.displayAvatarURL()).setTitle(member.username)
message.channel.send(emb)
}
else{
message.channel.send("Sorry none found with that name")
}
}else{
const emb=new Discord.MessageEmbed().setImage(message.author.displayAvatarURL()).setTitle(message.author.username)
message.channel.send(emb)
}
}
if (message.content.startsWith(prefix + 'avatar')) {
let user = message.mentions.users.first();
if(!user) user = message.author;
let color = message.member.displayHexColor;
if (color == '#000000') color = message.member.hoistRole.hexColor;
const embed = new Discord.RichEmbed()
.setImage(user.avatarURL)
.setColor(color)
message.channel.send({embed});
}
I have the following code:
("...............🚗......").then(sentMessage => sentMessage.edit("............🚗.........")).then(sentMessage => sentMessage.edit("........🚗............")).then(sentMessage => sentMessage.edit(".....🚗...............")).then(sentMessage => sentMessage.edit("..🚗..................")).then(sentMessage => sentMessage.edit("🚗....................")).then(sentMessage => sentMessage.edit("😮....🚗..............")).then(sentMessage => sentMessage.edit(".😧..🚗......................")).then(sentMessage => sentMessage.edit("..:tired_face:.:red_car:......................")).then(sentMessage => sentMessage.edit("...:ghost::red_car:......................")
How can I put this into a discord.js embed with the following code:
message.channel.send({
"embed": {
"title": "Car",
"description": - i want the above code to be here -,
"color": 16763981,
"footer": {
"text": "Have a fun ride!"
}
}
})
}
Is this possible in discord.js? If so, please help me out! Have no clue how to achieve this.
:) Will
I don't know what exactly you are trying to do. I guess what you made is an animation, if not, and you just want to print litterally this piece of code in your embed, just put this piece of code inside backticks
description: `("...............🚗......")
.then(sentMessage => sentMessage.edit("............🚗........."))
.then(sentMessage => sentMessage.edit("........🚗............"))
.then(sentMessage => sentMessage.edit(".....🚗..............."))
.then(sentMessage => sentMessage.edit("..🚗.................."))
.then(sentMessage => sentMessage.edit("🚗...................."))
.then(sentMessage => sentMessage.edit("😮....🚗.............."))
.then(sentMessage => sentMessage.edit(".😧..🚗......................"))
.then(sentMessage => sentMessage.edit("..:tired_face:.:red_car:......................"))
.then(sentMessage => sentMessage.edit("...:ghost::red_car:......................")`,
Then it looks like this :
If you want to make an animation, you're gonna have to use the bot to delete and rewrite the embed for each step of your animation (You can't just edit an embed if I'm not wrong)
Try to be more specific on what you really want to display
If I'm understanding you correctly, you want to send the first snippet of code into the description field and edit it, trying to make it be an animation?
I haven't tried editing an embedded message before but this is how I would go around it.
const sendCarAnimation = async (message) => {
// define the steps here
const animationSteps = [
"...............🚗......",
"............🚗.........",
"........🚗............",
".....🚗...............",
"..🚗..................",
"🚗....................",
"😮....🚗..............",
".😧..🚗......................",
"..:tired_face:.:red_car:......................",
"...:ghost::red_car:......................"
];
// generate an embed using the RichEmbed functionality
const embed = new Discord.RichEmbed()
.setTitle('Car')
.setDescription(animationSteps[0])
.setColor(16763981)
.setFooter('Have a fun ride!')
// initialize the message with the first embed
let messageState = await message.channel.send(embed);
// loop through and edit the message
let isFirst = true;
for(let currentStep of animationSteps) {
if(isFirst) {
isFirst = false;
continue;
}
embed.setDescription(currentStep);
messageState = await messageState.edit(embed);
}
}
NOTE: This will take a lot of requests to do and you will most likely get rate limited by discord for doing this. So I don't think this is a good idea. Here's their documentation on it. You can probably pull off some tricky code using the Discord.js's
client.on('rateLimit', (rateLimitInfo) => {});
event. Documentation link to this as well. Good luck!
Instead of deleting it and sending it again you can create a variable of the lastMessage (you might have to make a delay before selecting it) then do message.edit()
Got it! What I did to solve it was on startup, to grab the right channel using channel = client.user.guilds.cache.get("Guild id here").channels.cache.get("channel id"), built an embed that just said old, and then sent the embed.
I did include an array of animation steps like Emil Choparinov, and a msgProgress variable. The bot detects when a message is sent, and checks if (msg.content === ''). if true, it will set the recievedEmbed constant to msg.embeds[0].
Then, a new const, embed, is set to a new Discord.MessageEmbed, using the old embed as a starting point, and setting the title to animationSteps[msgProgress]. It then calls msg.edit(embed), and changes the msgProgress variable by 1.
There is also a client.on('messageUpdate', msg => {}), and it has the same code, except at the start, it checks if msg progress > 9, and if so, it returns. Here is the code:
require('dotenv').config();
const Discord = require('discord.js');
const client = new Discord.Client();
var channel;
const genericEmbed = new Discord.MessageEmbed()
.setTitle("old");
const animationSteps = [
"...............:red_car:......",
"............:red_car:.........",
"........:red_car:............",
".....:red_car:...............",
"..:red_car:..................",
":red_car:....................",
":open_mouth:....:red_car:..............",
".:cold_sweat:..:red_car:......................",
"..:tired_face:.:red_car:......................",
"...:ghost::red_car:......................"
];
var msgProgress = 0;
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
channel = client.guilds.cache.get("753227876207165570").channels.cache.get("753227876207165573");
console.log(channel);
const firstEmbed = new Discord.MessageEmbed()
.setTitle("old");
channel.send(firstEmbed);
});
client.on('message', msg => {
if (msg.content === '') {
console.log("good");
channel = msg.channel;
const receivedEmbed = msg.embeds[0];
const embed = new Discord.MessageEmbed(receivedEmbed)
.setTitle(animationSteps[msgProgress]);
msg.edit(embed);
msgProgress++;
}
});
client.on('messageUpdate', msg => {
if (msgProgress > 9) {
return;
}
if (msg.content === '') {
console.log("good");
channel = msg.channel;
const receivedEmbed = msg.embeds[0];
const embed = new Discord.MessageEmbed(receivedEmbed)
.setTitle(animationSteps[msgProgress]);
msg.edit(embed);
msgProgress++;
}
});
client.login(process.env.DISCORD_TOKEN);
Hope this helped! 😃