Discord.js - choosing random image in my pc - discord.js

I want to make a command where !send image will send random specified image on my pc. this is my array of images
const images = [
'/mybot/images/any image i have there',
'other images'
]
and this is the way it is supposed to choose one
if(message.content === prefix + 'send image')
{
message.channel.send(`${message.author} here you have image`, {
file: RetardedImage[Math.floor(Math.random() * RetardedImage.length)]
});
}```
but it doesnt work and problem is that it doesnt even say error or something so i dont know what the problem is, can someone please help me?

There's no file option for a message, it's called files and it's an array:
if(message.content === prefix + 'send image')
{
message.channel.send(`${message.author} here you have image`, {
files: [
{
name: "myimage.png",
attachment: RetardedImage[Math.floor(Math.random() * RetardedImage.length)]
}
]
});
}
This will send your file properly.

you can make an attachment like this
const attachment = new <Discord>.Attachment("PATH","NAME.EXTENSION")
message.channel.send(`blah blah`+attachment)

Related

How do I make my discord bot send an attachment when certain word is sent

I'm new to working with discord bot and decided to try it out, to start I just wanted to make the bot send an attachment (image, video, etc) when for example, "sendpicture" is written in chat.
I've changed the code several times yet I get the same error everytime, "Attachment is not a constructor" or "Discord.Attachment is not a constructor".
My current code looks like this:
const client = new Discord.Client();
client.once(`ready`, () => {
console.log("online");
});
const PREFIX = "!"
//replying with a text message
client.on('message', msg => {
if (msg.content === 'test1') {
msg.channel.send('working');
}
});
//replying with attachment
client.on("message", function(message){
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]) {
case "test2":
message.channel.send(new Discord.Attachment(`.a/this/bestpic.png`, `bestpic.png`) )
.then(msg => {
//aaaaaaaa
})
.catch(console.error);
break;
}
})
tyia
Had you tried looking at the official documentation ?
I don't think you should use new Discord.Attachment(), try this instead :
switch(args[0]) {
case "test2":
message.channel.send({
files: [{
attachment: '.a/this/bestpic.png',
name: 'bestpic.png'
}]
}).then(msg => {
//aaaaaaaa
}).catch(console.error);
break;
}
Discord.Attachment() is not a thing, i believe the answer you are looking for is this :)
new Discord.MessageAttachment()
Try this code, short and simple to use.
if (message.content.toLowerCase() === 'word') { //only word, without prefix
message.channel.send({ files: ['./path_to_your_file'] })
}
You should try using MessageAttachment because Discord.Attachment is not a thing, then add the attachment into the files property
I would consider making the attachment a variable instead of putting it directly into the function, it is optional tho
const { MessageAttachment } = require("discord.js");
const attachment = new MessageAttachment("url", "fileName(optional)", data(optional));
message.channel.send({ files: [attachment] }).then(//code...)
Let me know if it works

Discord.js slash commands type 5

So I have been developing a bot recently and I have implemented the slash commands into said bot. I have come across the need for a type 5 command "response" but I can't seem to find good documentation on the slash commands. I can't seem to make it "stop thinking". Any help would be appreciated!
EDIT: I found that you need to edit the interaction response (https://discord.com/developers/docs/interactions/slash-commands#interaction-response) but I'm not using webhooks I'm using a bot and I don't want to have to get another npm library if I don't have to. So how do I edit my interaction?
I have solved this, if you want to know how I did here is some code.
if your interaction responder looks like this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction)//i am using a command handler to put
//the actual event into a different file
}
and your "interaction message sender" looks like this: (notice it's type 5)
module.exports.whatever = (interaction) => {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 5
}
})
};
then it will say "{botname} is thinking" with a little ellipses, and after 15 minutes if nothing happens it will fail the interaction. If you want to make it "stop thinking" you have to edit the message. I am using the axios npm library (https://www.npmjs.com/package/axios) and if you just put in this code it should edit your interaction message. this goes at the top of your file with your requirements:
const axios = require('axios')
const appId = ''//bot id goes here
and somewhere near the bottom of your file maybe put in this:
const editInteraction = async (client, interaction, response) => {
const data = typeof response === 'object' ? { embeds: [ response ] } : { content: response };
const channel = await client.channels.resolve(interaction.channel_id);
return axios
.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, data)
.then((answer) => {
return channel.messages.fetch(answer.data.id)
})
};
then you will have the basic code structure to edit the message, now you just need to edit the message. to do that, in your code, do this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction).then(m => {
editInteraction(client, interaction, '>:(')//this will actually edit the message so
//instead of " >:( " put in what you want to edit you message to be
})
}
then you can run that command and it will say the bot is thinking then after whatever event you want to run it will edit it to say whatever!

How do I display local image with discord.js message embed?

I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);

How to copy a user's message in a bot embed

I want to make a command using 2 files to do a fully customizable embed.
In the first file : When the user do the command 2 embeds appears, the first is empty and the second has options with emojis we can react See the base I already did
In the second file : I made that when the user react with the first emoji, the bot sends a message saying "please specifiate an embed title"
But now I don't now what to do to make the bot copy the user's message and paste it in the first embed as a title.
I tried things like
switch (emoji) {
case "🖋️":
message.channel.send('Spécifie un titre d\'embed !')
const filter = m => (message.author.id === m.author.id)
const userEntry = await message.channel.awaitMessages(filter, {
max: 1, time: 20000, errors: ['time']
});
if(!member.user.bot) {
if(userEntry) {
const newEmbedModifTitle = userEntry.content;
modifembed.setTitle(`${newEmbedModifTitle}`)
message.edit(modifembed);
}
}
break;
}
}
But or the bot copies the message "please specifiate an embed title" and paste it in the second embed, or it don't do anything.
I hope someone can help me !
I advise you to just do !send [Title] [Color] [Footer] [Show author] [Content] then split it in a args[] let.

How to answer back with images in wit.ai?

I am trying to create a fb_messenger bot using wit.ai.In wit.ai,i can only do answering and question which is only text.But I want to answering back to user by showing images.How to do it?Please guide me.
Thank you very much.
You need to send the image in your Wit action using the messenger Bot:
Example if you're using Node js:
const actions = {
/**
* This is used by the "Bot sends" action in Wit
* #param sessionId
* #param text
* #returns {Promise.<T>}
*/
send({sessionId}, {text}) {
// Our bot has something to say!
// Let's retrieve the Facebook user whose session belongs to
const recipientId = sessions[sessionId].fbid;
if (recipientId) {
// Yay, we found our recipient!
// Let's forward our bot response to her.
// We return a promise to let our bot know when we're done sending
//bot is a simple wrapper for Messenger node code provided [here][1]
return bot.sendTextMessage(recipientId, text)
.catch((err) => {
console.error(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err.stack || err
);
});
} else {
console.error('Oops! Couldn\'t find user for session:', sessionId);
// Giving the wheel back to our bot
return Promise.resolve()
}
},
['my-custom-action']({sessionId, context, entities, message}) {
//Api calls ...
//now i got an image URL i want to send to the user
return bot.sendImageMessage(recipientId, image_url);
return Promise.resolve(context)
},
Don't forget to delete the "Bot sends" part from your story on Wit.ai, this is so you don't send both the Image and the URL.
Hope this helps!
You need to use the image attachment template.
curl -X POST -H "Content-Type: application/json" -d '{
"recipient":{
"id":"<USER_ID>"
},
"message":{
"attachment":{
"type":"image",
"payload":{
"url":"<IMAGE_URL>"
}
}
}
}' "https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>"
More information here:

Resources