JS Discord Bot Get Role - javascript

I'm trying to get a role without using messages, like:
const Discord = require('discord.js');
const Bot = new Discord.Client();
const Role = Discord.roles.find('name,'Exemple')
Role.delete()
Is this possible to do that?

Using that way of Collection#find("key", "value") in Discord.JS is deprecated by the way,
You should use Collection#find(Obj => Obj.key == "value") instead.

Yes you can but you will need to have the guild id you want to get the role from. Also, you should put that part in the ready event.
const discord = require("discord.js");
const client = new discord.Client();
client.on("ready", () => {
console.log("Bot online!");
const guild = client.guilds.get("The_server_id");
const role = guild.roles.find("name", "Your_role_name");
console.log(`Found the role ${role.name}`);
})

I tried with the posted solution but client.guilds.get was not recognized as a function:
UnhandledPromiseRejectionWarning: TypeError: client.guilds.get is not a function at Client.
Checking the content of client.guilds I found 'cache' object:
GuildManager {
cacheType: [Function: Collection],
cache: Collection [Map] {
'<discord server id>' => Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
(...)
}
}
}
The solution was:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
const myGuild = client.guilds.cache.get('<discord server id>');
const myRole = myGuild.roles.cache.find(role => role.name === '<role name>');
console.log(`Found the role ${myRole.name}`);
});

Guild doesn't work unless you have it set up on the server. People keep suggesting this but you have to already have infrastructure set up in your discord server.

const role = guild.roles.cache.get('role_id');
This seems to be working in the latest API version.

To get an specific role i use this code.
Replace SERVER_ID with your server id and ROLE_NAME with the name of the role
const guild = client.guilds.cache.get("SERVER_ID");
const role = guild.roles.cache.find((r) => r.name === "ROLE_NAME");
console.log(`Found the role ${role.name}`);
console.log(`Found the role ${role.id}`);

Related

TypeError: Cannot read properties of undefined (reading 'createInvite')

Whenever I try and make an invite to one of my guild's channels, it doesn't work.
const {
Client
} = require("discord.js");
const client = new Client({ intents: [] });
client.on("ready", async () => {
console.log(`Bot ${client.user.username} is ready`);
const guild = client.guilds.cache.first()
await guild.channels.cache
.filter(channel => channel.type === "text")
.first()
.createInvite()
.then((invite) => console.log('Server: ' + invite.code))
})
client.login(process.env.TOKEN);
I get the title error and I don't understand why it wont work as I'm getting a channel and I'm creating an invite. Thanks
The error likely lies in you filtering the guild's channels. text is not a valid channel type.
https://discord.js.org/#/docs/main/stable/typedef/ChannelType
Check the ChannelType documentation for your corresponding discord.js version.
Fixed my own question:
const {
Client
} = require("discord.js");
const client = new Client({ intents: [] });
client.on("ready", async () => {
console.log(`Bot ${client.user.username} is ready`);
try {
var channel = await client.channels.fetch('1056353927471308802');
var invite = await channel.createInvite()
console.log(`https://discord.gg/${invite.code}`)
} catch {
throw new Error(`Channel with ID ${sendChannel} not found`);
}
})
client.login(process.env.TOKEN);

How do I get the bot to write user's name

This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.

TypeError: Cannot read property 'roles' of undefined in discord.js

I am trying to get the bot to add roles in one discord and also add a role in another discord. but I keep getting the "roles" is not defined error. I have little to no coding knowledge and most of my code is a combination of things I find on google or friends teach me, so please excuse me if it is a dumb problem with a simple solution.
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.GUILD_ROLES] });
module.exports = {
name: 'accept',
description: 'Adds A Player To The Whitelist',
permissions: `ADMINISTRATOR`,
execute(message, args, add, roles, addRole, guild) {
message.delete()
let rMember = guild.roles.cache
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role1 =
message.guild.roles.cache.find((r) => r.id == roleID)
let role2 =
message.guild.roles.cache.find((r) => r.id == roleID)
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
rMember.roles.add(role1).catch((e) => console.log(e));
rMember.roles.add(role2).catch((e) => console.log(e));
rMember.roles.add(memberRole).catch((e) => console.log(e));
rMember.send(`message content`);
message.channel.send('message content')
}};
The error occurs in this line:
let memberRole = server.guild.roles.get("872432775330955264");
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
These particular lines justify your error, in the first case you are assigning the property of a guild object to server by getting the guild from the cache, now you see a guild object does not have a property further named guild to it so your error actually rests in the next line, where you are trying to get from server.guild it's same as saying guild.guild which makes no actual sense.
Only correction you would want to make with your code would be something of this sort:
let server = client.guilds.cache.get('guild ID')
let memberRole = server.roles.cache.get("role ID");

How do i make my discord bot respond to a message with prefix?

What I'm trying to do is set up a discord autoresponse bot that responds if someone says match prefix + respondobject like "!ping". I don't know why it doesn't come up with any response in the dispute. I've attached a picture of what it does. I can't figure out why it's not showing up with any responses in discord.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = '!'
client.on('ready', () => {
let botStatus = [
'up!h or up!help',
`${client.users.cache.size} citizens!`,
`${client.guilds.cache.size} servers!`
]
setInterval(function(){
let status = botStatus[Math.floor(Math.random() * botStatus.length)]
client.user.setActivity(status, {type: 'WATCHING'})
}, 15000);
console.log(client.user.username);
});
client.on('message', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return
const args = message.content.slice(prefix.length).split(/ +/)
const command = args.shift().toLowerCase()
const responseObject = {
"ping": `🏓 Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`
};
if (responseObject[message.content]) {
message.channel.send('Loading data...').then (async (msg) =>{
msg.delete()
message.channel.send(responseObject[message.content]);
}).catch(err => console.log(err.message))
}
});
client.login(process.env.token);
Your main issue is that you're trying to check message.content against 'ping', but require a prefix. Your message.content will always have a prefix, so you could try if (responseObject[message.content.slice(prefix.length)]).
Other alternatives would be to add the prefix to the object ("!ping": "Latency is...")
Or, create a variable that tracks the command used.
let cmd = message.content.toLowerCase().slice(prefix.length).split(/\s+/gm)[0]
// then use it to check the object
if (responseObject[cmd]) {}

I have the TypeError: Cannot read property 'toString' of undefined

I'm making a discord welcomer bot and there's a problem where when someone joins the server it sends this error:
TypeError: Cannot read property 'toString' of undefined
Here is the source code:
module.exports = (client) => {
const channelid = "865471665168580628";
client.on("guildMemberAdd", (member) => {
const serverid = member.guild.id
const guild = client.guilds.cache.get(serverid);
console.log("member");
const ruleschannel = guild.channels.cache.find(channel => channel.name === "rules");
const message = `welcome <#${member.id}> to music and chill! please read the ${member.guild.channels.cache.get(ruleschannel).toString()} before you start chatting.`;
const channel = member.guild.channels.cache.get(channelid);
channel.send(message);
})
}
Can someone please help me?
It means member.guild.channels.cache.get(ruleschannel) is undefined. As ruleschannel is a channel object, and the Collection#get() method needs a snowflake, you need to use its id property.
So member.guild.channels.cache.get(ruleschannel.id) should work.
A better way would be to check if the ruleschannel exists though. Also, you can just simply add rulesChannel inside the backticks and it gets converted to a channel link. Check out the code below:
client.on('guildMemberAdd', (member) => {
// not sure why not just: const { guild } = member
const guild = client.guilds.cache.get(member.guild.id);
const rulesChannel = guild.channels.cache.find((channel) => channel.name === 'rules');
if (!rulesChannel)
return console.log(`Can't find a channel named "rules"`);
const channel = guild.channels.cache.get(channelid);
const message = `Welcome <#${member.id}> to music and chill! Please, read the ${rulesChannel}.`;
channel.send(message);
});

Categories

Resources