Bot creates a second channel for no reason - discord

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)

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.

Discord.JS | Check If channel exists Ticket bot

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"

Creating channel and setChannel troubles

I'm having trouble creating a discord bot, what it should do is detect whenever someone jkoins a specific voice Chat, and if a user does, the bot would have to create a new channel with, as the name, the nickname of the user who joined, then move that user to the new created channel and set that channel to private so no one can join.
Currently my problems are:
-I can't set the name of the new channel as the nickname of the user
-I can't move the user to that channel
-And I think the rest may work
Here is the part of my code:
client.on('voiceStateUpdate', (oldMember, newMember) => {
if(newMember.channelID != '693086073244483614') return;
const nick = newMember.nickname;
newMember.guild.channels.create('test', { type: 'voice' })
.then(() => {
newMember.setChannel('test');
console.log(`Hello from ${newMember.channel}!`);
const nChannel = newMember.channel;
nChannel.setParent('690292158636360032');
nChannel.overwritePermissions([
{
parent: '#690292158636360032',
id: '532236212967047169',
deny: ['CONNECT'],
},
]);
});
});
Any help would be appriciated, I'm new to both discord bots and javascript, so thanks a lot!
The Client#voiceStateUpdate event does not return a member, it returns a VoiceState. https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-voiceStateUpdate
From the VoiceState, you can get a member with <VoiceState>.member.
So to fix your error, replace const nick = newMember.nickname to const nick = newMember.member.nickname.
client.on('voiceStateUpdate', (oldMember, newMember) => {
var oldUserChannel = oldMember.voiceChannel;
var newUserChannel = newMember.voiceChannel;
if(oldUserChannel === undefined && newUserChannel !== undefined) { //User joined the channel.
if(newMember.voiceChannel.id != '693086073244483614') return; //Check if the user join the right voice channel.
let nick = newMember.nickname;
if(nick == null){
nick = newMember.user.username; //If the member doesn't have a nickname.
}
newMember.guild.createChannel(nick, { type: 'voice' })
.then((nChannel) => {
console.log(`Hello from ${nChannel}!`);
nChannel.setParent('690292158636360032'); //Your category ID
nChannel.overwritePermissions(nChannel.guild.defaultRole.id, {
VIEW_CHANNEL: false
});
newMember.setVoiceChannel(nChannel)
});
} else if(newUserChannel === undefined){ //User left the channel.
if(oldMember.voiceChannel.parent == null) return;
if(oldMember.voiceChannel.parent.id != '690292158636360032') return; //Check if the voice channel is under the specified category.
if(oldMember.voiceChannel.members.first() == null){ //There is no more users in this channel.
oldMember.voiceChannel.delete(); //Delete the channel.
}
}
});
Here is the final result, fully working. I also add a system to automatically remove the channel if there is nobody in.
I have added some annotations, tell me if you have any questions.

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