can someone help me fix this script? - javascript

const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
var role = member.guild.roles.find("ID", "here I put the role id");
member.addRole(role);
});
This script is giving error and I don't know how to fix it. The error is:
member.guild.roles.find is not a function

discord.js v12+ uses Managers, so you will have to add the cache property.
Replace:
var role = member.guild.roles.find("ID", "here I put the role id");
with:
var role = member.guild.roles.cache.find(role => role.id === 'ID Here')
An even easier way to do it is with the .get() method:
var role = member.guild.roles.cache.get("ID Here")
Although either would work.
Since discord.js v12+, the addRole() method is also deprecated. Instead, replace it with:
member.roles.add(role)

Please consider reading on the Discord.js v12 docs regarding adding roles to members here
Things in the cache are now found directly on the cache
and members/roles/users/channels are all found on the cache, sooo
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
var role = member.guild.roles.cache.find(role => role.id == "ROLE ID HERE");
member.roles.add(role.id);
});

Hi #Joaozwy (Brazilian like me or not? :)
First things first. Why you are receiving this error?
The event "guildMemberAdd" from Discord.Client send the member object as a parameter.
It has the guild property which has the property roles.
But member.guild.roles which is from type RoleManager doesn't have the method find.
That's why it's giving you the error you are receiving.
Now, It seems to me, with the available information you gave us, you are trying to get the role by it's ID and add to the member.
If that's the case, try this:
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("guildMemberAdd", member =>{
let role = member.guild.roles.cache.find(role => role.id === "here I put the role id");
member.roles.add(role, "Optional string saying why are you adding this role to the member");
});
Remember to change the string "here I put the role id" to the string with the correct role ID you wanna add to the user.
Also, the add method returns a Promise. Its a good practice to, at least, listen for errors or rejections on promises so if something goes wrong, you can know why.

Related

Why doesn't my discord.js bot reply to messages? [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed 4 months ago.
So my code is this:
const { GatewayIntentBits } = require('discord.js');
const Discord = require('discord.js');
const token = 'My Token';
const client = new Discord.Client({
intents:
[
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
});
client.on('ready', () =>
{
console.log("Bot is on");
});
client.on('message', (message) =>
{
const channel = client.channels.get("1028177045773094915")
if (message.content === 'ping')
{
channel.send("pong")
}
});
// This is always the end
client.login(token);
I don't know why it is not working, it's in online but when I type anything in channel it doesnt do anything.
There are a few errors with this.
Before I get into the more complicated stuff, please know that the message event doesn't work -- use messageCreate.
The second smaller thing that I need to point out is that you don't have the MessageContent Intent enabled; that needs to be enabled for you to detect the text/attachments of a message that isn't a Direct Message to the bot, and doesn't ping/mention the bot.
Now, for the bigger stuff.
client.channels.get() isn't a function, and that's because of the Channel Cache.
I'll try my best to break down what a Cache is, but I'm not too good with this, so someone can correct me below.
A cache is similar to a pocket; when someone (being discord.js) looks inside of your pocket (the cache), that someone can only see the items inside of the pocket. It can't detect what isn't there. That's what the cache is. It's the inside of the pocket, and holds the things that you want discord.js to see.
If your item isn't in the cache, discord.js won't use it. But, you can get discord.js to look for that item elsewhere, and put it into that pocket for later.
This is the .fetch() method. It puts something that isn't in the cache, well, in the cache.
An example of using it:
const channel = await client.channels.fetch("CHANNEL_ID");
Or, what I'd call the more "traditional" way of doing it:
client.channels.fetch("CHANNEL_ID").then(channel => {
});
Now, after fetching your channel, you can call it like this:
client.channels.cache.get("CHANNEL_ID");
Another fun thing about the .fetch() method is that you can use it to shove everything in the cache, though it isn't necessary in most cases.
client.channels.fetch();
That will fetch every channel that the bot can see.
client.guilds.fetch();
That will fetch every guild the bot is in.
guild.members.fetch();
That will fetch every guild member of a guild.
And so on.
After Everything
After applying everything that I've said previously, you should wind up with code that looks like this:
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent // Make sure this is enabled in discord.com/developers/applications!
]
});
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase() === "ping") {
// I added the .toLowerCase() method so that you can do PING and it works.
client.channels.fetch("1028177045773094915").then(channel => {
channel.send({ content: "pong!" });
});
}
});
client.login("Your Token");

Sending message to specific channel in discord.js

I want to send a message to a specific channel but it doesn't work, I've tried
client.guilds.cache.get("<id>").send("<msg>")
but I get the error ".send is not a function".
What am I missing here?
There are three ways of sending message to a specific channel.
1. Using a fetch method
const channel = await <client>.channels.fetch('channelID')
channel.send({content: "Example Message"})
2. Using a get method
const channel = await <client>.channels.cache.get('channelID')
channel.send({content: "Example Message"})
3. Using a find method
a.
const channel = await <client>.channels.cache.find(channel => channel.id === "channelID")
channel.send({content: "Example Message"})
b.
const channel = await <client>.channels.cache.find(channel => channel.name === "channelName")
channel.send({content: "Example Message})
Your current code line is getting the GUILD_ID not the CHANNEL_ID.
You are trying to get from the cache a Guild not a Channel, or more specifically a TextChannel, that's why what you try is not working, you should try to change the code to something like this and it should work.
const channel = client.channels.cache.get('Channel Id');
channel.send({ content: 'This is a message' });
Also, as something extra, I would recommend using the fetch method for these things, since it checks the bot's cache and in the case of not finding the requested object it sends a request to the api, but it depends on the final use if you need it or not.
const channel = await client.channels.fetch('Channel Id');
channel.send({ content: 'This is a message' });

message channel name returning an undefined

Hi I'm trying to get the channel name of a channel I've created. however, I'm getting undefined as if the channel I created does not exist, which it does.
Here is my code:
const new_channel = message.guild.channels.create("New Name").then((channel) => {
channel.setParent(categoryId)
channel.setTopic(topic)
})
message.channel.send(`Ticket created in ${new_channel}`);
What I'm doing wrong here?
new_channel is NOT the GuildChannel you just created. It is a Promise<GuildChannel>. In other words, it is "promising" that it can deliver you a text channel, and will deliver it to you once the channel has been created via .then.
Basically, creating a text channel in Discord takes some time. Discord.js has to send a request to the Discord API, wait for Discord to create the channel, and then get the Discord API's response. Only then will Discord.js give you the data for the text channel you created. Hence why we use .then(); once the channel has been created, only then will the code inside .then() be executed.
As for why new_channel is undefined, it may be because you are not returning a value in your .then(). Therefore, there is nothing further to promise.
So the solution to your problem is to reference the actual variable that contains the created channel; the channel parameter passed into your .then(). Here is an example:
const new_channel = message.guild.channels.create("New Name").then((channel) => {
channel.setParent(categoryId);
channel.setTopic(topic);
message.channel.send(`Ticket created in ${channel.name}`);
})
As you can see, your code was already setting the parent and topic of channel, not new_channel. So it logically makes sense that the name of the channel is also in channel, not new_channel.
It's best to reference the channel ID of the channel created instead of the object when sending a message. See the example below.
Example:
let guild = await client.guilds.fetch(message.guild.id);
let newChannel = await guild.channels.create("name");
newChannel.setParent("catagory-id");
newChannel.setTopic("The topic of the channel");
message.channel.send(`<#!${message.author.id}> Your ticket was created in <#!${newChannel.id}>`);
Full Example:
let Discord = require('discord.js');
let client = new Discord.Client();
client.on('messageCreate', async function(message) {
// Do something
let guild = await client.guilds.fetch(message.guild.id);
let newChannel = await guild.channels.create("name");
newChannel.setParent("catagory-id");
newChannel.setTopic("The topic of the channel");
message.channel.send(`<#!${message.author.id}> Your ticket was created in <#!${newChannel.id}>`);
});
client.login('your-token');

Delete existing categories and channels and make new ones(discord.js)?

I need some help with a code in discord.js where I delete the existing categories and channels and then make new ones. My code edits the icon and guild name so now I'm moving onto channels and whatnot. No, this is not a nuker, I'm trying to make a server rebuilder or remodeler and things similar to that. Anyways, here is my code and by the bottom is where I'd like to implement the channel deleting and replacing.
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token } = require('./config.json');
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
client.on("message", async (message) => {
if (message.content == "server") {
try {
await message.guild.setIcon("./icon.png");
await message.guild.setName("server");
message.channel.send("Successfully made server.");
} catch {
message.channel.send("Unknown error occurred while making server.");
}
}
});
If anyone could help with this, please let me know.
Your question is too broad, you should try to narrow it to something specific that you are having issues with, like #Skulaurun Mrusal told you to. However, I can give you some tips on where to start:
You can access a <Guild>'s <GuildChannelManager> - a class that gives you some ways of managing the guild channels, such as deleting or creating them - through <Guild>.channels.
If you'd like to delete a channel from this <Guild> you would do <Guild>.cache.channels.find(channel => channel.name === 'channel-name').delete()
While if you wanted to create one, you would do: <Guild>.channels.create(...).
Don't forget you need the MANAGE_CHANNELS permission to do such operations. I hope this can help you out.

I need help making my bot dm me not the author of the command

So I have a main.js that already does the see what the command is so it knows im trying to do !report and is able to say text. I've also gotten it to dm the user who sent it - but not to dm me. (this is set up like the rest of my commands however those are just making the bot talk basically) The goal being it will tell me if someone needs help and I can just dm them to ask about what is going on. (I removed my ID and replace it with "My ID")
const Discord = require('discord.js');
const client = new Discord.Client();
const BluntSam = client.users.cache.get('My ID');
module.exports = {
name: 'report',
description: "Report a problem with this bot, channel, or people.",
execute(message, args){
if (message.toString().toLowerCase().includes('report')) {
message.author.send('Your report request has been sent. Please wait for a response from <#My ID>.');
message.author.send(message.author + ' has requested an assistance ticket.')
}
}
}
Get your user. Use an async function or IIFE for this.
Message it.
(async () => {
let me = await client.users.fetch('YOUR-USER-ID');
me.send('some message');
})();

Categories

Resources