V11 version mismatch - javascript

client.on("channelDelete", async channel => {
let channelg = await db.fetch(`channel_${channel.guild.id}`);
if (channelg == "on") {
const logs = await channel.guild.fetchAuditLogs({ type: 'CHANNEL_DELETE' }).then(audit => audit.entries.first())
const deleter = await channel.guild.members.fetch(logs.executor.id);
if(deleter.id == channel.guild.owner.user.id) return;
channel.clone(undefined, true, true, "channel delete system").then(async klon => {
await klon.setParent(channel.parent);
await klon.setPosition(channel.position);
channel.guild.owner.send(`channel: **${channel.name}** channel it occurred again.`)
console.log('correct')
})
}
})
allows you to create a channel back when it is deleted
how to make discord js V11 version compatible, V12 was prepared for release.
can you help? I hope everything is clear

You have to replace guild.members.fetch() with guild.fetchMember()
Also, the first argument of Channel.clone() must be an Object.
Instead of undefined, just provide an empty Object, as all options in the first parameter are optional.
channel.clone({}, true, true, "channel delete system")

Related

Check if first argument is a mention

I'm coding a discord bot and I'm trying to make a kick command right now. I managed to find how to check if there's any mention in the command message with message.mentions.members.first() but I couldn't find anything to check if a specific argument is a mention.
Code I have so far:
module.exports = {
name: "kick",
category: "moderation",
permissions: ["KICK_MEMBERS"],
devOnly: false,
run: async ({client, message, args}) => {
if (args[0]){
if(message.mentions.members.first())
message.reply("yes ping thing")
else message.reply("``" + args[0] + "`` isn't a mention. Please mention someone to kick.")
}
else
message.reply("Please specify who you want to kick: g!kick #user123")
}
}
I looked at the DJS guide but couldn't find how.
MessageMentions has a USERS_PATTERN property that contains the regular expression that matches the user mentions (like <#!813230572179619871>). You can use it with String#match, or RegExp#test() to check if your argument matches the pattern.
Here is an example using String#match:
// make sure to import MessageMentions
const { MessageMentions } = require('discord.js')
module.exports = {
name: 'kick',
category: 'moderation',
permissions: ['KICK_MEMBERS'],
devOnly: false,
run: async ({ client, message, args }) => {
if (!args[0])
return message.reply('Please specify who you want to kick: `g!kick #user123`')
// returns null if args[0] is not a mention, an array otherwise
let isMention = args[0].match(MessageMentions.USERS_PATTERN)
if (!isMention)
return message.reply(`First argument (_\`${args[0]}\`_) needs to be a member: \`g!kick #user123\``)
// kick the member
let member = message.mentions.members.first()
if (!member.kickable)
return message.reply(`You can't kick ${member}`)
try {
await member.kick()
message.reply('yes ping thing')
} catch (err) {
console.log(err)
message.reply('There was an error')
}
}
}

Discord Bot who disconnected a user from voice channel

I'm trying to make my bot to send a message when someone is disconnected. That contains the one who got disconnected and the one who disconnected them.
But when I run the bot and disconnect someone nothing is happening.
Here is my code:
client.on("voiceStateUpdate", function (oldMember, newMember) {
let newUserChannel = newMember.voiceChannel
if (newUserChannel === null) {
// User leaves a voice channel
const fetchedLogs = await (oldMember, newMember).guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_DISCONNECT',
});
const disconnectLog = fetchedLogs.entries.first();
const { executor } = disconnectLog;
client.channels.cache.get("828731501016252417").send(`<#${executor.id}> Disconnected <#${oldMember.id}>`)
}
});
The reason nothing is happening is because the client.voiceStateUpdate event now emits oldState and newState representing the VoiceStates of the member instead of the member itself. It's changed in discord.js v12. As the VoiceState doesn't have a voiceChannel property, your newUserChannel will be undefined.
Your if statement (if (newUserChannel === null)) will always be false, as undefined is not strictly equal to null, so nothing inside it will get executed.
You could check if newVoiceState.channel is null instead. You should also check if the bot has the required VIEW_AUDIT_LOG permission before you try to fetch the logs. You also missed the async keyword in front of your callback function, you can only use await inside async functions.
Check the code below, it should work as expected.
client.on('voiceStateUpdate', async (oldVoiceState, newVoiceState) => {
// User leaves a voice channel
if (newVoiceState.channel === null) {
// check if the bot can view audit logs
if (!oldVoiceState.guild.me.hasPermission('VIEW_AUDIT_LOG'))
return console.log('Missing permission: "VIEW_AUDIT_LOG"');
const fetchedLogs = await oldVoiceState.guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_DISCONNECT',
});
const { executor } = fetchedLogs.entries.first();
client.channels.cache
.get('828731501016252417')
.send(`${executor} disconnected ${oldVoiceState.member}.`);
}
});
PS: The current function sends the last entry every time someone leaves a voice channel, even if they left on their own will. I think, MEMBER_DISCONNECT will only be logged when someone else kicked the member from the channel. You need to verify somehow if the last log entry is the same as the current voiceStateUpdate.
voiceStateUpdate event has VoiceState type parameters, not members.
client.on("voiceStateUpdate", function (oldVoiceState, newVoiceState) {
let newUserChannel = newVoiceState.channel
if (newUserChannel === null) {
// User leaves a voice channel
const fetchedLogs = await (oldVoiceState, newVoiceState).guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_DISCONNECT',
});
const disconnectLog = fetchedLogs.entries.first();
const { executor } = disconnectLog.executor;
client.channels.cache.get("828731501016252417").send(`<#${executor.id}> Disconnected <#${oldVoiceState.id}>`)
}
});

create a channel with a embed

I try to create a very small ticket bot.
I would only like that when reacting a support channel opens and nothing else.
This is the code i am working with.
const ember = new Discord.MessageEmbed()
.setColor('#E40819')
.setTitle('⚠️SUPPORT')
.setDescription("Open a Ticket")
let msgEmbed6 = await message.channel.send(ember)
await msgEmbed6.react('⚠️')
The code inside the if statement will only run if the user reacts, I'm not sure what you mean by 'open a support channel'.
const reaction = msgEmbed6.awaitReactions((reaction, user) => user.id === message.author.id, { max: 1, timeout: TIME_IN_MILLISECONDS });
if (reaction.size > 0) {
// Creates a new text channel called 'Support'
const supportChannel = await message.guild.channels.create('Support', { type: 'text' });
// Stops #everyone from viewing the channel
await supportChannel.updateOverwrite(message.guild.id, { VIEW_CHANNEL: false });
// Allows the message author to send messages to the channel
await supportChannel.updateOverwrite(message.author, { SEND_MESSAGES: true, VIEW_CHANNEL: true });
}

How to add permissions to user to channel by command? Discord.js

How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }

Discord.js doesn't create temporary channels

I'm trying to make a bot which will create temporary voice channles
Code:
var temporary = []
client.on('voiceStateUpdate', (oldMember, newMember) => {
const mainCatagory = '677192265491415041';
const mainChannel = '677875869351542803';
if (newMember.voiceChannelID == mainChannel) {
newMember.guild.createChannel(`${newMember.user.username} 5vs5`, { type: 'voice', parent: mainCatagory })
.then(async channel => {
temporary.push({ newID: channel.id, guild: channel.guild })
// A new element has been added to temporary array!
await newMember.setVoiceChannel(channel.id)
})
}
if (temporary.length >= 0) for (let i = 0; i < temporary.length; i++) {
// Finding...
let ch = temporary[i].guild.channels.find(x => x.id == temporary[i].newID)
// Channel Found!
ch.setUserLimit(5)
if (ch.members.size <= 0) {
ch.delete(1000)
// Channel has been deleted!
return temporary.splice(i, 1)
}
}
})
Why it doesn't work?
it worked fine before i reinstalled system
node: 13.10.1
Win: 10
I can see you are having issues with asynchronous code. You have the following line:
await newMember.setVoiceChannel(channel.id)
That is not getting awaited as you are expecting it to because it falls within the block of a .then. The await only affects the code in that async block in the .then statement, and since nothing occurs after that line, it's not functionally doing anything different than it would if you didn't await it.
You should try to avoid mixing .then and async/await if possible (there are reasons you might mix but you need to know what you are doing). In this case I suggest setting the entire event handler to be async and await both.
Note: The following assumes you are using discord.js v11, which is consistent with your earlier code sample. If you are using v12 you should be using guild.channels.create(), guild.channels.cache.find(), and newMember.voice.setChannel() instead. You said you just installed a new instance of node and presumable discord.js so you may in fact be on v12 now and that could be part of your issue.
client.on('voiceStateUpdate', async (oldMember, newMember) => {
const mainCatagory = '677192265491415041';
const mainChannel = '677875869351542803';
if (newMember.voiceChannelID == mainChannel) {
let channel = await newMember.guild.createChannel(`${newMember.user.username} 5vs5`, { type: 'voice', parent: mainCatagory })
temporary.push({ newID: channel.id, guild: channel.guild })
// A new element has been added to temporary array!
await newMember.setVoiceChannel(channel.id)
}
// The rest of your code.
}

Categories