Attempt to create a command with 2 arguments - javascript

I am trying to make a command so that I enter two names and these names are identified as Query1 and Query2, however, I don't know how to do it, can someone help me?
const {MessageEmbed} = require('discord.js');
module.exports ={
name : 'battle',
aliases: ['batalha'],
run : async(client, message) => {
await message.delete();
const query1 = args[0].join(" ");
if(!query1) return message.reply('Adicione o primeiro nome!');
const query2 = args[1].join(" ");
if(!query2) return message.reply('Adicione o segundo nome!')
var embed = new MessageEmbed()
.setColor('RANDOM')
.setAuthor('BATALHA DE FOTOS', client.user.avatarURL)
.setDescription(`Marque o emoji de acordo com o seu voto: \n\n ${query1}: 😍 \n${query2}: 🤩`)
.setFooter(message.author.username, message.author.displayAvatarURL)
.setTimestamp()
.setThumbnail('https://i.imgur.com/1oHJJZQ.png')
const msg = await message.channel.send(embed)
await msg.react('😍')
await msg.react('🤩')
}
}
Error
(node:864) UnhandledPromiseRejectionWarning: ReferenceError: args is not defined
at Object.run (C:\Users\Pc\Desktop\RemakeGANGBOT\commands\info\battle.js:10:24)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

It looks like you aren't defining args. You can define it before running any code for your command by using:
const args = message.content.trim().split(/ +/g);

Related

DIscord.js UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body

I have an issue with my code.
if (command === 'channel'){
if (args.length == 0 ){
return message.channel.send(Aucun argument trouvé)
}
await message.guild.channels
.create(args[0] ,{
type : 'text' ,
})
.then((chan)=>{
var data = fs.readFileSync('test.json')
var parsedata = JSON.parse(data)
var test = 0
console.log(parsedata['category'])
try {
chan.setParent( parsedata['category'])
}catch{
message.channel.send("il s'emblerais que la commande category est mal été configuré ")
channel.delete()
console.log("end")
return
}
});
message.channel.send("channel "+args[0]+" crée :)")
};
I'm trying to create a channel and move it to a category. The category ID is stored in a file called test.json.
My problem is if the ID stored does not exist then the try-catch should stop the error and execute the code in the catch block.
but that is not the case.
Here is the error:
node:15548) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
parent_id: Category does not exist
at RequestHandler.execute (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async TextChannel.edit (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\structures\GuildChannel.js:355:21)
(Use node --trace-warnings ... to show where the warning was created)
<node_internals>/internal/process/warning.js:42
(node:15548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
<node_internals>/internal/process/warning.js:42
(node:15548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Thank for your help in advance
You receive the error as the parent category doesn't exist. If you want to catch this error, you'll need to use the await keyword in front of chan.setParent() (as the .setParent() method is asynchronous):
if (command === 'channel') {
if (args.length === 0) return message.channel.send('Aucun argument trouvé');
try {
let chan = await message.guild.channels.create(args[0], {
type: 'text',
});
let data = fs.readFileSync('test.json');
let parsedata = JSON.parse(data);
await chan.setParent(parsedata['category']);
message.channel.send(`channel ${args[0]} crée :)`);
} catch {
message.channel.send(
"il s'emblerais que la commande category est mal été configuré",
);
// not sure what channel you want to delete here
channel.delete();
}
}

How can I solve 'TypeError: userId is not a function' in my unban command?

I'm trying to create a unban command for my bot, but every time I want to test the command (!unban <userId>) I'm not getting the expected result. Instead, I'm getting an error as shown down below.
This is my code:
const Discord = require('discord.js')
module.exports = {
name: 'unban',
usage: '%unban <userId> <reason>',
description: 'To unban someone',
async execute(client, message, args) {
if (!message.member.hasPermission("BAN_MEMBERS")) return;
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.reply(`You do not have permission to unban`);
let userId = args[0];
if (!userId) return message.reply(`Please state a user ID to unban`);
let reason = args.slice(1).join(" ");
if (!reason) reason = "No reason mentioned";
if (userId === message.author.id) return message.reply(`You can not unban yourself`);
let bans = await message.guild.fetchBans();
if (bans.has(userId)) {
message.guild.members.unban(userId({ reason }))
message.channel.send(`Successfully unbanned **${userId}**`);
} else {
message.reply(`Provided ID is invalid or isn't a banned member`)
}
}
}
Here the error I'm getting:
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:23184) UnhandledPromiseRejectionWarning: TypeError: userId is not a function
at Object.execute (C:\Users\lolzy\OneDrive\Desktop\discordbot\commands\unban.js:19:41)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:23184) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23184) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that
are not handled will terminate the Node.js process with a non-zero exit code.
message.guild.members.unban(userId({ reason })) should be message.guild.members.unban(userId, reason), since userId isn't a function.

I am getting a 400 bad request while using google custom search with discord.js! what am I doing wrong here?

I am building a discord bot which searches a query on google using the custom search api but i am getting this error! here's my code, what am i doing wrong?
const Discord = require("discord.js");
const request = require("node-superfetch");
var fs = require('fs');
module.exports = {
name: 'google',
description: "searches google ",
cooldown: 10,
permissions: [],
async execute(message, args, cmd, client, Discord) {
let googleKey = "XXXX";
let csx = "be4b47b9b3b849a71";
let query = args.join(" ");
let result;
if(!query) return message.reply("Please enter a Valid Query");
result = await search(query);
if (!result) return message.reply("Invalid Search");
const embed = new Discord.MessageEmbed()
.setTite(result.title)
.setDescription(result.snippet)
.setImage(result.pagemap ? result.pagemap.cse_thumbnail[0].src : null)
.setURL(result.link)
.setColor(0x7289DA)
.setFooter("Powered by Google")
return message.channel.send(embed);
async function search(query) {
const { body } = await request.get("https://customsearch.googleapis.com/customsearch/v1").query({
key: googleKey, cs: csx, safe: "off", q: query
});
if(!body.items) return null;
return body.items[0];
}
}
}
ERROR MESSAGE: (node:10944) UnhandledPromiseRejectionWarning: Error: 400 Bad Request
at Request._request (D:\Coding\FLASH\node_modules\node-superfetch\index.js:58:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async search (D:\Coding\FLASH\commands\google.js:31:26)
at async Object.execute (D:\Coding\FLASH\commands\google.js:17:14)
(Use node --trace-warnings ... to show where the warning was created)
(node:10944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Cannot read property 'get' of undefined (node js discord js "discord bot")

Dicord bot and sorry by my english is some bad:
client.on("ready", () => {
console.log(`Genesis bot online!`);
client.user.setPresence({
status: "online",
game: {
name: "Official Discord Bot",
type: "PLAYING" //PLAYING, LISTENING, WATCHING
}
});
setInterval(async function(){
let msg = await client.channels.cache.get(channelID).channel.messages.cache.get(messageID);
let stafflist = new MessageEmbed()
.setColor("GOLD")
.setTitle("Staff Members")
.setDescription(client.guilds.cache.get(serverID).roles.cache.find((r) => r.name == "➦「Staff Member」").members.map((m) => `\`${m.user.tag}\``).join(", "));
msg.edit(stafflist)
}, 3000);
});
this is the complete error:
(node:276) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'get' of undefined
at Timeout._onTimeout (N:\Genesis bot\Genesisbot2.0\index.js:34:47)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) (Use node --trace-warnings ... to show where the warning was created) (node:276) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled
promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:276) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.

Discord JS V11 BAN COMMAND

Hello I have a ban command. Also I have a error. This is a code
I want solve. But I don't.
const Discord = require('discord.js')
module.exports = {
komut: "ban",
açıklama: "",
kategori: "moderasyon",
alternatifler: ["!ban", "!yasakla"],
kullanım: "!ban",
yetki: "BAN_MEMBERS"
}
module.exports.baslat = (message) => {
// if(!message.member.hasPermission(["BAN_MEMBERS"])) return message.channel.send("Ban atabilmek için yetkili olman gerek!")
let banMember = message.mention.members.first() || message.guild.member.get(args[0])
if(banMember) return message.channel.send("Lütfen banlamak istediğiniz kişiyi etiketleyin!")
let reason = args.slice(1).join(" ")
if (!reason) reason = "Lütfen bir sebep belirtiniz!"
// if(!message.guild.me.hasPermission(["BAN_MEMBERS" , "ADMINISTRATOR"])) return message.channel.send("Bu komutu kullanmak için yetkim yok")
message.delete()
banMember.send(`Merhaba, iyi günler dilerim. ${message.guild.name} adlı sunucudan ${reason} sebebiyle banlandın.`).then(() =>
message.guild.ban(banMember, {days : 1 , reason : reason})).catch(err => console.log(err))
message.channel.send(`**${banMember.user.tag}** banlandı.`)
let embed = new Discord.RichEmbed()
.setColor("RED")
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL)
.addField("Moderasyon :", "ban")
.addField("Kişi : ", banMember.user.username)
.addField("Banlayan Admin :", message.author.username)
.addField("Sebep : ", reason)
.addField("Date :", message.createdAt.toLocaleString())
let sChannel = message.guild.channels.find(c => c.name === "ban-log")
sChannel.send({embed:embed})
};
This is a terminal error :
(node:16116) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'members' of undefined
at Object.module.exports.baslat (C:\Users\RYZEN\Desktop\U4 BOT\komutlar\moderasyon\ban.js:16:33)
at AdvancedClient.<anonymous> (C:\Users\RYZEN\Desktop\U4 BOT\node_modules\discordjs-advanced\src\client.js:549:5)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:16116) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16116) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Please help me
Okey, don't see a
module.exports = {
komut: "ban",
açıklama: "",
kategori: "moderasyon",
alternatifler: ["!ban", "!yasakla"],
kullanım: "!ban",
yetki: "BAN_MEMBERS"
}
Note : I change members and users. Bot don't work again.
(Sorry for my bad english :) )
You are using message.mention.members.first() but it should be mentions -
message.mentions.members.first()

Categories