Create a channel with discord.js - discord.js

I am trying to do a discord bot that creates channels among others, but I can't achieve it because my code it's supposed to create a channel but... I tried a lot of things, these are the two that haven't given me error: (I substituted the bot's token with DONOTLOOK, I won't have problems...)
OPTION 1:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login('DONOTLOOK');
bot.on('ready', () => {
console.log('Logged in as ${bot.user.tag}!');
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
var server = msg.guild;
bot.channels.add("anewchannel", {type: 0});
}
});
OPTION 2:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login('DONOTLOOK');
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
var server = msg.guild;
const channel = bot.channels.add("newchannel", {type: 0});
}
});
That don't gave me any node.js error on console, the bot answered me but haven't created the channel. I also looked two references(https://discord.com/developers/docs/resources/guild#create-guild-channel, https://discord.js.org/#/docs/main/stable/class/GuildChannelManager?scrollTo=create), no one's solutions worked, the discord.com one gave me node.js error too. The two options above are taken from the discord.js file, they gave no node.js errors but doesn't create the channel. If someone can help me please.

discord.js v13 has changed some stuff.
Updated version:
bot.on("messageCreate", message => { // instead of 'message', it's now 'messageCreate'
if (message.content === "channel") {
message.guild.channels.create("channel name", {
type: "GUILD_TEXT", // syntax has changed a bit
permissionOverwrites: [{ // same as before
id: message.guild.id,
allow: ["VIEW_CHANNEL"],
}]
});
message.channel.send("Channel Created!");
})
I would also recommend using bot.guilds.cache.get(message.guildId). This removes the need to use the API to fetch the user.

The code below explains how to create a text channel from a command.
bot.on('message', msg => { //Message event listener
if (msg.content === 'channel') { //If the message contained the command
message.guild.channels.create('Text', { //Create a channel
type: 'text', //Make sure the channel is a text channel
permissionOverwrites: [{ //Set permission overwrites
id: message.guild.id,
allow: ['VIEW_CHANNEL'],
}]
});
message.channel.send("Channel Created!); //Let the user know that the channel was created
}
});

If you don't want to use messages to create you can use..
var bot = client.guilds.cache.get("<GUILD-ID>");
server.channels.create("<CHANNEL-TEXT>", "<CHANNEL-TYPE>").then(channel => {
var cat = server.channels.cache.find(c => c.name == "BUSINESSES" && c.type == "category");
if (!cat) { console.log("category does not exist"); return; }
channel.setParent(cat.id);
})

Related

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

Discord.js V13 Adding role when using a slash command

I am trying to code a bot that when you use a certain slash command, it gives you a role. I have looked for a solution but haven't been able to find one. Nothing is seeming to work for me, i keep getting errors about the code, like "message not found, did you mean Message"
This is my first time trying to code a bot so if its a dumb issue, please bear with me.
Here is my code:
import DiscordJS, { Intents, Message, Role } from 'discord.js'
import dotenv from 'dotenv'
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
],
})
// Slash Commands
//ping pong command
client.on('ready', () => {
console.log('BOT ONLINE')
//bot test server
const guildId = '868857440089804870'
const guild = client.guilds.cache.get(guildId)
const role = client.guilds.cache.find(r => r.name == "Test Role to
give")
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application?.commands
}
commands?.create({
name: 'ping',
description: 'says pong'
})
commands?.create({
name: "serverip",
description: 'Gives user the server IP'
})
commands?.create({
name: "giverole",
description: 'Gives user the role'
})
})
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
//This is the role id that i want to give
const role = '884231659552116776'
//these are the users that i want to give the role to
const sniper = '725867136232456302'
const josh = '311981346161426433'
if (commandName === 'ping') {
interaction.reply({
content: 'pong',
ephemeral: true,
})
} else if (commandName === 'serverip') {
interaction.reply({
content: 'thisisserverip.lol',
ephemeral: true,
})
} else if (commandName === 'giverole') {
interaction.reply({
content: 'Role given',
ephemeral: true,
})
}
})
client.login(process.env.test)
You can just simply retrieve the Interaction#Member and add the role to them using GuildMemberRoleManager#add method!
const role = client.guilds.cache.find(r => r.name == "Test Role to
give");
await interaction.member.roles.add(role); // and you're all set! welcome to stackoverflow 😄
if (commandName === 'giverole') {
const role = client.guilds.cache.find(r => r.name == "Ahmed1Dev")
await user.roles.add(role)
message.channel.send("Done Added Role For You") // Fixed By Ahmed1Dev
}

im trying to make a simple discord.js bot

i am trying to make it so as soon as you type: mememe it will react with: your nickname is now:
my current code is
const Discord = require("discord.js");
const client = new discord.client();
client.login(process.env.SECRET);
const embed = new Discord.MessageEmbed()
.setTitle("This is Embed Title")
.setDiscription("this is embed discription")
.setColor("RANDOM")
.SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot", "op", "man", "power", "docter"];
client.on("ready", () => {
client.user.setPresence({ activity: { name: "brave" }, status: "invisible" });
});
client.on("message", (message) => {
if (message.content === "ding") {
message.channel.send === "dong";
}
if (message.content === "embed") {
message.channel.send(embed);
}
});
if (message.content("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index]);
}
but i dont know why it does not work it says as a error: Parsing error: Unexpected token
that is all and idk how to fix that
Edit : you guys were useless
I first want to say: Please fix your indents (I did it for you below here.
const Discord = require("discord.js")
const client = new Discord.Client()
client.login(process.env.SECRET)
// const embed = new Discord.MessageEmbed()
// .setTitle("This is Embed Title")
// .setDiscription("this is embed discription")
// .setColor("RANDOM")
// .SetFooter("This is Embed Footer");
const nicknames = ["dumbass", "idiot" , "op" , "man" , "power" , "docter"]
client.on("ready" , () => {
client.user.setPresence({ activity: { name: "brave"}, status: "invisible"})
})
client.on("message" , message => {
if(message.content === ("ding")) {
message.channel.send === ("dong")
}
if(message.content === ("embed")) {
message.channel.send(embed)
}
if(message.content === ("mememe")) {
const index = Math.floor(Math.random() * nicknames.length);
message.channel.send(nicknames[index])
}
})
The issue was you were calling the mememe command wrong. Above you used messega.content === "..."
In the mememe command you used message.content("mememe"). This does not work. Changes it (or copying the code above should fix the issue. Maybe an idea for you. You could add a feature where it changes the Users Nickname instead of sending a random one.

How to make my bot give send messages permissions to the specified role id , when prompted "=heist roleid"

I've made a discord bot and made a function in which it unlocks the channel for the members role which is appointed to everyone in my server. I want to make it so that it requires the id that is going to be unlocked after writing its id so basically =heist roleid.
I want this to unlock the channel only for the given role.
My current code:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ('=')
var numeral = require('numeral');
client.once('ready', () => {
console.log('Dank heists is now online');
client.user.setPresence({
activity: {
type:"PLAYING",
name: "discord.io/heists",
status: "available",
}
});
});
else if (message.content.startsWith(prefix +'heist' )) {
message.channel.createOverwrite("793930139737128997", {
SEND_MESSAGES: true
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
const embed = new Discord.MessageEmbed()
.setTitle('HEIST HAS NOW STARTED!!!')
.setThumbnail('https://img2.pngio.com/unlocked-padlock-png-transparent-unlocked-padlockpng-images-lock-unlock-png-512_512.png')
.setColor('#1d35cf')
.setFooter('Manan, ')
.setDescription(" I HAVE UNLOCKED THIS CHANNEL SO PEOPLE CAN JOIN THE HEIST " )
message.channel.send(embed)
}
update and send the whole code all together if possible
I recommend you to learn JavaScript first and then learn the basics of Discord.js and Node.js.
Answer to your question :
else if (message.content.startsWith(prefix + "heist")) {
const roleT = message.content.replace(prefix + "heist", "").trim();
const role = message.guild.roles.cache
.filter((r) => r.name.toLowerCase() === roleT.toLowerCase())
.first();
if (!role) {
return message.channel.send("Please tag a role!");
}
message.channel
.createOverwrite(role.id, {
SEND_MESSAGES: true,
})
.then((channel) =>
console.log(channel.permissionOverwrites.get(message.author.id))
)
.catch(console.error);
const embed = new Discord.MessageEmbed()
.setTitle("HEIST HAS NOW STARTED!!!")
.setThumbnail(
"https://img2.pngio.com/unlocked-padlock-png-transparent-unlocked-padlockpng-images-lock-unlock-png-512_512.png"
)
.setColor("#1d35cf")
.setFooter("Manan, ")
.setDescription(
" I HAVE UNLOCKED THIS CHANNEL SO PEOPLE CAN JOIN THE HEIST "
);
message.channel.send(embed);
}

How to make a bot that deletes a message and posts it in another channel based on reactions

I'm trying to make it so when my bot picks up a reaction in a specific channel, it'll see if it hit 10 reactions on a specific reaction. Then it'll delete the reacted message and post it into another specific channel with a message attached to it.
Here's the code
doopliss.on('message', message => {
if (message.channel.id === "587066921422290953") {
setTimeout(function(){
message.react(message.guild.emojis.get('587070377696690177'))
}, 10)
setTimeout(function(){
message.react(message.guild.emojis.get('587071853609353256'))
}, 50)
setTimeout(function(){
message.react(message.guild.emojis.get('587070377704816640'))
}, 100)
}
});
const message = require("discord.js");
const emoji = require("discord.js");
const reaction = require("discord.js");
doopliss.on('message', message => {
if (message.channel.id === "587066921422290953") {
let limit = 2; // number of thumbsdown reactions you need
if (message.reaction.emoji.name == message.guild.emojis.get('587070377696690177')
&& reaction.count >= limit) message.reaction.message.delete();
let tcontent = message.reaction.message.content
let accept = message.guild.channels.get('587097086256873483')
accept.send(`${tcontent} \`\`\`This server suggestion has been accepted by the community! Great job! Now a staff member just needs to forward it to username.\`\`\``)
}})
Can't figure out how to do this.
Expected Result: Bot sees if post has 10 reactions, then delete it and take the same message to a different channel
Actual Result: An error occurs Cannot read 'channel' property
First I want to say that some question here like this one have what you search.
Moreover, the discord documentation and the guide provide an awaiting reactions section.
There is some other question that refer to the subject or the function used in the guide and by searching a bit you can even find question like this one which is almost the same thing as you.
However, here is a complete example of what you want to do. You can add a timer to the promise instead of just waiting. I didn't use the reaction collector because promise are a bit faster, but you can also create a management system of multiple collector , or use the client.on('messageReactionAdd').
const Discord = require('discord.js');
const config = require('./config.json');
const channelSuggestion = '<channelID>';
const channelSend = '<channelID>';
const emojiReact = '<emojiID>';
const prefixSuggestion = '!';
const reactionMax = 11;
const client = new Discord.Client();
client.on('ready', () => {
console.log('Starting!');
client.user.setActivity(config.activity);
});
client.on('message', (msg) => {
if ((msg.content[0] === prefixSuggestion) && (msg.channel.type === 'dm')){
sendSuggestion(msg);
}
});
function filter(reaction) {
return reaction.emoji.id === emojiReact;
}
function moveSuggestion(msg) {
client.channels.get(channelSend).send(msg.content)
.then(() => msg.delete()).catch(err => console.log(error));
}
function sendSuggestion(msg){
client.channels.get(channelSuggestion).send(msg.content.substr(1))
.then((newMsg) => newMsg.react(emojiReact))
.then((newMsgReaction) =>
newMsgReaction.message
.awaitReactions(filter, {max: reactionMax})//, time: 15000, errors: ['time']})
.then(collected => {
moveSuggestion(newMsgReaction.message);
})
// .catch(collected => {
// console.log(`After a minute, only ${collected.size} out of 10 reacted.`);
// })
);
}
client.login(config.token)
.then(() => console.log("We're in!"))
.catch((err) => console.log(err));
The bot will listen to dm message (I don't know how you want your bot to send the suggestion message, so I made my own way) which start with a !.
Then the bot will send a message to a specific channel, wait for N person to add a reaction, and then will send the message to another channel.

Resources