How to set the name of a channel from the guildMemberAdd event? - discord

I am trying to make a voice channel which displays the number of members on my server, however I can't seem to be able to get the ID of the channel to change it. I have this code in the guildMemberAdd event:
bot.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(ch => ch.name === 'factions');
channel.send(`Welcome to the server, <#${member.id}>! Make sure to check out <#757221255198802051> and <#757221255198802051>!`);
const serverCount = (bot.guilds.cache.get(member.guild.id).memberCount);
member.guild.channels.find(ch => ch.name === "Server Count:").setName(`Server Count: ${serverCount}`);
});
This all works apart from the last line because member.guild.channels.find is not a function. I know that I need to do channel.setName but I am not sure how to get the channel to set the name of from the member object that is passed into the guildMemberAdd event.

You forgot 2 things, cache and the startsWith() function. To fix your problem:
bot.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(ch => ch.name === 'factions');
channel.send(`Welcome to the server, <#${member.id}>! Make sure to check out <#757221255198802051> and <#757221255198802051>!`);
const serverCount = member.guild.memberCount;
member.guild.channels.cache.find(ch => ch.name.startsWith("Server Count: ")).setName(`Server Count: ${serverCount}`);
});

Related

Discord.js Filter Discord Events From Only 1 Server

I am working on trying to filter events for only 1 server rather than all servers the bot is in, but I'm trying to figure out how to exactly save each guild the bot is in as an collection so I can just filter events based on a guild ID I desire. Is this even possible? This is a snippet of the code I have to date, it's able to display the server names and ID's the bot is currently in, the events are working properly but triggering for all servers rather than the one I desire, how would I go about filtering for one guild collection?
const Discord = require('discord.js')
const bot = new Discord.Client()
const config = require('./config.json')
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
//Sets Activity
//client.user.setStatus('invisible')
bot.user.setActivity("Discord Cooks", { type: "WATCHING"})
console.log("Set User Activity!");
//Online Webhook
const webhookClient = new Discord.WebhookClient('','');
const embed = new Discord.MessageEmbed()
.setTitle(`${bot.user.tag} is online`)
.setColor('#FFFF00')
.setTimestamp()
webhookClient.send(embed);
bot.guilds.cache.forEach((guild) => {
console.log(guild.name, guild.id);
});
});
bot.on("channelCreate", (channel) => {
console.log(`channelCreate: ID: ${channel.id} Name: ${channel.name}`);
});
bot.on("channelUpdate", (oldChannel, newChannel) => {
console.log(`channelUpdate -> ${oldChannel.name} to ${newChannel.name}`);
});
bot.on("channelDelete", (channel) => {
console.log(`channelDelete: ID: ${channel.id} Name: ${channel.name}`);
});
bot.login(config.bottoken)
You can only execute code if event happened on exact server in much easier way:
if(guild.id == "GUILD_ID") {
// code
}
Also as #MrMythical said, you can just use if (message.guild.id !== "GUILD_ID") return; if you only need to run your code for 1 guild!

event channelCreate .setauthor

is there any way to put the user who created the channel in .setAuthor? I searched in https://discord.js.org/#/docs/main/stable/class/GuildChannel but found nothing
client.on("channelCreate", function(channel) {
const logchannel = channel.guild.channels.cache.find(ch => ch.name === "logchannel")
if (!logchannel) return
const embed = new Discord.MessageEmbed()
.setTitle("Channel created)
.setDescription(`Channel <#${channel.id}> has created.`)
.setTimestamp()
.setAuthor(//user who created the channel)
logchannel.send(embed)
})
I think it's best to use the AuditLogs, you may want to take a look at it.

Leave message discord.js v12

I have a porblem. My leave message. There I have:
client.on("guildMemberAdd", member => {
const welcomeChannel = member.guild.channels.cache.find(
channel => channel.name === "welcome"
);
welcomeChannel.send(`Hosgeldin :heart: ${member}`);
});
client.on("guildMemberRemove", member => {
const welcomeChannel = member.guild.channels.cache.find(
channel => channel.name === "gelen-giden"
);
welcomeChannel.send(`Bye ${member}!`);
});
and then when somebody left then came <#id>.
I want to find his id because then I can make an link of the person who left.
It look like https://discordapp.com/users/732569703142129685 .
And then it should write 'Member' and this 'member' should be the link.
Please in v12.
Discord returns <#id> because the member that left doesn't have more guilds(servers) in common with you and he is no more in your cache. If you need his id for some deletion of rows in db you can get it as member.id
When a user leaves, he is no longer on the guild, so you can't find a channel on a server he isn't anymore in. You'll need to use client.channels.cache.find() in this case.
have a good day.

Discord.js How can I edit previous bot's message?

so I am trying to make a ROSTER command. The command is $roster add/remove #user RANK. This command basically should edit a previous bot's message (roster) and add a user to the roster to the RANK in the command... This is my code so far, but I haven't managed to make the roster message and the editing part of it and the RANK system. If someone could help that would be very amazing!
//ROOSTER COMMAND
client.on('message', async message => {
if (message.content.startsWith(prefix + "roster")) {
if (!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
const args = message.content.slice(prefix.length + 7).split(/ +/)
let uReply = args[0];
const user = message.mentions.members.first()
if(!uReply) message.channel.send("Please use `add` or `remove`.")
if(uReply === 'add') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are adding **${user.displayName}** from the roster.`)
} else if(uReply === 'remove') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are removing **${user.displayName}** from the roster.`)
}
}})
Sounds like the .edit() method is what you want.
Example from the docs:
// Update the content of a message
message.edit('This is my new content!')
.then(msg => console.log(`Updated the content of a message to ${msg.content}`))
.catch(console.error);
To edit your bots previous message, you need to have a reference of the message you want to edit. The returned reference is a promise so do not forget to use await keyword. you can then use .edit() function on the reference to update you msg.
const msgRef = await msg.channel.send("Hello");
msgRef.edit("Bye");

Creating an invite in a GuildCreate event

So I was trying to make my bot send me a DM to every server it joins but I keep getting the API error: Unkown Channel
My code:
bot.on("guildCreate", async guild => {
guild.channels.first().createInvite().then(inv =>
bot.users.get(ownerID).send(`I have been added to **${guild.name}** | ${inv.url}`)
)
});
Okay, this is your problem. I have made the same mistake a few months ago, here's how to fix it.
Since you are using discord.js version 11, guild.channels is indeed a Collection, which you can use .first() on. In this case, you can't do that.
Here's my workaround:
bot.on("guildCreate", async guild => {
var channel;
guild.channels.forEach(c => {
if (c.type === "text" && !channel) channel = c;
});
channel.createInvite({ maxAge: 0 }).then(inv => bot.users.get(ownerID).send(`I have been added to **${guild.name}** | https://discord.gg/${inv.code}`));
});
This basically loops through each channel and finds a valid TextChannel to create an invite.
Hope this helps.

Resources