Trying to do close and open command quick.db - javascript

const db = require("quick.db");
module.exports.run = async (client, message, args) => {
let botfetch = db.fetch(`ddoskoruma_${message.guild.id}`);
let kapaç = args[0];
if (kapaç === "aç") {
db.set(`ddoskoruma_${message.guild.id}`)
console.log("Open")
} else if (botfetch) {
console.log("Already open.")
}
if (kapaç === "kapat") {
db.delete(`ddoskoruma_${message.guild.id}`)
console.log("Closed.")
} else if (!botfetch) {
console.log("Already close.")
}
}
module.exports.conf = {
name: "ddoskoruma"
};
I am trying to do close and open commands with quick.db. I want to do if command already closed, reply "It's already closed/opened." but I'm trying this code for it but I'm getting this error:
(Sorry for my bad english)
(node:26756) UnhandledPromiseRejectionWarning: TypeError: Input cannot be undefined # ID: ddoskoruma_640958795643617284

You need to provide a key and a value when you use db.set(). For example:
db.set(`ddoskoruma_${message.guild.id}`, 1);
Just edit this line and it will work.

Related

Code stopped working, didn't change a thing. Error is: TypeError: Cannot read properties of undefined (reading 'commands')

When i run 'node .' in the terminal it produces this error
TypeError: Cannot read properties of undefined (reading 'commands')
This is strange as I haven't changed anything, I simply just came back to my work.
This is the Commands.js file :
const { Perms } = require("../Validation/Permissions");
const { Client } = require("discord.js");
/**
* #param {Client} Client
*/
module.exports = async (client, PG, Ascii) => {
const Table = new Ascii("Command Loaded");
CommandsArray = [];
(await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
const command = require(file);
if(!command.name)
return Table.addRow(file.split("/")[7], "⛔ FAILED", "Missing a
name.")
if(!command.context && !command.description)
return Table.addRow(command.name, "⛔ FAILED", "Missing a
description.")
if(command.permission) {
if(Perms.includes(command.permission))
command.defaultPermission = false;
else
return Table.addRow(command.name, "⛔ FAILED", "Permission is
invalid.")
}
client.commands.set(command.name, command);
CommandsArray.push(command);
await Table.addRow(command.name, "✔ SUCCESSFUL");
});
console.log(Table.toString());
// Permissions Check //
client.on("ready", async () => {
const MainGuild = await
client.guilds.cache.get("961963167410454598");
MainGuild.commands.set(CommandsArray).then(async (command) =>
{
const Roles = (commandName) => {
const cmdPerms = CommandsArray.find((c) => c.name ===
commandName).permission;
if(!cmdPerms) return null;
return MainGuild.roles.cache.filter((r) =>
r.permissions.has(cmdPerms));
}
const fullPermissions = command.reduce((accumulator, r)
=> {
const roles = Roles(r.name);
if(!roles) return accumulator;
const permissions = roles.reduce((a, r) => {
return [...a, {id: r.id, type: "ROLE",
permission: true}]
}, [])
return [...accumulator, {id: r.id, permissions}]
}, [])
await MainGuild.commands.permissions.set({
fullPermissions });
});
});
}
The full error is :
C:\Users\wrigh\Documents\Discord Bots\Practice Bot -
Copy\Structures\Handlers\Commands.js:43
MainGuild.commands.set(CommandsArray).then(async (command) =>
{
It's line 43, or just under // Permissions Check // if you can't find it.
Any help is appreciated.
Again there have been no changes except uploading it to github, this is when i realised it stopped working.
Sorry about the format of the code, it got messed up when i pasted it in.
If you need to look at any other files please just ask!
If you are trying to access an attribute of an object (ex. object.userName) and it's undefined, you should console log out the entire object, and see if that property even exists on the object, or if the entire object is undefined as well.
From that point, if the client object does not have the property you're looking for, or if it is undefined itself, you can trace your issue down further from there.
I appreciate you uploading your code, but typically you want to have the code embedded into your question itself so we can run it there and inspect it properly.

Discord bot failing to call username of person who calls it

I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.

Why since my switch to discord js 13, the messageCreate Event bug?

I explain my problem: I use a js file external to my commands for my Events and I have the impression that there are some things that do not work correctly in my messageCreate.js which however worked before with Discord .JS in version 12.
For example, when I want to return as soon as the bot sends a message it doesn't work via the messageCreate.js, I have to put it in all of my commands etc.
In my commands I noticed that the arguments do not work whereas before I had no problems. I was able to verify this by putting a
if(args == undefined) return console.log("test")
and the message "test" was displayed in the console as soon as I tried.
I put my code below, hoping you can help me. :)
the part of my index.js that deals with events:
fs.readdir("./Events/", (err, files) => {
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.cyan('Chargement des évènements ...')}`)
if (err) return Debug.logs(err)
files.forEach(async (file) => {
if (file.endsWith(".js")) {
const event = require(`./Events/${file}`)
let eventName = file.split(".")[0]
try {
bot.on(eventName, event.bind(null, bot))
delete require.cache[require.resolve(`./events/${file}`)]
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.green('Event Chargé :')} ${chalk.cyan(file)}`)
} catch (error) {
Debug.logs(error)
}
} else {
return
}
})
})
my messageCreate.js :
const env = process.env
const chalk = require('chalk')
const moment = require('moment')
const Debug = require('../utils/Debug')
const config = require("../config.json")
module.exports = async (bot, message) => {
if(message.channel.type === "DM"){
if(message.author.bot) return;
message.reply("Les commandes en **messages privés** sont actuellement **désactivées** !")
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a envoyé ${chalk.green(message.content)} en DM`)
}else{
if (!message.author.bot) {
if (message.content.startsWith(config.prefix)) {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = bot.commands.get(command)
if (cmd) {
await cmd.run(bot, message, args)
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a utilisé ${chalk.green(command)} ${chalk.cyan(args.join(" "))}`)
} else {
return
}
} else {
return
}
} else {
return
}
}
}
and one exemple of command who not work with messageCreate.js :
const Discord = require("discord.js");
module.exports.run = async (bot, message, config, args) => {
message.delete();
if(args == undefined) return console.log("wtf that not work ?")
}
module.exports.help = {
name:"test",
desc:"test commands !",
usage:"test",
group:"autre",
examples:"$test"
}
module.exports.settings = {
permissions:"false",
disabled:"false",
owner:"false"
}
as soon as I run the command with argument or without any argument, in both cases the console receives the message "wtf that not work?"
I hope you can help me! thanks in advance :)
Sorry if my english is bad but i'm french, not english !
In messageCreate.js, you call your command with the following:
// 3 arguments
await cmd.run(bot, message, args);
However, your command's run function is defined with 4 parameters:
async (bot, message, config, args) => {
// config = 'args', and args = undefined
}
To fix the issue, either:
Pass in a value for config, such as null:
await cmd.run(bot, message, null, args);
Make your function only have 3 parameters:
async (bot, message, args) => {
// ...
}

Discord bot clear command error [INVALID_TYPE]: Supplied options is not an object

When I or some random user try to use the !clear command I see this message in my channel.
"Yeah... That's not a number? I also can't delete 0 messages by the way.
Something went wrong... " + this error message.
TypeError [MESSAGE_BULK_DELETE_TYPE]: The messages must be an Array, Collection, or number.
In my console I get this error msg:
(node:28184) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied options is not an object.
this is my clear.js script:
const discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.deletetable) {
message.delete();
}
// Member doesn't have permission
if (!message.member.hasPermission("MANAGE_MESSAGES")) {
message.channel.send("You can't delete messages...").then(m => m.delete(5000));
}
// Check if args[0] is a number
if (isNaN(args[0]) || parseInt(args[0]) <= 0) {
message.channel.send("Yeah... That's not a number? I also can't delete 0 messages by the way.").then(m => m.delete(5000));
}
// Maybe the bot can't delete messages
if (!message.guild.me.hasPermission("MANAGE_MESSAGES")) {
message.channel.send("Sorry... I can't delete messages.").then(m => m.delete(5000));
}
let deleteAmount;
if (parseInt(args[0]) > 100) {
deleteAmount = 100;
} else {
deleteAmount = parseInt(args[0]);
}
message.channel.bulkDelete(deleteAmount, true)
.then(deleted => message.channel.send(`I deleted \`${deleted.size}\` messages.`))
.catch(err => message.channel.send(`Something went wrong... ${err}`));
}
module.exports.help = {
name: "clear"
}
Thanks in advance!
Greetings
You must return when one condition is not true.
For the command works you must give a number of messages to clear: !clear <Number>.
//...
// Member doesn't have permission
if (!message.member.hasPermission("MANAGE_MESSAGES")) {
return message.channel.send("You can't delete messages...").then(m => m.delete(5000));
}
// Check if args[0] is a number
if (isNaN(args[0]) || parseInt(args[0]) <= 0) {
return message.channel.send("Yeah... That's not a number? I also can't delete 0 messages by the way.").then(m => m.delete(5000));
}
// Maybe the bot can't delete messages
if (!message.guild.me.hasPermission("MANAGE_MESSAGES")) {
return message.channel.send("Sorry... I can't delete messages.").then(m => m.delete(5000));
}
//...
You can find more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
Hope this help !

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources