Discord.JS | Check If channel exists Ticket bot - discord

So Hello again,
I am making a ticket bot for discord and I got this bug that I cannot solve it my self.
here's the create ticket command:
if(cmd === "new"){
const reason = message.content.split(" ").slice(1).join(" ");
if (message.guild.channels.exists("name", "ticket-" + message.author.username)) return message.channel.send(`You already have a ticket open.`);
message.guild.createChannel(`ticket-${message.author.username}`, "text").then(c => {
let role = message.guild.roles.find("name", "Support Team");
let role2 = message.guild.roles.find("name", "#everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
var embedcreated = new Discord.RichEmbed()
.setColor("#f00202")
.setDescription(`You ticket has been created ` + message.guild.channels.find(channel => channel.name === c.name).toString())
.setTitle("Tickets | MiZ")
.setFooter(`Tickets System`)
.setTimestamp();
message.channel.send(embedcreated);
const embed = new Discord.RichEmbed()
.setColor("#f00202")
.addField(`Hey ${message.author.username}!`, ` Please explain your problen to the staff team.`)
.setTimestamp();
c.send({ embed: embed });
}).catch(console.error);
let sChannel = message.guild.channels.find(x => x.name === "logs");
if(!sChannel) return message.channel.send("logs channel not found.")
var staff = new Discord.RichEmbed()
.setColor("#f00202")
.addField("Created a ticket: " , message.author)
.setTitle("Logs | MiZ")
.setTimestamp();
sChannel.send(staff)
}
I have a line that checks if the channel exists but it doesn't work as I can create more tickets.
Used:
Discord.js: ^11.3.2

Please next time be more specific and use the javascript block code so it's more understandeble
no block code
"Javascript block code"

Related

When i try to create a role it gives me an error (discord.js)

So i am trying to make a command that mute a member. I want my bot to check if there is role name Muted and if there is not, to create a role for Muted members.
This is the code:
module.exports = {
name: 'mute',
description: 'mutes a member',
execute(message, args, Discord, bot) {
let mutedRole = message.guild.roles.cache.find(r => r.name === 'Muted')
if(!mutedRole) {
Guild.roles.create({
data: {
name: 'Muted',
color: 'BLACK'
}
})
}
}
}
and the error is this:
C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\mute.js:10
Guild.roles.create({
^
TypeError: Cannot read property 'create' of undefined
I don't think you should create a role via code. I think you should create a role in your Discord server (like actually just making one without code). Download the ms package. (npm i ms) Then, paste this code in:
const ms = require('ms');
module.exports = {
name: "mute",
description: "Mutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
if (!args[1]){
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted.`);
return;
}
if (isNaN(args[1]) || !args[1] === ' '){
message.channel.send("Please enter a real number! (If you have a space after the username and you don\'t want to set a time limit, delete the space. YOU HAVE TO.)");
return;
}
memberTarget.roles.remove(mainRole.id);
memberTarget.roles.add(muteRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
setTimeout(function(){
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
}, ms(args[1]));
} else {
message.channel.send("Can't find that member!");
}
}
}
Thanks to CodeLyon for this code. Hope this works for you! It even includes a time limit.
format 1: !mute #User
format 2: !mute #User 1000 (1000 can be changed, just make sure it's in milliseconds)
module.exports = {
name: "unmute",
description: "Unmutes a member!",
execute(message, args, Discord, bot){
const target = message.mentions.users.first();
if (target) {
let mainRole = message.guild.roles.cache.find(role => role.name === 'Member');
let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
let memberTarget = message.guild.members.cache.get(target.id);
memberTarget.roles.remove(muteRole.id);
memberTarget.roles.add(mainRole.id);
message.channel.send(`<#${memberTarget.user.id}> has been unmuted.`);
} else {
message.channel.send("Can't find that member!");
}
}
}
format: !unmute #User
Remember, this code only works if you have a role Member and a role Muted. So, in your server, add the role Member to everybody and add a role Muted (not to everybody).
Hope this works! If there's any need for clarification, please tell me in the comments.

Bot creates a second channel for no reason

I have a big mistake. Everything works perfectly! But the bot creates two instead of one channel. Why is that? I've been trying to figure it out for myself. But I can't find the error.
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.guild.id !== "601109434197868574") return;
if (reaction.emoji.name === "🛑") {
if (reaction.message.channel.id === "732018576604528640");
const channelName = `•┇ticket-${user.username}`
if(reaction.message.guild.channels.cache.find(channel => channel === `•┇ticket-${user.username}`)){
return user.send("Du hast bereits ein offnes Ticket!")
}
reaction.message.guild.channels.create(channelName, {parent: '731947024932667432', topic: `Ticket Owner: ${user}`}).then(c => {
const everyone = reaction.message.guild.roles.cache.find(role => role.name === '#everyone')
const sr = reaction.message.guild.roles.cache.find(role => role.name === 'ticketsuppport')
c.updateOverwrite(sr, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
c.updateOverwrite(everyone, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
c.updateOverwrite(user, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
let GreetEmbed = new Discord.MessageEmbed()
.setColor(colours.maincolour)
.setDescription(`> Guten Tag, ${user}!\n> \n> Du hast nun ein Support-Ticket erstellt. Wie können wir dir helfen?\n> \n> \🔒 Ticket schließen | \🆘 Weitere hilfe anfordern`)
.setFooter(`Ticket erstellt`)
.setTimestamp()
c.send(GreetEmbed)
let ping = c.send(`${user}`).then(message => {
message.delete(ping)
})
})
}```
You most-likely have two instances of the bot running.
To verify this, you can make a change to the code (like modifying the message it sends when creating the channel). If both channels have the modification, I am wrong xD. If not, you need to find where your second bot it running (separate server, minimized window, etc..).
if (reaction.message.guild.channels.cache.find(channel => channel.name === channelName)) {
return user.send("Du hast bereits ein offenes Ticket!")
}
I think you forgot the channel.name because otherwise it filters for the channel object which will never be the same as a string and throughout that it'll never return. (BTW: There's also a typo with offnes)

guild.icon & guild.iconURL() not working in embed thumbnail

I want to set guild icon as the thumbnail of embed but neither guild.icon nor guild.iconURL() work
bot.on('message', message => {
if(message.author.bot) return;
if(message.channel.name === 'verify') {
if(message.content === '!verify') {
message.delete()
let dm = message.author;
let server = message.guild.name;
let servericon = message.guild.iconURL();
console.log(servericon)
let attachment = new Discord.MessageAttachment(this.choose , 'chosen.png')
let embed = new Discord.MessageEmbed()
.setTitle(`**Welcome to ${server}**\n\nCaptcha`)
.setDescription("Please complete the captcha given below to gain access to the server.\n**Note:** This is case sensitive")
.setAuthor('Mr.Verifier', "https://i.ibb.co/nckjDjG/hmm.png")
.setThumbnail(servericon)
.addField(
{ name: '**Why all this?**', value: 'This is to protect the servers from\nmalicious raids of automated bots'}
)
.setImage(`attachment://chosen.png`)
dm.send(embed)
}else{
message.delete();
}
};
})
You need to use guild.iconURL().

Discord.js - Give role a all channel

Hello I would like to create an order (! Giverole) so that it gives the roles (mute) to all the channels of the server or to be made the order.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
var mute_role = message.guild.roles.find(r => r.name == 'mute', {READ_MESSAGES: true, SEND_MESSAGES: false})
if (!mute_role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.overwritePermissions(channel => channel.addRole(mute_role));
var lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
thank you in advance
At the fist - try always get role with role ID, its more safely.
If I understand your question correctly and you need a certain role on all channels to establish certain rights. So you can use this code.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
let muteRole = message.guild.roles.get('ROLEID')
if (!muteRole) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.map(channel => {
if(channel.type === 'text') {
channel.overwritePermissions(muteRole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
})
.then(console.log)
.catch(console.log);
}
})
let lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
}
})
```

Block Kick or set Limit to Kick Discord.js

hello I don't want the mods to do kick action in my server i see discord.js doesnt add guildKickAdd like guildMemberAdd
so how can i block kick or set limit kick ?
this is ban block when someone do ban action bot taking roles and gives him punished.
client.on("guildBanAdd", async function(guild, user) {
const entry = await guild
.fetchAuditLogs({ type: "MEMBER_BAN_ADD" })
.then(audit => audit.entries.first());
const yetkili = await guild.members.get(entry.executor.id);
setTimeout(async () => {
let logs = await guild.fetchAuditLogs({ type: "MEMBER_BAN_ADD" });
if (logs.entries.first().executor.bot) return;
guild.members
.get(logs.entries.first().executor.id)
.removeRoles(guild.members.get(logs.entries.first().executor.id).roles); ///TÃœM ROLLERÄ°NÄ° ALIR
setTimeout(() => {
guild.members
.get(logs.entries.first().executor.id)
.addRole("633026228537917460"); /// VERÄ°LECEK CEZALI ROL Ä°D
}, 3000);
const sChannel = guild.channels.find(c => c.id === "641032067840344064");
const cıks = new Discord.RichEmbed()
.setColor("RANDOM")
.setDescription(
`<#${yetkili.id}> ${user} adlı Kişiye Sağ tık ban Atıldığı için Banlayan Kişinin Yetkileri Alındı`
)
.setFooter("Created by Tokuchi");
sChannel.send(cıks);
guild.owner.send(
`Tokuchi Affetmez † Guard | ** <#${yetkili.id}> İsimili Yetkili <#${user.id}>** Adlı Kişiyi Banladı Ve Yetkilerini Aldım.`
);
}, 2000);
});```
You need to use guildMemberRemove event:
// When a member left. Maybe he left himself, but maybe he was kicked.
client.on("guildMemberRemove", (member) => {
// Get the last kick case of the server
const entry = await guild
.fetchAuditLogs({ type: "MEMBER_KICK" })
.then(audit => audit.entries.first());
// if there's not any kick case in this server
if(!entry) return;
// if the target was not the member who left
if(entry.target.id !== member.id) return;
// Else, you know the member was kicked, and you have the entry so you can do what you want
});
This is the best way to know if someone was kicked.

Resources