Doesn't create a channel - node.js

I want to use !test epicchannel (epicchannel being the name of the channel , for example if I want to use !test infinite , it will create a channel named testing-infinite ) but it doesn't work. it just makes a channel named testing-test
I've tried using message.content.startsWith, but if I do that, nothing happens.
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = '!';
client.on("message", async message => {
if(message.content.startsWith === '!test') {
if(message.author.id === '560761436058550273') {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
message.guild.createChannel(`testing-${args}`).then(channel => {
channel.setTopic(`Today we will test: ${args}`)
})
}else{
if(!message.author.id === '560761436058550273') {
return;
}
}
}
});
client.login('login is here');
No errors, I just want it to use !test infinite to create a channel named testing-infinite

Simply change
const args = message.content.slice(prefix.length).trim().split(/ +/g);
to
const [_, args] = message.content.trim().split(' ')
That way we split the message by spaces after trimming it, and we actually save the second part in args variable by doing some array destructuring assignment.

args is an array, just join testing- and args[1] to get the name you want:
rodrigo:~:node
> const prefix = '!';
undefined
> var message = { content:'!test epicchannel'}
undefined
> message
{ content: '!test epicchannel' }
> const args = message.content.slice(prefix.length).trim().split(/ +/g);
undefined
> args
[ 'test', 'epicchannel' ]
> var channelName = `testing-${args[1]}`;
undefined
> channelName
'testing-epicchannel'

Related

Need to send message twice in order to get a response

When I have this code here:
client.on("message", msg => {
const args = msg.content.trim().split(/ +/g);
let second = args[1];
let x = Math.floor((Math.random() * second) + 1);
if(msg.content === "random") {
msg.channel.send(`${x}`)
console.log(x)
console.log(second)
}
})
I need to send "random 10 (example)" twice and it still doesn't work cause it uses the "random" as the input for "second¨ how do i make this work?
Since "msg" is a string, you need to parse it as an integer before preforming an operation on it. I recommend replacing the "let x" line with the following:
let x = Math.floor((Math.random() * parseInt(second)) + 1);
parseInt is an internal function that takes a string with number contents and turns it into an integer.
const triggerWords = ['random', 'Random'];
client.on("message", msg => {
if (msg.author.bot) return false;
const args = msg.content.trim().split(/ +/g);
let second = args[1];
let x = Math.floor((Math.random() * parseInt(second)) + 1);
triggerWords.forEach((word) => {
if (msg.content.includes(word)) {
msg.reply(`${x}`);
}
});
});
To add on to quandale dingle's answer, what you can do with your bot is to create a command handler, which will make the developing process much easier and will look nice. If you don't really want to create a command handler, you can also use the following code:
if (message.content.startsWith(prefix)){
//set a prefix before, and include this if statement in the on message
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const commandName = args.shift().toLowerCase()
//use if statements for each command, make sure they are nested inside the startsWith statement
}
If you want to create a command handler, there's some sample code below. It works on discord.js v13, but I've no idea if it will work in v12. This is a more advanced command handler.
/*looks for commands in messages & according dependencies
or command handler in more simple terms*/
const fs = require("fs");
const prefix = "+"; //or anything that's to your liking
client.commands = new Discord.Collection();
fs.readdirSync("./commands/").forEach((dir) => {
const commandFiles = fs.readdirSync(`./commands/${dir}/`).filter((file) =>
file.endsWith(".js")
); //subfolders, like ./commands/helpful/help.js
//alternatively... for a simpler command handler
fs.readdirSync("./commands/").filter((file) =>
file.endsWith(".js")
);
for (const file of commandFiles) {
const commandName = file.split(".")[0]
const command = require(`./commands/${file}`);
client.commands.set(commandName, command);
}
});
//looks for commands in messages
client.on("messageCreate", message => {
if (message.author == client.user) return;
if (message.content.startsWith(prefix)){
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const commandName = args.shift().toLowerCase()
const command = client.commands.get(commandName)
if (!command) return;
command.run(client, message, args)
}
});

DiscordAPIError: Invalid Form Body Code : 50035 , Slash commands

Hello So I was developing my own slash command handler for the Discord.js v13 bot
But I have run into a snag.... When I collect the array of all slash commands and their respective options to register into the commands.set() method I get an error which is :
**> throw new DiscordAPIError(data, res.status, request);
> ^
>
> DiscordAPIError: Invalid Form Body options[2]: Required options must
> be placed before non-required options
> at RequestHandler.execute (C:\Users\Mihir\Desktop\FunMod\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
>
> at processTicksAndRejections (node:internal/process/task_queues:96:5)
> at async RequestHandler.push (C:\Users\Mihir\Desktop\FunMod\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
> at async GuildApplicationCommandManager.set (C:\Users\Mihir\Desktop\FunMod\node_modules\discord.js\src\managers\ApplicationCommandManager.js:146:18)
> at async Object.execute (C:\Users\Mihir\Desktop\FunMod\slashregistering.js:71:13) { method:
> 'put', path:
> '/applications/922152514420363285/guilds/933052184432636014/commands',
> code: 50035, httpStatus: 400,**
This is the complete code of the slashregistering.js ( pls ignore the code typing style... )
**const fs = require('fs')
const db= require('quick.db')
module.exports = {
async execute(client){
const categories = ['MODERATION' , 'FUN' ,'ACTIONS' , 'UTILITY']
const registeredCommandsArray = new Array()
const guildId = '933052184432636014'
const guild = client.guilds.cache.get(guildId)
//console.log(client.guilds.cache);
let commands
var commandsarray = new Array()
if(guild){
commands = guild.commands
}
else{
commands = client.application?.commands
}
//console.log(commands)
let data
data = await db.get('slashcommands')
if(data){
var scommands = new Array()
var unRegisteredCommands
const slashcommands = await guild.commands.fetch()
unRegisteredCommands = slashcommands.filter(a => !data.includes(a.name))
for(var e in unRegisteredCommands){
scommands.push(e.name)
}
for(const category of categories){
for(const file of scommands){
const command = require(`./slashcommands/${category}/${file}.js`)
//console.log(command , category)
commandsarray.push({
name : command.name,
description : command.description,
options : command.options
})
}
}
data.concat(scommands)
//console.log(data)
commands.set(commandsarray)
console.log(`Loaded ${scommands.length} commands.`)
await db.set('slashcommands' , data)
}
else{
for(const category of categories){
const slashCommandFiles = fs.readdirSync(`./slashcommands/${category}`).filter(file => file.endsWith('.js'))
for(const file of slashCommandFiles){
const command = require(`./slashcommands/${category}/${file}`)
//console.log(command , category)
commandsarray.push({
name : command.name,
description : command.description,
options : command.options
})
registeredCommandsArray.push(command.name)
}
}
console.log(`Loaded ${registeredCommandsArray.length} commands.`)
await commands.set(commandsarray)
await db.set('slashcommands' , registeredCommandsArray)
}
}
}**
Its all working fine until I reach the commands.set(commandsarray) ... Please help ! and thanks in advance!

Trying to learn module.exports but having some problem

I'm using discord.js from some week and now I would like to do that when someone enter in a vocal chat, the bot will send a message in the console. I tried using this code in the main file of the bot and perfectly worked but when I try to put it in another file and export it in the main file it doesn't work. Someone that can help me and maybe explain it?
main.js:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
const a = require("./commands/test1")
if(client.guilds.cache.get("<guild if>")){
return a
}
test1.js:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
module.exports = {
execute() {
client.on('voiceStateUpdate', (oldState, newState) => {
if (newState.channelID === null) console.log('Inside channel', oldState.channelID);
else if (oldState.channelID === null) console.log('Outside channel', newState.channelID);
else console.log('user moved channels', oldState.channelID, newState.channelID);
})}}
In this part in your main.js file:
const a = require("./commands/test1")
if(client.guilds.cache.get("<guild if>")){
return a
}
The a variable contains an object like { execute: function(){...} }. You not calling the execute function.
Try this:
const { execute } = require("./commands/test1")
if(client.guilds.cache.get("<guild if>")){
return execute();
}
Can you try adding the keyword function before the word execute()?
Alternatively, you could do:
// \/ you can put arguments here
module.exports.execute = () => {
// function here
}
and then in your index file..
const a = require("./commands/test1")
if(client.guilds.cache.get("<guild if>")){
return a.execute(this is where you would put your arguments)
}
Happy coding!

Making a simple music bot for discord server, not working

Working on making a bot for a personal discord server, wanting it to simply join general voicechat when command "Blyat" is detected, play mp3 file, when its done to leave. Code:
var Discord = require('discord.js');
var client = new Discord.Client();
var isReady = true;
client.on('message', message => {
if (command === "Blyat") {
var VC = message.member.voiceChannel;
if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.playFile('C:\Users\Wyatt\Music\soviet-anthem.mp3');
dispatcher.on("finish", end => { VC.leave() });
})
.catch(console.error);
};
});
client.login('token, not putting in code, is there in real code');
Error: "ReferenceError: command is not defined
at Client. (C:\Users\jeffofBread\Desktop\Discord Bot\main.js:6:5)"
Any help or tips will be much appreciated, haven't coded in many years and have lost any knowledge I had once held.
Your problem comes from an unidentified variable. Fortunatly that is very easy to fix. All you have to do is define command before you call it.
For this we'll splice the message content into two parts. The command and any arguments that may be included like mentions or other words. We do that with:
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
Note: The args constant is an array.
Which would make your entire onMessage event look like this:
client.on('message', message => {
const prefix = "!";
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "blyat") {
var VC = message.member.voice.channel;
if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.play('C:\Users\Wyatt\Music\soviet-anthem.mp3');
dispatcher.on("finish", end => { VC.leave() });
})
.catch(console.error);
};
});

Bot sending a message in certain channel

I want to have a command which is similar to "say" command but it's only restricted to bot owner and only sent in one channel at a specific server. Any tips?
Here's my code (not working atm):
client.on("message", (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "+ubersay") {
if(message.author.id !== process.env.ownerID) return;
const sayMessage = args.join(" ");
message.delete().catch(O_o=>{});
client.channels.get(process.env.specifiedChannel).send(sayMessage);
}
});
The code should work flawlessly, the only thing that could be a problem is your const args = message.content.slice(prefix.length).trim().split(/ +/g); combined with if(command === "+ubersay") { Because this askes for your Command to be used in the format [prefix]+ubersay so if your prefix is + you would need to do ++ubersay

Resources