Couldn't find a channel after creating it discord.js v13 - javascript

module.exports = async (msg,arg)=>{
const guildid = msg.guild.id
const guild =msg.guild
const display = msg.guild.channels.cache.find(ch => ch.name=='Total Members')
if(!display){
try {
const channelName='Total Members'
await msg.guild.channels.create(channelName, {
type: "voice", //This create a text channel, you can make a voice one too, by changing "text" to "voice"
permissionOverwrites: [
{
id: msg.guild.roles.everyone, //To make it be seen by a certain role, user an ID instead
allow: ['VIEW_CHANNEL'], //Allow permissions
deny: [ 'SEND_MESSAGES','CONNECT'] //Deny permissions
}
],
})
msg.channel.send('Successfully created the Channel ')
}
catch (error){console.log(error)
msg.channel.send('Couldnt create one ')}
}
const display1 = await msg.guild.channels.cache.find(ch => ch.name=='Total Members')
const display1id = await msg.guild.channels.cache.get(display1.id)
setInterval((guild)=>{
const count = msg.guild.memberCount
const channel = msg.guild.channels.cache.get(display1id)
channel.setName(`Total Members: ${count.toLocaleString()}`);
console.log('Updating Member Count');
},5000)
}
The error:
const display1id = await msg.guild.channels.cache.get(display1.id)
TypeError: Cannot read property 'id' of undefined
Can anyone tell me how to solve this error,
basically this code helps to see the current member of the guild
and it will autoupdate it.
It will create a voice channel if it didn't found any one for showing the member.

The reason it couldn't find the channel is because the channel type for voice is GUILD_VOICE (not just voice) in discord.js v13. That is why it used the default channel type GUILD_TEXT. And text channels can't have capital letters and spaces in their names. It converted the channel name 'Total Members' to 'total-members' and when you tried searching for the channel with .find() it wasn't found, because the channel name was different.
The .find() method returned undefined and you later tried reading a property .id of the returned variable. Thus reading a property .id of undefined.
Also don't use an equal sign when searching for the channel. Use .startsWith() instead, because later you are adding the member count to the channel name.
You can take a look at this:
// ... The variable msg defined somewhere (e.g. as messageCreate callback parameter) ...
const channelName = "Total Members";
let display = msg.guild.channels.cache.find(ch => ch.name.startsWith(channelName));
if(!display) {
try {
display = await msg.guild.channels.create(channelName, {
type: "GUILD_VOICE",
permissionOverwrites: [
{
id: msg.guild.roles.everyone,
allow: ["VIEW_CHANNEL"],
deny: ["SEND_MESSAGES", "CONNECT"]
}
],
});
msg.channel.send(`Successfully created a channel '${channelName}'.`);
}
catch (error) {
console.log(error);
msg.channel.send(`Failed to create a channel '${channelName}'.`);
return;
}
}
setInterval(() => {
const count = msg.guild.memberCount;
display.setName(`${channelName}: ${count.toLocaleString()}`);
console.log("Updating Member Count ...");
}, 5000);

Related

TypeError: Cannot read property 'mentions' of undefined

first time poster looking for some help, struggling to get this to work. I'm wanting to create a command which followed by a channel mention and Raw JSON will then post an embed in the mention channel. The code itself throws up no errors, until the point I initiate the command, where I get "TypeError: Cannot read property 'mentions' of undefined". Any ideas where I've gone wrong?
const DiscordJS = require('discord.js')
const WOKCommands = require('wokcommands')
require('dotenv').config();
module.exports = {
name: "embedjson",
category: "info",
description: "post embed from json data",
minArgs: 2,
expectedArgs: '<Channel mention> <JSON>',
run: async ({client, message, args, level }) => {
// get the target channel
const targetChannel = message.mentions.channels.first()
if (!targetChannel) {
message.reply('Please specify a channel to send the embed in')
return
}
// removes the channel mention
args.shift()
try {
// get the JSON data
const json = JSON.parse(args.join(' '))
const { text = '' } = json
// send the embed
targetChannel.send(text, {
embed: json,
})
} catch (error) {
message.reply(`Invalid JSON ${error.message}`)
}
},
}

Mention users with specific role in bot status

Sooo, hello to everyone who sees this, it's my first time posting anything on StackOverflow. Anyway, recently I started learning discord.js and I managed to create a small bot in v12 with automatically changing status. Here is the code:
setInterval(() => {
const statuses = [
`user 1`,
`user 2`,
`user 3...`
]
const status = statuses[Math.floor(Math.random() * statuses.length)]
client.user.setActivity(status, { type: "WATCHING" })
}, 5000)
The point is to have certain members usernames appear in bot status and this is really nice if the server has like just a few of these "special" members but now my server became larger and I would like for bot to target ONE specific role and list all the members with that "special" role :)
Please help me, thank you in advance
So after Elitezen tried to help me I did this:
I added async in client on ready:
client.on("ready", async () => {
const guild = client.guilds.cache.get("SERVER_ID");
I added your code:
const role = guild.roles.cache.get('SERVER_ID');
await guild.members.fetch();
setInterval(() => {
const statuses = Array
.from(role.members.cache.values())
.map(member => member.displayName);
const status = statuses[Math.floor(Math.random() * statuses.length)]
client.user.setActivity(status, { type: "WATCHING" })
}, 5000)
And now Im stuck with this error:
TypeError: Cannot read property 'values' of undefined
An example to target your desired role using RoleManager#get() or RoleManager#find()
const role = <Guild>.roles.cache.find(r => r.name == 'role name');
// Or
const role = <Guild>.roles.cache.get('role id');
To get all the members that hold this role fetch all members of the guild first, then construct an array from the Collection's values.
Then map the array of members to their display name (or user's username)
Ensure you have the guild member's intent enabled if you want to fetch all members.
await <Guild>.members.fetch();
setInterval(() => {
const statuses = Array
.from(role.members.values());
.map(member => member.displayName);
const status = statuses[Math.floor(Math.random() * statuses.length)]
client.user.setActivity(status, { type: "WATCHING" })
}, 5000)
So, thanks to Elitezen I managed to solve my problem.
After making client on ready an async function
client.on("ready", async () => {
const guild = client.guilds.cache.get("SERVER_ID");
This is the final script for mentioning users with a certain role in bot status:
const role = guild.roles.cache.get('ROLE_ID');
await guild.members.fetch();
setInterval(() => {
const statuses = Array
.from(role.members.values())
.map(member => member.displayName);
const status = statuses[Math.floor(Math.random() * statuses.length)]
client.user.setActivity(status, { type: "WATCHING" })
}, 5000)

discord.js can't add a role to member when they join my server

I want my bot to give a certain role to people when they join the server. But I get some weird error I don't really understand.
This is the code:
const { GuildMember, MessageEmbed } = require("discord.js");
module.exports = {
name: "guildMemberAdd",
/**
* #param {GuildMember} member
*/
async execute(member){
let role = member.guild.roles.cache.some(role => role.name === 'Member')
member.roles.add(role)
member.guild.channels.cache.get(process.env.WELCOME_MESSAGE_CHANNEL_ID).send({
embeds: [
new MessageEmbed()
.setTitle("Welcome! :smiley:")
.setDescription(`${member.toString()} has joined the server!\n
Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`)
.setThumbnail(member.user.displayAvatarURL())
.setColor("GREEN")
]
})
}
}
And when someone joins I get this error message:
TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or
Array or Collection of Roles or Snowflakes.
The problem is that some() returns a boolean (either true or false) and when you try to add a role to the member you pass this boolean value instead of a role ID. You can use the find() method instead that returns the first item where the given function returns a truthy value (i.e. where role.name is equal to "Member"):
async execute(member) {
let role = member.guild.roles.cache.find((role) => role.name === 'Member');
if (!role)
return console.log('Cannot find the role with the name "Member"');
member.roles.add(role);
member.guild.channels.cache
.get(process.env.WELCOME_MESSAGE_CHANNEL_ID)
.send({
embeds: [
new MessageEmbed()
.setTitle('Welcome! :smiley:')
.setDescription(
`${member.toString()} has joined the server!\n Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`,
)
.setThumbnail(member.user.displayAvatarURL())
.setColor('GREEN'),
],
});
}

How to create a channel in a specific category?

I'm making a Discord.js bot. I want to create a function that triggers once you join a specific channel. When triggered, the bot will create a channel with your username in a specific category. The channel gets created successfully, but I didn't find any way to create it in the category I want by pointing its id.
Here is my code:
client.on('voiceStateUpdate', async (_oldState, newState) => {
try {
let newUserChannel = newState.channelID;
const channelhubID = '758361123316826124';
const channel = newState.channel;
if (newUserChannel == channelhubID) {
const guild = channel.guild;
const joinedUsername = newState.member.user.username;
guild.channels.create(`${joinedUsername}`, { type: 'voice' });
} else if (newUserChannel == undefined) {
}
} catch (error) {
console.log(error);
}
});
I don't get an error from this, but when I try to execute the setParent method, nothing happens.
One of the options for GuildChannelManager.create() is the parent property.
guild.channels.create(joinedUsername, {
type: 'voice',
parent: 'Category ID or Object Here',
});

How to fix a complex Discord command in JS based off of webhooks and roles

I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.

Categories