cannot read property of 'channels' of undefined discord.js - javascript

const reason = args.slice(0).join(" ");
if (!reason) return message.channel.send('Reason for ticket?');
const user = message.guild.member(message.author);
const ticket = db.fetch(`Ticket_user_${user.id}`)
if(ticket) message.channel.send("You already made a ticket senpai! Close your old ticket.");
const channel = message.guild.channels.cache.find
(channel => channel.name === 'ticket')
if (!channel)
guild.channels.create('ticket', {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
})
.then(console.log)
.catch(err => {
message.channel.send("An error occurred while running the command. Please report this error to the support server:"+ err)
return;
})
db.add(`Ticket_user_${user.id}`)
const time = "3"
setTimeout(() => {
const embed = new Discord.MessageEmbed()
.setTitle(`Ticket#0001`)
.setDescription(`Reason: ${reason}`)
.addField("Welcome to my ticket senpai!! We are waiting for staff")
.setColor("PURPLE")
message.channel.send(embed)
}, ms(time))
}
}
I'm making a ticket system for my bot and ik you people smart because top.gg won't help
Thank you for the help this will help my bot and my code and make me smart plus I'm removing the dot becccause of downvote ig

Here in this code
if (!channel){
guild.channels.create('ticket', { //...... rest of the code
You didn't define guild. Try replacing guild with message.guild
Like this:
if (!channel){
message.guild.channels.create('ticket', { //.... rest of the code
Also, please remove the unnecessary part (dots) from the question

Related

Discord.js v13 Reaction Roles

I already have this code to post an embed and to add a reaction, I'm just wondering how I would go about adding a role to a user when they add the reaction?
if (message.content.startsWith(`${prefix}rr`)) {
let embed = new MessageEmbed()
.setColor("#ffffff")
.setTitle("📌 Our Servers Rules 📌")
.setDescription("To keep our server safe we need a few basic rules for everyone to follow!")
.setFooter("Please press ✅ to verify and unlock the rest of the server!")
.addFields(
{
name: "1.",
value: "Stay friendly and don't be toxic to other users, we strive to keep a safe and helpful environment for all!",
},
{
name: "2.",
value: "Keep it PG-13, don't use racist, homophobic or generally offensive language/overly explicit language!",
},
{
name: "3.",
value: "If you want to advertise another server/website etc please contact me first!",
},
{ name: "4.", value: "Don't cause drama, keep it civil!" },
{
name: "5.",
value: "If you have any questions please contact me #StanLachie#4834",
}
);
message.channel.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react("✅");
});
}
You may want to check this Discord.js Guide page. But in summary...
const filter = (reaction, user) => {
return reaction.emoji.name === '✅' && user.id === message.author.id;
};
const collector = message.createReactionCollector({ filter });
collector.on('collect', (reaction, user) => {
const role = await message.guild.roles.fetch("role id");
message.guild.members.fetch(user.id).then(member => {
member.roles.add(role);
});
});

Can I use an if statement inside a try-catch method?

I'm using the guild.fetchVanityData() method to get a guild's vanity data in my Discord bot using the Discord.js library.
My invite.js command throws an error saying This guild does not have the VANITY_URL feature enabled.
I know that the guild does not have it enabled, and am sending a custom message to the user telling them that. Hence, I do not want it to throw an error. I'm using an if check in my message.js event file to swallow the error if the command executed is the invite command (The command throwing the error), using a return method. This does not seem to work as it still throws an error.
The only file in my entire bot in which I am using a try-catch is at the end of message.js.
My code is below, please help me out.
Message.js event file
module.exports = {
name: 'message',
execute(message, client) {
const prefixes = ['!1','833376214609690674', "<#!833376214609690674>","<#833376214609690674>"]
const prefix = prefixes.find(p => message.content.startsWith(p));
if (!prefix || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (message.content === "<#833376214609690674>" || message.content === "<#!833376214609690674>" || message.content === "833376214609690674" || message.content === "!1") {
const mCommand = client.commands.get('help')
mCommand.execute(message, args)
}
if (!client.commands.has(commandName)) return message.channel.send("Please provide a valid command.")
const command = client.commands.get(commandName);
try {
command.execute(message, args, client);
}
catch (error) {
if(command.name === "invite") {
return
}
else {
console.log(error)
}
}
},
};
Invite.js command file
const Discord = require('discord.js')
module.exports = {
name: 'invite',
category: "utility",
description: 'Get the bot invite or server invite info.',
execute: async (message, args) => {
if (args[0] === 'bot') {
const embed = new Discord.MessageEmbed()
.setTitle('Bot Invite')
.setDescription("Returns the bot's invite link.")
.addFields({
name: 'Invite',
value: "[Click here](https://discord.com/api/oauth2/authorize?client_id=833376214609690674&permissions=4294442710&scope=bot%20applications.commands) to invite the bot to your server."
})
message.channel.send(embed)
}
else if (args[0] === 'server') {
message.guild.fetchVanityData()
if (!message.guild.vanityURLCode) {
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: 'This server does not have a Vanity URL.',
inline: true
},
{
name: 'Uses',
value: 'Not Applicable',
inline: true
})
.setTimestamp()
return message.channel.send(embed)
}
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: `https://discord.gg/${message.guild.vanityURLCode}`,
inline: true
},
{
name: 'Uses',
value: `${message.guild.vanityURLUses}`,
inline: true
})
message.channel.send(embed)
}
}
}
I think this is all the code that is required, but if you wish to see my other commands, files, etc., you can go to this repl: https://replit.com/#smsvra6/MultiBot
According to discord.js documentation, <Guild>.fetchVanityData returns a Promise. Therefore, you can use <Promise>.then and <Promise>.catch syntax.
i.e.:
message.guild.fetchVanityData()
.then(data => {
// success, the server has a vanity url ;
})
.catch(error => {
// error, the server does not have a vanity url.
});
There is no need for an if statement.

I'm trying to create a channel named like user args. [DISCORD.JS V12]

It just gives me an error that the function message.guild.channels.create does not work because it's not a correct name.
My intention is to create a command where you will be asked how the channel you want to create be named. So it's ask you this. After this you send the wanted name for the channel. Now from this the bot should name the channel.
(sorry for bad english and low coding skills, im a beginner)
module.exports = {
name: "setreport",
description: "a command to setup to send reports or bugs into a specific channel.",
execute(message, args) {
const Discord = require('discord.js')
const cantCreate = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`Can't create channel.`)
const hasPerm = message.member.hasPermission("ADMINISTRATOR");
const permFail = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`${message.author}, you don't have the permission to execute this command. Ask an Admin.`)
if (!hasPerm) {
message.channel.send(permFail);
}
else if (hasPerm) {
const askName = new Discord.MessageEmbed()
.setColor(' #4f6abf')
.setDescription(`How should the channel be called?`)
message.channel.send(askName);
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { max: 1, time: 10000 });
console.log(collector)
var array = message.content.split(' ');
array.shift();
let channelName = array.join(' ');
collector.on('collect', message => {
const created = new Discord.MessageEmbed()
.setColor('#16b47e')
.setDescription(`Channel has been created.`)
message.guild.channels.create(channelName, {
type: "text",
permissionOverwrites: [
{
id: message.guild.roles.everyone,
allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'],
deny: ['SEND_MESSAGES']
}
],
})
.catch(message.channel.send(cantCreate))
})
}
else {
message.channel.send(created)
}
}
}
The message object currently refers to the original message posted by the user. You're not declaring it otherwise, especially seeing as you're not waiting for a message to be collected before defining a new definition / variable for your new channel's name.
NOTE: In the following code I will be using awaitMessages() (Message Collector but promise dependent), as I see it more fitting for this case (Seeing as you're more than likely not hoping for it to be asynchronous) and could clean up the code a little bit.
const filter = m => m.author.id === message.author.id
let name // This variable will later be used to define our channel's name using the user's input.
// Starting our collector below:
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
name = collected.first().content /* Getting the collected message and declaring it as the variable 'name' */
} catch (err) { console.error(err) }
await message.guild.channels.create(name, { ... })

TypeError: channel.updateOverwrite is not a function

Im trying to make a lock channel command but Im getting the following error:
TypeError: channel.updateOverwrite is not a function
I have tried changing it to channel.overwritePermissions but it does not work.
Any help works, thanks in advance
EDIT: Changing it to message.channel.updateOverwrite does not work, it locks the channel where you sent the message instead of the channel mentioned
EDIT2: The problem has been solved, I just had to add let channel = message.mentions.channels.first() in the code, I have edited the code.
Its the same for the unlock command
Heres the code:
const Discord = require('discord.js');
module.exports = {
category: 'Moderation',
name: 'lock',
commands: 'lock',
description: 'Locks the specified channel!',
callback: (message, args, channel, text) => {
if (!message.member.hasPermission('MANAGE_CHANNELS'))
return message.reply('<:nomark:791577754659192832> You dont have the necessary permissions to use this command!');
if (!args[0])
return message.reply('<:nomark:791577754659192832> You need to mention a channel!');
if (!message.mentions.channels.first())
return message.reply('<:nomark:791577754659192832> You need to mention VALID a channel!');
const role = message.guild.roles.cache.find(role => role.name === "#everyone");
if (!role) return message.channel.send('Role is not able to be found.')
message.mentions.channels.forEach(channel => {
if (channel.name.startsWith("🔒"))
return message.channel.send(`<#${channel.id}> is already locked!`)
channel.setName(`🔒${channel.name}`);
try {
channel.updateOverwrite(role, {
SEND_MESSAGES: false
});
message.channel.send(`<#${channel.id}> has been locked!`);
} catch (err) {
console.log(err);
message.channel.send(`Something has went wrong when locking the channels.`);
}
})
channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
}
}
The problem has been solved, I just had to add let channel = message.mentions.channels.first() in the code, I have edited the code

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources