Can't find the message author - javascript

In this line of code I am trying to send private message, to initial message author. For some unknown reason there is an error:
(node:17560) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is this line of code:
const appStart = await message.author.send(questions[collectCounter++]);
Here is whole file:
const Discord = require("discord.js");
const {Client, Message, MessageEmbed} = require("discord.js");
module.exports = {
name: 'apply',
/**
*
* #param {Client} client
* #param {Messafe} message
* #param {String[]} args
*/
run : async(client, message, args) => {
const questions = [
"What is your in-game name?",
"Do you accept the rules?",
"How old are you?",
"Where are you from?",
"How long have you been playing Minecraft?",
"Where did you find the server?",
"Have you ever been banned from another server on Minecraft? If yes, what was the reason?",
"Why should we accept you?",
]
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++]);
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
collector.on("collect", () => {
if(collectCounter < questions.length) {
channel.send(questions[collectedCounter++]);
} else {
channel.send("Your application has been sent!");
collector.stop("fulfilled");
}
});
const appsChannel = client.channel.cache.get('863534867668009004');
collector.on('end', (collected, reason) => {
if(reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected.map((msg) => {
return `&{index++}) &{questions[endCounter++]}\n-> ${msg.content}`
})
.join('\n\n');
}
appsChannel.send(message.channel.send('New Application!', mappedResponses));
});
},
};
This is my index.js:
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const BOT_ID = "863550035923697674";
const prefix = "!";
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setActivity("ur cheat files...", {
type: "WATCHING",
url: "https://discord.gg/bzYXx8t3fE"
});
});
for(const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on("message", message => {
let userID = message.author.id;
if (userID == BOT_ID) {
return;
}
const version = "Wersja bota 0.2";
///const args = message.content;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(!client.commands.has(command)) return;
try{
client.commands.get(command).run(message, args);
}catch(error){
console.error(error);
message.reply('**There was an issue executing that command!**');
}
});
client.login("tokenishere");
Thanks for help!

This just means that message is not what you think it is. In your command handler, you executed the command with the arguments message and args (order matters). However, in the command file, you expected the parameters to be client, message, and then args.
This means, that in your command file, client actually refers to the message, message actually refers to the args, and the third parameter doesn't exist.
To fix this problem, you can modify the names and order of the parameters in either file.

This is an easy fix... as #Lioness100 mentioned your parameters are wrong and im here to show a code example
locate this line of code in index.js :
client.commands.get(command).run(message, args);
// and change it to
client.commands.get(command).run(message, args, client);
after wards go to your "File" and fine this line of code :
run : async(client, message, args) => {
// And change it to
run : async(message, args) => {
Your problem was that you were executing wrong parameters in Your "File" so you just needed to change your parameters from client, message, args to message, args, client
This is a common mistake

Related

How can I create a bot which replies something to random messages. im using an event handler

So i want my bot on discord to have custom replies for example:
user: Hi
bot: Hello
user: ping
bot: pong
I want to make my bot do this but i'm using an event handler for all the commands i'm using and I don't want to use If(message.content ==... message.channel.send ".." in the messagecreate.js or the index.js file because I'm planning to use multiple messages like so and I'd like my code to be relatively clean and organized
so if there is any way I can move the 'if' statements to another messagereplies.js file and run it from there, please let me know
This is my messagecreat.js file
require('dotenv').config();
module.exports = async (Discord, client, message) => {
const prefix = (process.env.PREFIX);
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if (command) command.execute(client, message, args, Discord);
and this is my event handler
const fs = require('fs');
module.exports = (client, Discord) => {
const load_dir = (dirs) => {
const event_files = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith('.js'))
for (const file of event_files) {
const event = require(`../events/${dirs}/${file}`);
const event_name = file.split('.')[0];
client.on(event_name, event.bind(null, Discord, client))
}
}
['client', 'guild'].forEach(e => load_dir(e));
}
Basically I just want a block in the messagecreate.js file or event_handler.js file that executes another file in another folder if a message is sent
Create a json file call it whatever and inside of it put your trigger phrase and its response like so, for this example, I'm calling it catchPhrase.json
{
"hi": "hello",
"ping": "pong",
"here": "there",
"nowhere": "everywhere",
"master": "slave",
"mac": "pc"
}
Then in your event listener you only need one if statement
require('dotenv').config();
module.exports = async (Discord, client, message) => {
const prefix = (process.env.PREFIX);
const catchPhrase = require('path/to/catchPhrase.json')
if (catchPhrase[message.content]) return message.reply(`${catchPhrase[message.content]}`)
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if (command) command.execute(client, message, args, Discord);
}

Heroku: how to have it access multiple .js files

I'm getting this error message on heroku and I think I'm getting it cause of Procfile.
I'm using Worker at the moment, but I'm trying to figure out how to have heroku access both index.js and ping.js. Unless I'm reading the error message completely wrong and this could be a different issue. Any help is appreciated!
EDIT:
Here's my code for index.js
const Discord = require('discord.js');
const music = require('#koenie06/discord.js-music');
const fs = require('fs');
const { dir } = require('console');
const bot = new Discord.Client({
shards: "auto",
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES
]
});
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
//Command handler and aliases
fs.readdirSync('./commands/').forEach(dir => {
//in the commands folder, we gonna check for the category
fs.readdir(`./commands/${dir}`, (err, files) => {
//console log error(catch error)
if(err)throw err;
//checking if the files ends with .js if its a javascript file
var jsFiles = files.filter(f => f.split('.').pop() === 'js');
//if there is no commands in the file it will return
if(jsFiles.length <= 0) {
console.log("Can't find any commands");
return;
}
jsFiles.forEach(file => {
//console the loaded commands
var fileGet = require(`./commands/${dir}/${file}`);
console.log(`[COMMAND HANDLER] - File ${file} was loaded`);
//gonna let the commands run
try {
bot.commands.set(fileGet.help.name, fileGet);
// it search in the commands folder if there is any aliases
fileGet.help.aliases.forEach(alias => {
bot.aliases.set(alias, fileGet.help.name);
})
} catch(err) {
//catch error in console
return console.log(err);
}
})
})
})
/**
* ECHO STUFF
*/
//slash command to echo
bot.on('ready', async () => {
bot.user.setPresence({ activities: [{ name: "Tedi", type: "WATCHING"}] });
console.log("bye");
const data = {
name: 'echo',
description: 'Echo your text',
options: [{
name: 'text',
type: 'STRING',
description: 'The user input',
required: true,
}],
};
const command = await bot.guilds.cache.get('872986148681703444')?.commands.create(data);
})
bot.on('messageCreate', async message => {
if(message.author.bot || message.channel.type == 'DM') return
let prefix = '~'
let messageArray = message.content.split(' ');
let cmd = messsageArray[0];
let args = messageArray.slice(1);
//it will make the cmd work with his original name and his aliases
let commands = bot.commands.get(cmd.slice(prefix.length)) || bot.commands.get(bot.aliases.get(cmd.slice(prefix.length)));
if(commands) {
if(!message.content.startsWith(prefix)) return
commands.run(bot, message, args, prefix);
}
})
//interactionCreate for echo slash command
bot.on('interactionCreate', async interaction => {
/**
* isButton() used to check if its a button
* isCommand() used to check if its a slash command
* isSelectMenu() used to check if its a dropdown menu
* isMessageComponent()
*/
if(interaction.isCommand()) {
if(interaction.commandName === 'echo') {
const text = interaction.options.getString('text');
await interaction.reply({ content: text, ephemeral: false}); //if ephemeral if true, it would make the slash command private
}
}
})
bot.login(process.env.token);
Here is my ping.js
const Discord = require("discord.js");
module.exports.run = async (Client, message, args, prefix) => {
message.channel.send("pong")
}
module.exports.help = {
name: "ping",
aliases: ["p"]
}
This error is not because of Heroku, it's basically because there is a file in your command handler that doesn't have a name while handling it, as example like this code over here:
const Discord = require("discord.js");
module.exports.run = async (Client, message, args, prefix) => {
message.channel.send("pong")
}
module.exports.help = {
// here the name isn't included
aliases: ["p"]
}
// so just check if you have a file without a name while handling it and put a name, and if you don't want aliases make it `aliases: []`
This command handler should be like thisCommands Folder commands > Subfolder e.g. Moderation > kick.jsThats how it works, also thank you for watching my videos, I'm UltraX :)

Having problem making a command handler with prefix in discord.js [duplicate]

This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
I have been trying to make a command handler with prefix, but I'm getting a problem, the bot won't respond and there is no error either
// Index
---// Collections
client.functions = new Collection();
client.commands = new Collection();
client.interactions = new Collection();
---// Handlers
const handlers = fs
.readdirSync("./config/handlers/")
.filter((file) => file.endsWith(".js"));
const commandFolders = fs.readdirSync("./config/commands/");
const interactionFolders = fs.readdirSync("./config/interactions");
const eventFiles = fs
.readdirSync("./config/events/")
.filter((file) => file.endsWith(".js"));
(async () => {
for (file of handlers) {
require(`./config/handlers/${file}`)(client);
}
client.handleCommands(commandFolders);
client.handleInteractions(interactionFolders);
client.handleEvents(eventFiles);
client.login(token);
})();
// The event handler
module.exports = (client) => {
client.handleEvents = async (eventFiles) => {
for (const file of eventFiles) {
const event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
console.log(`[EVENT HANDLER] - ${file} has been loaded.`);
}
};
};
// command handler
const fs = require("fs");
module.exports = (client) => {
client.handleCommands = async (commandFolders) => {
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./config/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
client.commands.set(command.name, command);
console.log(`[COMMANDS HANDLER] - ${file} has been loaded`);
}
}
};
};
// and in the last my messageCreate.js
const prefix = ".";
module.exports = {
name: "messageCreate",
async execute(message, client) {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!message.user.id === "798928603201929306") return;
console.log(
`${message.user.tag} used ${command} in #${message.channel} triggered an command.`
);
if (
!message.content.startsWith(prefix) ||
message.author.bot ||
message.channel.type === "DM"
)
return;
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args, client);
} catch (error) {
console.error(error);
message.reply("there was an error trying to execute that command!");
}
},
};
// ping command
module.exports = {
name: "ping",
async execute(message, args, client) {
message.channel.send(`Pong ${client.ws.ping}`)
}
} // I haven't tried this yet because I'm getting an error in the messageCreate.js
notes:
1. sorry for the long code block
2. hope I inputted everything for getting enough help/info
3. my discord.js version is v13
4. if you need more info about my files, let me know in the comments
It is likely that you created your client with the wrong intents. If you need to listen to messages in servers, make sure you use the GUILD_MESSAGES intent.
const bot = new Discord.Client({intents:[Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES]})

(node:4044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined

I sort of need help here, honestly not sure where I went wrong, here is the full code. I am sort of new, just trying to bring back the mention user and the reason back in a message instead of doing anything with this information.
const { client, MessageEmbed } = require('discord.js');
const { prefix } = require("../config.json");
module.exports = {
name: "report",
description: "This command allows you to report a user for smurfing.",
catefory: "misc",
usage: "To report a player, do $report <discord name> <reason>",
async execute(message, client){
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
const offender = getUserFromMention(args[0]);
if (args.length < 2) {
return message.reply('Please mention the user you want to report and specify a reason.');
}
const reason = args.slice(1).join(' ');
message.reply("You reported",offender,"for reason:", reason)
}
}
If I put no mention, I end up with this
And If I do put a mention
this
I get the above error with no response.
(node:4044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
Index.js:
const fs = require('fs');
const Discord = require("discord.js");
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.prefix = prefix;
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 eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args,client));
} else {
client.on(event.name, (...args) => event.execute(...args,client));
}
}
client.login(token);
You don't have to create a function to get a mention from a message, you can use the Message.mentions property to get the mentions, check the docs for other info about it.
This should solve your issue.
const { prefix } = require("../config.json");
module.exports = {
name: "report",
description: "This command allows you to report a user for smurfing.",
catefory: "misc",
usage: "To report a player, do $report <discord name> <reason>",
async execute(message, client) {
const args = message.content.slice(1).trim().split(/ +/);
const offender = message.mentions.users.first();
// users is a collection, so we use the first method to get the first element
// Docs: https://discord.js.org/#/docs/collection/master/class/Collection
if (args.length < 2 || !offender.username) {
return message.reply('Please mention the user you want to report and specify a reason.');
}
const reason = args.slice(1).join(' ');
message.reply(`You reported ${offender} for reason: ${reason}`);
}
}
Why are you calling client in a command file if you already started a new instance of a client in your root file? try removing client from the top of the code. Hope that works

Post mentioned user's avatar embedded using Discord.js

I'm using Discord.js for a discord bot and I'm trying to make it so that when you do the command !avatar #user
It will reply back with an embedded image of the mentioned user's avatar. I keep getting:
(node:3168) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.image.url: Not a well formed URL.
This is the code I have so far, however I'm unaware of how else to grab the user's avatar?
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.get(mention);
}
}
function getUserFromMentionRegEx(mention) {
const matches = mention.match(/^<#!?(\d+)>$/);
const id = matches[1];
return client.users.get(id);
}
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
if (args[0]) {
const user = getUserFromMention(args[0]);
const userAvatar = user.displayAvatarURL;
if (!user) {
return message.reply('Please use a proper mention if you want to see someone else\'s avatar.');
}
const avatarEmbed = new Discord.RichEmbed()
.setColor('#275BF0')
.setImage('userAvatar');
message.channel.send(avatarEmbed);
}
return message.channel.send(`${message.author.username}, your avatar: ${message.author.displayAvatarURL}`);
}
});
client.login(config.token);
you dont need parse mentions with another function, discord have method for this. You can use message.mentions.members.first()
And you try to set image a string, with text userAvatar so sure you got error.
You can get mention member avatar and send it with this code.
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
const prefix = "!";
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const withoutPrefix = message.content.slice(prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
if (command === 'avatar') {
let targetMember;
if(!message.mentions.members.first()) {
targetMember = message.guild.members.get(message.author.id);
} else {
targetMember = message.mentions.members.first()
}
let avatarEmbed = new Discord.RichEmbed()
.setImage(targetMember.user.displayAvatarURL)
.setColor(targetMember.displayHexColor);
message.channel.send(avatarEmbed);
}
});

Categories