I have the below code which is intended to create a new channel with a name. This works fine. It then needs to set the permissions of the channel to making it VIEW_CHANNEL false for all users. It then needs to overwrite permissions for the message author to grant them VIEW_CHANNEL. Im getting stuck on how to make the permissions apply on the channel just created.
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let botIcon = bot.user.displayAvatarURL;
let ticketEmbed = new Discord.RichEmbed()
.setDescription("TicketBot")
.setColor("#bc0000")
.setThumbnail(botIcon)
.addField("New Ticket", `${message.author} your ticket has been created.`);
let ticketchannel = message.guild.channels.find(`name`, "bot-testing");
if(!ticketchannel) return message.channel.send("Couldn't find bot testing channel.");
ticketchannel.send(ticketEmbed);
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let ticketid = getRandomInt(10000);
let name = `ticket-${message.author.username}-${ticketid}`;
message.guild.createChannel(name, "text")
.then(
message.channel.overwritePermissions(message.author, {
VIEW_CHANNEL: true
})
);
}
module.exports.help = {
name: "new"
}
The below code works :)
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let botIcon = bot.user.displayAvatarURL;
let ticketEmbed = new Discord.RichEmbed()
.setDescription("TicketBot")
.setColor("#bc0000")
.setThumbnail(botIcon)
.addField("New Ticket", `${message.author} your ticket has been created.`);
let ticketchannel = message.guild.channels.find(`name`, "bot-testing");
if(!ticketchannel) return message.channel.send("Couldn't find bot testing channel.");
ticketchannel.send(ticketEmbed);
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let ticketid = getRandomInt(10000);
let name = `ticket-${message.author.username}-${ticketid}`;
message.guild.createChannel(name, "text")
.then(m => {
m.overwritePermissions(message.guild.id, {
VIEW_CHANNEL: false
})
m.overwritePermissions(message.author.id, {
VIEW_CHANNEL: true
})
})
//channel.delete()
}
module.exports.help = {
name: "new"
}
Related
I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction
const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
let index = Math.map(Math.random() * react.length);
let winner = react[index];
console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
I'm trying to code a giveaway module however the winner result is coming out as undefined and I can't seem to figure out why, If you guys can help me out be greatly appreciated
These were logged by the console if it helps any
index = NaN
winner = undefined
const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
const reactArray = react.map(c => c)
let index = Math.floor(Math.random() * reactArray.length);
let winner = reactArray[index];
console.log(reactArray)
// console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
Seems to have resolved the issue, Added const reactArray = react.map(c => c)
Changed
let index = Math.floor(Math.random() * react.length); to let index = Math.floor(Math.random() * reactArray.length); which made const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch(); into an array of user id's
i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("BÅ‚Ä…d!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('BÅ‚Ä…d!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};
So i am coding a bot , in Node.js with Visual Studio Code. I want to have a channel, that when a user joins the guild , will send 'Welcome user and invited by thisuser(Total Invites: 5)
The code is :
module.exports = (client) => {
const invites = {} // { guildId: { memberId: count } }
const getInviteCounts = async (guild) => {
return await new Promise((resolve) => {
guild.fetchInvites().then((invites) => {
const inviteCounter = {} // { memberId: count }
invites.forEach((invite) => {
const { uses, inviter } = invite
const { username, discriminator } = inviter
const name = `${username}#${discriminator}`
inviteCounter[name] = (inviteCounter[name] || 0) + uses
})
resolve(inviteCounter)
})
})
}
client.guilds.cache.forEach(async (guild) => {
invites[guild.id] = await getInviteCounts(guild)
})
client.on('guildMemberAdd', async (member) => {
const { guild, id } = member
const invitesBefore = invites[guild.id]
const invitesAfter = await getInviteCounts(guild)
console.log('BEFORE:', invitesBefore)
console.log('AFTER:', invitesAfter)
for (const inviter in invitesAfter) {
if (invitesBefore[inviter] === invitesAfter[inviter] - 1) {
const channelId = '731801004462571602'
const channel = guild.channels.cache.get(channelId)
const count = invitesAfter[inviter]
channel.send(
`Please welcome <#${id}> to the Discord! Invited by ${inviter} (${count} invites)`
)
invites[guild.id] = invitesAfter
return
}
}
})
}
This code works perfectly with console but i am facing a problem,never post the message in the channel!
The message might not be being sent because of the channel ID double check you are using the right channel ID and you might want to try changing
const channel = guild.channels.cache.get(channelId) to this
const channel = client.channels.cache.get(channelId)
How do I make it so that when someone reacts with the first emoji in this command, the bot deletes the message and sends it to another channel?
Current Code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You are not allowed to run this command.");
let botmessage = args.join(" ");
let pollchannel = bot.channels.cache.get("716348362219323443");
let avatar = message.author.avatarURL({ size: 2048 });
let helpembed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, avatar)
.setColor("#8c52ff")
.setDescription(botmessage);
pollchannel.send(helpembed).then(async msg => {
await msg.react("715383579059945512");
await msg.react("715383579059683349");
});
};
module.exports.help = {
name: "poll"
};
You can use awaitReactions, createReactionCollector or messageReactionAdd event, I think awaitReactions is the best option here since the other two are for more global purposes,
const emojis = ["715383579059945512", "715383579059683349"];
pollchannel.send(helpembed).then(async msg => {
await msg.react(emojis[0]);
await msg.react(emojis[1]);
//generic filter customize to your own wants
const filter = (reaction, user) => emojis.includes(reaction.emoji.id) && user.id === message.author.id;
const options = { errors: ["time"], time: 5000, max: 1 };
msg.awaitReactions(filter, options)
.then(collected => {
const first = collected.first();
if(emojis.indexOf(first.emoji.id) === 0) {
msg.delete();
// certainChannel = <TextChannel>
certainChannel.send(helpembed);
} else {
//case you wanted to do something if they reacted with the second one
}
})
.catch(err => {
//time up, no reactions
});
});