Discord.jc / ReferenceError: MessageAttachment is not defined - javascript

I get this error and it seems that the bot cannot find an image.
How do I define the path of the image? It is located in: C:\Users\Yanzi\Desktop\LaisaBot\Emotes?
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client();
const prefix = "!";
client.on("message", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (command === "sum") {
const numArgs = args.map(x => parseFloat(x));
const sum = numArgs.reduce((counter, x) => counter += x);
message.reply(`The sum of all the arguments you provided is ${sum}!`);
}
// If the message is '!rip'
else if (message.content === '!rip') {
// Create the attachment using MessageAttachment
const attachment = new MessageAttachment('./laisa2.png');
// Send the attachment in the message channel with a content
message.channel.send(`${message.author},`, attachment);
}
});
client.login(config.BOT_TOKEN);

You are calling MessageAttachment when you have not defined it.
It is part of the Discord libary you required at the top so you have two solutions:
Use new Discord.MessageAttachment instead of new MessageAttachment
Where you required Discord at the top replace this with { MessageAttachment }, please be aware that you will also need to add , client and others to that object as you are calling Discord.Client further up. This will result in const { MessageAttachment, Client } = require('discord.js');
I hope this helps, be sure to read the docs and checkout some tutorials.
You can take a look here for info on destructing:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://dmitripavlutin.com/javascript-object-destructuring/

Related

handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined (Discord Bot)

I have been dealing with an issue with my discord bot captcha. The captcha works really well but when it comes to adding a role if they verified it slaps me with
handledPromiseRejectionWarning: TypeError: Cannot read property 'add' of undefined
This is my code:
const Discord = require('discord.js-12');
const client = new Discord.Client();
const prefix = 'ri-';
const Captcha = require("#haileybot/captcha-generator");
client.once('ready', () => {
console.log('Ready!');
});
let captcha = new Captcha();
console.log(captcha.value);
const path = require("path"),
fs = require("fs")
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'verification') {
let captcha = new Captcha();
message.channel.send(
"**Enter the text shown in the image below:**",
new Discord.MessageAttachment(captcha.JPEGStream, "captcha.jpeg")
);
let collector = message.channel.createMessageCollector(m => m.author.id === message.author.id);
collector.on("collect", m => {
if (m.content.toUpperCase() === captcha.value){ message.channel.send("Verified Successfully!");
let role = message.guild.roles.cache.find(r => r.id === "Verified");
message.author.roles.add(role);
}else{ message.channel.send("Failed Verification!");}
collector.stop();
});
}
});
client.login('you don't need this.');
Any help is appreciated! ^^
Error:
I see two problems in your code.
message.author refers to an user, which does not hold roles. Use message.member instead
Replace r.id with r.name, id is not a string.
Have a great day :)

Google search with discord bot

I am working on a bot who searches to google with given arguments.
So i just want it to send the link of the top result found on google kinda like this
so here is the code till now
const Discord = require(`discord.js`);
const bot = new Discord.Client();
const config = require('./botconfig.json');
const prefix = '!g'
bot.on('ready', () => {
console.log('Google-Bot is ready!');
})
bot.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const searchTopic = args.join(' ')
//here it searches on google and provides the link
message.channel.send(`Here is the result! \n ${result}`)
})
bot.login(config.token)
thank you for reading!
You can simply add a link to the requested argument by using https://google.com/search?q=${args.join('+')}, then send it.
Example:
message.channel.send(`https://google.com/search?q=${args.join('+')}`)
You also need to join with a + because google encodes any spaces with a plus symbol.
I also have a suggestion that could lead to a potential problem.
First, make sure you're using the slice attribute after your args.join('+') to exclude the prefix from the argument. So you could use args.join('+').slice(1).
Here is your improved code:
const Discord = require(`discord.js`);
const bot = new Discord.Client();
const config = require('./botconfig.json');
const prefix = '!g'
bot.on('ready', () => {
console.log('Google-Bot is ready!');
})
bot.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const searchTopic = args.join('+').slice(1)
let googleResult = `https://google.com/search?q=${searchTopic}`
let searchEmbed = new Discord.MessageEmbed()
.setColor("#00ff00")
.setDescription(`Here's what Google came up with for ${searchTopic}!\n${googleResult}`)
message.channel.send(searchEmbed)
})
bot.login(config.token)

Discord.js can i execute a file inside of another file

I have My Main Index.js File, Inside That, I have This Code (Imagine Input is !help)
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
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);
}
client.on("error", console.error);
client.once('ready', () => {
console.log('ProBot is online!');
});
client.on('message', message => {
if (message.author.bot) return;
if (message.guild === null) return;
if (message.content.startsWith("!")){
const prefix = "!";
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command.length === 0) return;
let cmd = client.commands.get(command);
if (!cmd) return message.reply(`\`${prefix + command}\` doesn't exist!`);
cmd.execute(message, args);
}
};
Then That Opens the file help.js, example being
const Discord = require('discord.js');
module.exports = {
name: 'help',
description: "!help Command",
execute(message, args){
if(!message.member.hasPermission("MANAGE_GUILD")){ //Regular Output
message.react('❤️')
const help2Embed = new Discord.MessageEmbed()
.setColor('#ffd6d6')
.setTitle('!Help\n')
.setDescription('Check Your Private Messages For More Information')
message.channel.send(help2Embed)
const h11elpEmbed = new Discord.MessageEmbed()
.setColor('#ffd6d6')
.setTitle('!Help\n')
.setDescription('This Bot Has Lots Of Special Features\n \n \nGeneral Commands Are;\n \n!blacklist = Shows The BlackListed Words\n!safe = Disables The Filter For That Message\n!server = Displays Server Name, Total Members And Amount On/Offline')
message.author.send(h11elpEmbed)
return;
}
}}
Question Is, If it was Changed To be a !warn #member [low, med, high] [reason] - Could The Index Take it to a warn.js file, then from there depending on if args[2] is low, med, high open and execute a new file? to run a different code for each.[or if there is an easier way I have overlooked]
Just to close the question and get an answer.
a really helpful comment from #worthy Alpaca (all credit to them)
you can just create a new file, that you can name however you want, according to the schema you already have. Inside that file you can then handle whatever parameters you wish to use with that command

How to make commands for discord bot non-case sensitive

const Discord = require("discord.js");
//ignore 1 up and 1 down
const client = new Discord.Client();
//prefix
const prefix = `+`;
//log for me
client.once(`ready`, () => {
console.log("IM POWERED UP")
});
//commands
client.on(`message`, message =>{
const args = message.content.slice(prefix.lengh).split(/ +/);
//Username..(embed)
if (message.content === `${prefix}Username`){
let messageArray = message.content.split(" ");
let args = message.content.split(` `);
let command = messageArray[1].toLowerCase();
const embed = new Discord.MessageEmbed()
.setTitle(`user information`)
.addField(`Your Username is`, message.author.username)
.addField(`Bugs`, `To report bugs please go to TxPsycho#1080 and you may earn a reward!`)
.setThumbnail(message.author.displayAvatarURL())
.setFooter(`Wanna get Valorant cheats? Join here`)
.setColor(`RANDOM`)
message.channel.send(embed);
}
//help command
if (message.content === `${prefix}Help`){
const embed = new Discord.MessageEmbed()
.setTitle(`Help`)
.addField(`A list of commands are below!`)
.setThumbnail(message.author.displayAvatarURL())
.setDescription(`AMOTHERFUCKINGTESTYOUMOTHERFUCKAYOUTHINKITSFUNNYCALLINGAT2AM`)
.setColor(`RANDOM`)
message.channel.send(embed);
}
});
//ignore this and leave it at bottom
client.login(`Nz`)
I am not sure how to make the commands caps insensitive, this is the error it’s been giving me. I have been searching but found no information. Down below is the link to an error that I have been receiving when I try to debug the code.
Click here to see the error picture
Like rogue said the issue is calling toLowerCase on undefined here:
let command = messageArray[1].toLowerCase();
The real command would be at 0, since arrays are 0 indexed
You might want to shift it instead so you can get the args easier:
Message: !help 12 24 36
const args = message.content.split(" ");
const command = args.shift().toLowerCase();
console.log(args);
// => [12, 24, 36]
console.log(args[0]);
// => 12
After that you just compare command instead of message.content:
if(command === "!help") {
}
You can sanitise messages with toLowerCase
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('aLPhABeT'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toLowerCase()); // 'alphabet'

How do you send a DM using a discord bot using discord.js

So I am trying to make a bot that has a command to send a "ticket", which is like a warning except it sends a configurable message in a DM. Here's my code so far:
const bot = new Discord.Client()
const token = token here;
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
bot.on('ready', async () => {
console.log('This bot is online! Created by #littleBitsman.');
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
if(message.content.startsWith(PREFIX))
switch (args[0]) {
case 'ticket':
if (message.member.roles.highest == '701895573737046066') {
mention = message.mentions.users.first()
var thing = args.shift()
thing = args.shift()
thing = thing.replace(",", " ")
if(mention = null) {return}
var message = new Discord.MessageEmbed()
.setTitle('Ticket')
.setDescription('Hey ' + mention + '! You recieved this because of: ' + args +'.')
message.channel.type(`dm`) + message.channel.send(mentionMessage)
}
}
})
bot.login(token);
I took out all other code that did not have to do with this question.
To send a message to a specific user, you can do message.client.users.fetch(`insert_ID`).then(user => user.send('message')).
It seems like you're trying to send a message to a user that was mentioned. In that case:
message.client.users.fetch(`${mention.id}`).then(user => user.send('insert_message')).
Hope this helps!

Categories