After some modification, instead of message is not defined, it is receivedMessage.channel.bulkdelete(args[0].then (() => {
ReferenceError: receivedmessage is not defined. I am not really sure myself what does that mean because im new to node.js and javascript. If there is any mistakes I made please tell me!
client.on('message', (receivedMessage) => {
if (receivedMessage.author == client.user) { // Prevent bot from responding to its own messages
return
}
if (receivedMessage.content.startsWith("?")) {
processCommand(receivedMessage)
}
})
function processCommand(receivedMessage) {
let fullCommand = receivedMessage.content.substr(1) // Remove the leading exclamation mark
let splitCommand = fullCommand.split(" ") // Split the message up in to pieces for each space
let primaryCommand = splitCommand[0] // The first word directly after the exclamation is the command
let arguments = splitCommand.slice(1) // All other words are arguments/parameters/options for the command
console.log("Command received: " + primaryCommand)
console.log("Arguments: " + arguments) // There may not be any arguments
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
clearCommand(arguments, receivedMessage)
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help`, `?multiply` or '?clear'")
}
function helpCommand(arguments, receivedMessage) {
if (arguments.length > 0) {
receivedMessage.channel.send("It looks like you might need help with " + arguments + ".Try `!multiply 2 4 10` or `!multiply 5.2 7`")
} else {
receivedMessage.channel.send("I'm not sure what you need help with. Try `?help [topic]`")
}
}
function multiplyCommand(arguments, receivedMessage) {
if (arguments.length < 2) {
receivedMessage.channel.send("Not enough values to multiply. Try `!multiply 2 4 10` or `!multiply 5.2 7`")
return
}
let product = 1
arguments.forEach((value) => {
product = product * parseFloat(value)
})
receivedMessage.channel.send("The product of " + arguments + " multiplied together is: " + product.toString())
}
}
function clearCommand (arguments, receivedMessage) {
if (!recievedMessage.member.hasPermission("MANAGE_MESSAGES"))
return receivedmessage.reply("You have no permission to use this command.Sad.");
if (!args[0])
return receivedMessage.channel.send("Please specify a number.")
}
receivedmessage.channel.bulkDelete(args[0]).then(() => {
receivedMessage.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
}
,)
You need to use receivedMessasge instead of message, as thats the name you choose in that function.
It kinda seems like you dont really have much experience and I would recommend you to read the offical discord.js guide: https://discordjs.guide . It will teach you how to write Discord Bots without needing to copy a lot of weired stuff into your Code!
1) You have defined receivedMessage instead of messsage
2) The code for clear command is not in any function and it executes once, before any messages.
You need to use receivedMessage instead of message and insert the code in the processCommand function
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply("You have no permission to use this command.Sad.");
if (!args[0]) return message.channel.send("Please specify a number.")
message.channel.bulkDelete(args[0]).then(() => {
message.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
});
// or create a function for this command
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help` or `?multiply`")
}
Related
I've made a tempmute command for my discord bot and it almost works. It has quite a few foolproofing measures like preventing the bot from muting themselves, not working if the time isn't specified and such. I am using the npm ms package to deal with the mute duration (https://www.npmjs.com/package/ms). when instead of specifying an amount of time I type in gibberish it works as intended and replies with the correct message. The problem is that when I type in a 100% correct command it responds asthough I didn't specify the time correctly instead of muting the user for that amount of time. here's how it looks. Any ideas as to why that is?
My code is here:
const ms = require('ms');
const { Permissions, MessageActionRow, UserFlags } = require('discord.js');
module.exports = {
name: 'tempmute',
description: "Temporarily mutes a user",
execute(message, args)
{
const target = message.mentions.members.first();
let muteRole = message.guild.roles.cache.find(role => role.name === "muted");
if(message.member.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
{
if(target)
{
let memberTarget = message.guild.members.cache.get(target.id);
if(target.id == 'myBotsID')
{
message.reply("I can't mute myself.")
}
else if(message.member == target)
{
message.reply("You can't mute yourself!")
}
else if(memberTarget.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
{
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
}
else
{
if(!args[1])
{
return message.reply("Time not specified.")
}
else
{
let time = ms(args[1])
memberTarget.roles.add(muteRole.id);
try {
message.reply("<#" + memberTarget.user.id + ">" + "has been muted for " + ms(ms(args[1])).catch(console.error))
setTimeout(function () {
memberTarget.roles.remove(muteRole.id);
}, time);
} catch (err) {
message.reply("Can't transform that into milliseconds `"+args[1]+"`")
return
}
}
}
}
else
{
message.reply("You have to mention a valid member of this server.")
}
}
else
{
message.reply("You can't use that.")
}
}
}
Okay so I figured it out. Here's the problematic code:
try {
message.reply("<#" + memberTarget.user.id + ">" + "has been muted for " + ms(ms(args[1])).catch(console.error))
setTimeout(function () {
memberTarget.roles.remove(muteRole.id);
}, time);
} catch (err) {
message.reply("Can't transform that into milliseconds `"+args[1]+"`")
return
}
IDK why but the ".catch(console.error))" (which is a leftover code and shouldn't be there in the first place) caused it to behave differently aka treat everything as an incorrectly specified time and returned the corresponding message instead of muting the member for the specified amount of time. After removing that short part of code everything is working as intended.
I have 2 simple functions the first is to check the code if it's true or not. then I have the second one where some things happening. I want to run the second function only if the user enters the right code. I tried with Settimeout but after some second the second function runs without passing the test of the first.
Thank you for Help
Both are in the global scope
//Check The code To start the conversations
function CheckCode(msg) {
const num = msg;
//Check if The code is Valid
if(num == 333 ) {
MessageEl.innerHTML = `<div>${msg} Code is Right, How are you Today!</div>`;
return;
}
else {
MessageEl.innerHTML = `<div>${msg} Code is Wrong, Please Speak The Right Code To talk to me</div>`;
return;
}
}
function TalkTheTalk(msg) {
const talk = msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
const result = greetings.find((greeting)=> {
return greeting === talk;
});
if(result) {
MessageEl.innerHTML = '<div> Im so happy to hear that! What can i do for you today ! </div>';
}
else {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
}
Try Promise
var pro = function () {
return new Promise((resolve, reject) => {
function CheckCode(msg) {
const num = msg;
if(num == 333 ) {
MessageEl.innerHTML = `<div>${msg} Code is Right, How are you Today!</div>`;
resolve(num)
return;
}
else {
MessageEl.innerHTML = `<div>${msg} Code is Wrong, Please Speak The Right Code To talk to me</div>`;
return;
}
}
})
}
pro().then(check_data => {
if(typeof check_data == "number") {
TalkTheTalk(check_data)
}
});
function fn1( rule ) {
//The rules here
if( rule == 'right' ) return true;
return false;
}
function fn2() {
if( fn1('right') ) {
// fn2 codes here
console.log('fn1, right');
}
}
fn2();
Set a bool to true when the correct code is entered and check it to issue the response you wish. Sorry the indentation is wrong.
//Check The code To start the conversations
boolean correct_code = 0;
function CheckCode(msg) {
const num = msg;
//Check if The code is Valid
if(num == 333 ) {
MessageEl.innerHTML = `<div>${msg} Code is Right, How are you Today!</div>`;
correct_code = true;
}
else {
MessageEl.innerHTML = `<div>${msg} Code is Wrong, Please Speak The Right Code To talk to me</div>`;
}
}
function TalkTheTalk(msg) {
const talk = msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
const result = greetings.find((greeting)=> {
return greeting === talk;
});
if(result && corect_code == true) {
MessageEl.innerHTML = '<div> Im so happy to hear that! What can i do for you today ! </div>';
}
else {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
}
You can do that in various ways.
Here are some solutions:
Call function TalkTheTalk() inside function CheckCode() which is satisfying condition.
Use some Boolean flag to check condition is satisfied or not, and check that flag in 'if' condition of function.
function checkCode( msg ) {
//check the message and return appropriate boolean value
if( msg == 'right' ) return true;
return false;
}
function TalkTheTalk(msg) {
if( checkCode(msg) {
//this executes when the check code is satisfied
console.log('fn1, right');
}
}
It's been 2 days since I'm trying to understand my error. So far what I've learnt is that i will never be able to bypass "undefined" returned value because i cannot understand callback or promises... I rode all the poste , did some easy exemple , but I 'm not undertanding how to make it happen on my code ...
function realloot(data){
return data;
console.log(`${data}`);
}
function lootbox_openning(callback, user, type, nombre){
let sqlQueryopenbox = `SELECT item_qty FROM users_items WHERE discord_id = '${user}' AND item_id = ${type};`
let token_won=0;
let real_token_won=0;
let common_pp_looted = 0;
let rare_pp_looted = 0;
let epic_pp_looted = 0;
db.query(sqlQueryopenbox, (err, rows) => {
let user_box_real_qty = rows[0].item_qty;
let sql;
if (err) {
real_token_won="sql error";
throw err;
}
if (nombre > user_box_real_qty){real_token_won="error number";}
else {
//function open
if (type==1) {
for (var i = 0; i <= nombre; i++){
token_won=little_box_open();
real_token_won=real_token_won+token_won;
}
var myreturn = callback(real_token_won);
console.log(`${myreturn}`);
return myreturn;
}
if (type==2) {}
if (type==3) {}
}
});
}
//this is a bot discord so huge on.message here...
case "open":
if (!args[1]) return message.channel.send('please give value box | bigbox');
if (args[1] ==='box' ){
if (!args[2]) {message.channel.send ("Specify number please");}
if (args[2]) {
var number = parseInt(args[2]);
if (Number.isInteger(number)){
message.channel.send ("You re openning "+args[2]+" boxes");
**var token_won = lootbox_openning(realloot, message.author.id, 1, args[2]);** //PROBLEM IS HERE
if (token_won==="error number"){message.channel.send ("Vous n'avez pas assez de box !");}
else {message.channel.send ("you won : "+token_won+" tokens !");}
}
else message.channel.send ("Give a valid number");
}
}
Please be gentle, I already hit my head so hard on others posts but it seems like I need more explanations...
async logic is a common place for newcommers to get tripped up on. But, it basically boils down to doing this:
Example of a synchronous code:
(this is assuming that db.query() was written as a sync function, which its not)
function doQuery(id) {
let res = db.query(`SELECT * FROM table WHERE id=${id}`)
return res
}
Example of asynchronous code (which using db.query() as an async function)
function doQuery(id, callback) {
db.query(`SELECT * FROM table WHERE id=${id}`, function(res) {
callback(res)
})
}
The main difference here is that instead of doing return res you have to do callback(res). This will always be the case when working with async code.
And its important to note that once you're in the async world, you can never go back to a sync world. i.e. This is impossible:
// some sync logic
let resultOfAsyncOperation = someAsyncFunction()
// some sync logic
Once you're dealing with callbacks, you have to use callbacks everywhere. This is because the user of an async function has to itself be async. The only exception is if you don't care about what's getting returned or when, you just want it to go off and do some task.
So, this is how these principles applies to your specific chunk of code. This snippet of code is exactly the issue I was describing - you're trying to use an async function inside of sync logic.
var number = parseInt(args[2]);
if (Number.isInteger(number)) {
message.channel.send("You re openning " + args[2] + " boxes"); **
var token_won = lootbox_openning(realloot, message.author.id, 1, args[2]); ** //PROBLEM IS HERE
if (token_won === "error number") {
message.channel.send("Vous n'avez pas assez de box !");
} else {
message.channel.send("you won : " + token_won + " tokens !");
}
} else message.channel.send("Give a valid number");
You'll have to convert this chunk of code to also be async, like this:
message.channel.send("You re openning " + args[2] + " boxes");
function callback(token_won) {
realloot(token_won)
if (token_won === "error number") {
message.channel.send("Vous n'avez pas assez de box !");
} else {
message.channel.send("you won : " + token_won + " tokens !");
}
}
lootbox_openning(callback, message.author.id, 1, args[2]);
(it's possible I didn't fully understand how you intended your original code to work, so take this example with a grain of salt. It shows the principle, but you'll have to tweak it to work for your needs)
I'm working on a kick command for a Discord bot in Discord.js. How it works is a previous function passes an array of user IDs to attempt to kick from the server. For some reason, the for loop is repeating more than it should and the i value doesn't seem to change sometimes.
Here's my code:
exports.kick = async (guild, targets, member, reason, bot) => {
var modRoleQuery = await exports.queryModRole(guild, member, bot);
var outputMessage = '';
if (modRoleQuery === false && !member.hasPermission('ADMINISTRATOR') && member != guild.me) return `You do not have permission to execute this command.`;
else if (targets.length === 0) return `Command usage: ${config.prefix}kick <#mentions/IDs> [reason]`;
else if (!guild.me.hasPermission('KICK_MEMBERS')) return `I require the \`Kick Members\` permission to execute this command.`;
else if (targets.length > 10) return `You may only kick 10 members at a time.`;
else if (reason.length > 1000) return `The kick reason must not exceed 1000 characters. Currently, it is ${reason.length}.`;
for (i = 0; i < targets.length; i++) {
console.log(`checking ${targets[i]}, ${i}`);
let targetMember = guild.member(targets[i]);
if (targetMember) {
if (targetMember.kickable) {
let targetMemberModRole = await exports.queryModRole(guild, targetMember, bot);
if ((targetMemberModRole || targetMember.hasPermission('ADMINISTRATOR')) && !member.hasPermission('ADMINISTRATOR')) {
outputMessage += `Unable to kick \`${targetMember.user.tag}\`: Only administrators can kick people with the moderator role and/or admin perms.\n`
} else {
await targetMember.user.send(`You were kicked from ${targetMember.guild.name} by ${member.user.tag}:\nReason: \`${reason}\``).catch(err => {});
await targetMember.kick(`[${member.user.tag}] ${reason}`);
exports.modLogEvent(bot, guild, `KICK`, targetMember.user, member.user, reason);
outputMessage += `Successfully kicked \`${targetMember.user.tag}\`\n`;
}
} else {
outputMessage += `Unable to kick \`${targetMember.user.tag}\`: I don't have permission to kick them.\n`;
}
} else {
outputMessage += `Unable to kick \`${targets[i]}\`: They don't seem to be in this server.\n`;
console.log(`${targets[i]} is not a member`)
}
}
outputMessage += `**Kick Reason:**\n\`${reason}\``;
return outputMessage;
}
When the size of the array is 1, this works as expected, however when it is more than 1, it doesn't. I've put in some console.log() functions for debugging purposes.
For some reason, the i value gets stuck on 1. I also ran it a bit earlier (this is before I added the console.log()s) and it behaved even more oddly:
I've been trying to debug this for over a day now and I'm not getting anywhere. Any assistance would be greatly appreciated.
I made a bot with purpose to manage discord roles and here's my code briefly
bot.on('message', (message) => {
const parts = message.content.split(' ');
if (parts[0] == 'Platform' || 'platform') {
if (parts[1] == 'iOS') {
message.channel.send(`thx, ${message.author}`)
message.member.roles.add(iOS);
}
else {
message.channel.send(`nooo`)
}
}
}
Why my else command keeps going over and over? How am I supposed to do in order to stop it?
Your code should read:
if (parts[0] == 'Platform' || parts[0] == 'platform') {