send an image using discord.js - javascript

I have been following a few different guides to program a simple discord bot. Everything works except I cannot get it to send an image. I have looked at these previous questions 1 2, but their solutions are not working for me. This is my code:
const {Client, Intents} = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = '?';
client.once('ready', () => {
console.log("Dog is online!");
});
client.on('messageCreate', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping') {
message.channel.send('pong!');
}
else if (command === 'bark') {
message.channel.send('bark bark bark grrrr...')
}
else if(command === 'nick') {
message.channel.send('grrr...');
}
else if (command === 'pic') {
message.channel.send("little dog", {files: ["https://i.imgur.com/xxXXXxx.jpeg"] });
}
});
//must be last line
client.login('');
my client login is there in my editor, just not sharing it here. the "pic" command is what is not working. It displays the "little dog" text, but does not send the image. The only reason I'm using imgur is because I'm not sure if you can send local images; if someone knows a solution using local files I'll take it.

You can use
files: [{ attachment: "YourImage.jpg" }] });
You can also rename the image with
files: [{ attachment: <images>.toBuffer(), name: 'newName.png' }] });
Example:
message.channel.send({ files: [{ attachment: 'YourImage.png' }] });
the <images> is your image variable
const images = blablabla

According to the V13 discord.js
You can do following, this is also working for me.
const { MessageAttachment } = require('discord.js')
const attachment = new MessageAttachment('URL'); //ex. https://i.imgur.com/random.jpg
message.channel.send({ content: "I sent you a photo!", files: [attachment] })
This example will send a photo with the text I sent you a photo!

Related

Bot isn't replying to any message

I'm trying to make a simple Discord bot, but I haven't been able to get it to respond to any of my messages.
const Discord = require("discord.js");
const { GatewayIntentBits } = require('discord.js');
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("messageCreate", msg => {
if(msg.content === "ping") {
msg.reply("pong");
}
})
const token = process.env['TOKEN']
client.login(token)
The bot is logging into discord, I'm not getting any errors in the console, and I've toggled on all the privileged gateway intents.
Edit
So, my previous answer was wrong, but is most definitely a better way to send messages.
There's not anything else that I can see is wrong with the code -- so I guess I'll try to debunk?
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ]});
client.on("ready", async() => {
console.log(`${client.user.tag} logged in.`);
});
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase() === "ping") {
message.reply({ content: "pong!" }); // or message.reply("pong!");
}
});
client.login(process.env.TOKEN);
This should be a runnable instance of your code. What you should do is see if you're even getting the messageCreate event at all, by running it like this:
client.on("messageCreate", (message) => {
console.log(`Received message!`);
});
If you do get something, then it is unable to correctly parse the message content. Are you ensuring it's the same capitalization wise? Is it spelt correctly?
If you don't get something, it's an issue with your Intents, or the way your event is structured.
Try adding parenthesis around your msg, though that shouldn't affect anything. Just a thought.
Incorrect Answer
In discord.js#13.x.x, the way to send messages has changed.
Formerly, you could do the following:
message.reply("Hello world!");
But now, to make formatting what provided property is what, it goes as follows:
message.reply({
content: "Hello world!",
});
You can also add things such as Embeds by using embeds: [], or Components by: components: [] (which requires Action Rows, not base Components).
Hope this helps.

Only reply in dms discord.js

So I was working on this project where people will DM the BOT and run command and it replies test. But it doesn't reply.
client.on("messageCreate", async message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (message.channel.type === 'dm') {
message.reply("test");
}
}
});
That's because you didn't enable the intents for getting a dm message,
try putting those two on your client declarations :
const client = new Discord.Client({
intents : ['DIRECT_MESSAGES','GUILD_MESSAGES'],
partials: ["CHANNEL","MESSAGE"]
})
here is a way:
1.Create a file named ** 'privateMessage.js'** and in the main file add:
const privateMessage = require('./privateMessage')
client.on('ready' ,() =>{
console.log('I am online')
client.user.setActivity('YouTube Music 🎧', {type:'PLAYING'})
privateMessage(client, 'ping', 'pong')
})
and in the file we just created privateMessage.js add:
module.exports=(client, triggerText, replyText)=>{
client.on('message', message =>{
if(message.content.toLowerCase()===triggerText.toLowerCase()){
message.author.send(replyText)
}
})
}

Discord.js embeds: TypeError: Discord.MessageEmbed is not a constructor

I was recently trying to add a MessageEmbed for my discord bot, but I get this error:
TypeError: Discord.MessageEmbed is not a constructor
I was wondering if anyone knows how to fix this, I have tried some of the rips I could find online, some include trying to re-install node.js and discord.js, other mention a different method like using NewMessageEmbed() instead, but none of them have been working for me, it would be great someone with a bit more experience than me could provide a solution, I have provided all the code involved and screenshot of the error, thanks in advance.
Command file:
module.exports = {
name: 'command',
description: "Embeds!",
execute(message, args, Discord){
const newEmbed = new Discord.MessageEmbed()
.setColor('#FFA62B')
.setTitle('Rules')
.setURL('https://discord.gg/fPAsvEey2k')
.setDescription('**This is an embed for the server rules.**')
.addFields(
{name: '1.', value: 'Treat everyone with respect. Absolutely no harassment, witch hunting, sexism, racism or hate speech will be tolerated.'},
{name: '2.', value: 'No spam or self-promotion (server invites, advertisements, etc.) without permission from a staff member. This includes DMing fellow members.'},
{name: '3.', value: 'No NSFW or obscene content. This includes text, images or links featuring nudity, sex, hard violence or other graphically disturbing content.'},
{name: '4.', value: 'if you see something against the rules or something that makes you feel unsafe, let staff know. We want this server to be a welcoming space!'},
{name: '5.', value: 'Keep public conversations in English.'},
{name: '6.', value: 'This list is not exhaustive and will be updated as we see fit.'}
)
.setImage('./images/rules.png')
.setFooter('Make sure to follow the rules');
message.channel.send(newEmbed);
}
}
Main file:
// grabs the discord.js bot file for import //
const {Client, Intents, Collection} = require('discord.js');
// create the client for the bot //
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
// prefix to use for bot commands //
const prefix = '!';
const fs = require('fs');
const Discord = require('./commands/discord');
client.commands = new 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);
}
// log to console that the bot has successfully logged in //
client.once('ready', () => {
console.log("Reformed Esports is online");
});
/* Command handler, checking if message starts with prefix and is not the bot,
allowing commands to have multiple words */
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if(command === 'discord'){
client.commands.get('discord').execute(message, args);
} else if(command === 'pugs') {
client.commands.get('pugs').execute(message, args);
} else if(command === 'command'){
client.commands.get('command').execute(message, args, Discord)
}
});
// bot login using discord bot token //
client.login('blank');
Image of full error:
You should be passing the discord.js module but instead you pass a file. This may have different functions, properties, etc than the discord.js module.
This code will fix the error:
client.commands.get('command').execute(message, args, require('discord.js'))
Additionally, embeds must now be sent using the embeds property
message.channel.send({ embeds: [newEmbed] })
It looks like you are sending ./commands/discord as an argument instead of the real discord.js package. I would add Embed to the const {Client, Intents, Collection} = require('discord.js');, and send Embed instead of Discord inside of client.commands.get('command').execute(message, args, Discord).

Discord only recognizing "ping" command in discord.js

In my Discord.JS bot, I have multiple commands setup (ping, beep, etc.) but Discord only recognizes "ping". I have tried multiple setups, and all are the same.
Here is my code:
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName: command } = interaction;
if (command === 'ping') {
await interaction.reply('Pong!');
} else if (command === 'beep') {
await interaction.reply('Boop!');
} else if (command === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (command === 'user-info') {
await interaction.reply(`Your username: ${interaction.user.username}\nYour ID: ${interaction.user.id}`);
}
});
client.login(token);
And here is Discords command view when "/" is enter
As you can see, ping is the only thing being recognized by discord.
It is also worth noting the β€˜ping’ command has a description which the original description I setup, so it seems like issue is that Discord is not updating the commands each time the script changes. But, I don’t know how to resolve that issue.
It seems like you only registered the ping command. You have to register each slash command individually.
I guess you registered the slashcommand some tile earlier, and have not removed it since. You are only responding in your code example to slashcommands, but you have to create them in the first hand.
Check here on how to do that.
it may take up to one hour to register a global command tho, so be patient. If you are fine, with slashcommands for one guild only, you can also only create guildCommands. These are up and running within a view minutes (under 10minutes max)
Here is a simple command, with which you can update the slashcommands (this is staright from the docs)
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
if (message.content.toLowerCase() === '!deploy' && message.author.id === client.application?.owner.id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'pong',
description: 'Replies with Ping!',
},
];
const commands = await client.application?.commands.set(data);
console.log(commands);
}
});
NOTE: you have to be running the master branch of discord.js (aka Discord.js V13). If you have not installed it yet, you can install it by running: npm install discord.js#latest. Make sure, you have uninstalled the "normal" discord.js dependency beforehand, by running npm uninstall discord.js.
If you are not sure what version you currently have installed, simply run npm list
This worked for me, the idea is to render each command separately.
I also went for some hardcoded configs: guild_id & client_id (to win some time in dev mode)
const { Client, Collection, Intents } = require('discord.js');
const { token, client_id, guild_id } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
// => client_id was just a quick fix, the correct value should be the id of the guild owner(s)
if (message.content.toLowerCase() === '!deploy' && message.author.id === client_id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'foo',
description: 'Replies with bar!',
},
{
name: 'chicken',
description: 'Replies with sticks!',
},
];
// same here, guild_id should also be replaced by the correct call to the idea number, just as client_id in this code!
for (let i = 0; data.length > i; i++) {
await client.guilds.cache.get(guild_id)?.commands.create(data[i]);
}
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = interaction.commandName;
if (command === 'ping') {
await interaction.reply('pong')
} else if (command === 'foo') {
await interaction.reply('bar')
} else if (command === 'chicken') {
await interaction.reply('nuggets')
}
});
client.login(token);

Node JS Error canvas.node is not a valid Win32 application

im trying to make a plugin discord in js and add the package: discord-image-generation but i need to have canvas installed on my PC, when i try to run it it's give me the error:
C:\Users\USER\node_modules\canvas\build\Release\canvas.node is not a valid Win32 application.
Here is my code:
const Discord = require("discordjs")
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
const DIG = require("discord-image-generation");
client.on("ready", () =>
{
});
client.on("message", message =>
{
let cmd = message.content.split(" ")[0]
cmd = cmd.slice(PREFIX.length)
let args = message.content.split(" ").slice(1)
if (cmd === "deletetrash")
{
message.delete()
const user = message.mentions.users.first()
if (!user) return window.BdApi.alert("πŸ”ͺ Eroge Notification πŸ”ͺ",`You need mention someone. ❌`);
Delete();
async function Delete()
{
let image = await new DIG.Delete().getImage(user.avatarURL).then(image =>
{
message.channel.send({
files: [{
attachment: image,
name: "Delete.png"
}]
})
})
}
}
});
client.login(get_token.authToken).catch(() =>
{
return window.BdApi.alert("πŸ”ͺ Eroge Notification πŸ”ͺ",`Oops, look like your token not working...`);
})
i have tried every solutions nothing work, thanks in advance for your help!
It means, that canvas build version and nodejs version are not the same. i.e. x32 canvas build and x64 nodejs build. Just build canvas for your node version

Categories