Discord js Random image embed but outside embed - discord

So I'm trying to make a script that runs a random image when someone uses !inspire command I have the code working but the embed fires the random images outside of the embed?
bot.on("messageCreate", message => {
const channel1 = message.guild.channels.cache.find(channel => channel.name === '🤖-bot-chat')
if (message.content.startsWith (prefix,'inspire')) {
message.delete(1000);
const idx = (len) => Math.floor(Math.random() * (len));
const files = fs.readdirSync('/images/');
const myImage = files[idx(files.length)];
const embed = new Discord.MessageEmbed()
.setTitle("Just a test")
channel1.send({ embeds: [embed], files: [`/images/${myImage}`] });
}
})
Here what it's doing now

You have used the files attribute in the channel1.send() function. That makes the image outside the embed.
https://discordjs.guide/popular-topics/embeds.html#using-the-embed-constructor
The .setImage() attribute makes the image wrapped INSIDE the embed. That's how it works :)

Related

Uploading multiple content to Cloudinary React js

I'm building this website where users can sometimes upload one audio or one image and sometimes both at the same time to cloudinary. I'm able to upload from the front-end (react.js) one or the other (image or audio) but not both at the same time.
I saw this post that says that it is not possible except if we "write a script and use multi-threads (up to 10 threads) to upload many files at once. " I have no idea what it means in the context of react.js | JavaScript.
My code is the following:
I first call the handleUploadCloudinary with its parameter. The function is being called once the data is ready to be published.
const publishTheEntry = () => {
const {
mainText,
mediaAudio,
mediaImg
} = formData;
if(mediaAudio !== ""){
handleUploadCloudinary("audio");
};
if(mediaImg !== ""){
handleUploadCloudinary("image");
};
};
The handleUploadCloudinary() is the following:
const handleUploadCloudinary = (mediaType) => {
const {
mediaAudio,
mediaImg
} = formData;
const formDataCloudinary = new FormData();
formDataCloudinary.append("upload_preset", my_var_here);
formDataCloudinary.append("timestamp", (Date.now() / 1000) | 0);
if(mediaType === "img"){
formDataCloudinary.append("file", mediaImg);
axios.post(
"https://api.cloudinary.com/v1_1/sismographie-cloud/image/upload",
formDataCloudinary
).then((response) => {
console.log(response);
let url = response.data.secure_url;
setFormData({...formData, mediaImg: url});
})
}else if(mediaType === "audio"){
formDataCloudinary.append("file", mediaAudio);
axios.post(
"https://api.cloudinary.com/v1_1/sismographie-cloud/upload",
formDataCloudinary
).then((response) => {
let url = response.data.secure_url;
setFormData({...formData, mediaAudio: url});
})
}
};
Even if, for when both audio + image are stored into the state, I can console.log() both of the conditions, the state won't bot update the formData with both. One will successfully sate the state with a new cloudinary link while the other one will remain a buffer.
You can loop through your resources list and upload assets one by one, or create new threads at the backend (best practice).
This link is a demo for uploading multiple files using Axios and React:
https://codesandbox.io/s/chunked-client-side-upload-forked-vqx6mp?file=/src/CldCustUploadLgRestApi.js

"message.member.voice" returning undefined even when I'm in a voice channel - discord.js

I'm trying to make my discord bot play music for my discord server (in light of groovy shutting down).
But when I tried to get it to join using message.members.voice.join() it always returns undefined, even when I'm in a discord voice channel. I've left and rejoined the call, and restarted the bot, but nothing has worked.
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(message, args) {
const { voiceChannel } = message.member.voice;
if (!voiceChannel) return message.channel.send('Join a Voice-Channel to use this command');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
if (!args.length) return message.channel.send('You need to send the second argument!');
const connection = await voiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' })
connection.play(stream, { seek: 0, volume: 1 });
}
}
}
You need to use #discordjs/voice package for discord.js v13.
const { joinVoiceChannel } = require('#discordjs/voice')
And join voice or stage channels with the joinVoiceChannel method
let connection = joinVoiceChannel({
...
})
You need to specify the options as shown in their documentation
Though I'm not sure about playing audio, there is a method joinVoiceChannel.subscribe() that takes AudioPlayer as parameter, which allows the player to play audio on the connection.
You could make an AudioPlayer by using createAudioPlayer(). But there is a method play in AudioPlayer, that takes AudioResource as parameter, which plays the resource in the player.
And to make AudioResource, use createAudioResource method, which takes input as parameter.
const {joinVoiceChannel, createAudioPlayer, createAudioResource} = require('#discordjs/voice')
let player = createAudioPlayer()
connection.subscribe(player)
let resource = createAudioResource('')
player.play(resource)
Though I'm still not sure about the value for the parameter, it could be URL or file paths, I haven't tested it out since I'm currently out
In discord.js version 12 you would need to get the GuildMember#voice state's VoiceChannel object they are connected to so you would have to use VoiceState#channel so you would to define your connection like so:
const connection = await message.member.voice.channel.join()

Error 400 Bad Request while Uploading Image to firebase storage in React Native

I am working on react native project connected to firebase. I am =using firebase storage ad=nd trying to upload a file to firebase storage But I get following error.
{code: 400, message: "Bad Request. Could not access bucket quickbuy-a0764.appspot.com","status":"Access_Bucket"}
I tried configuring my permissions but did not work for me.
example of Image Uri I am providing to put() is as follows
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAk and so on
Now what should I do to resolve this issue?
let filename = values.images + Date.now();
let uri = values.images[0];
const uploadTask = storage.ref(`images/${filename}`).put(uri);
uploadTask.on("state_changed", (snapshot) => {
console.log(snapshot);
});
firebase.storage.Reference#put() accepts a Blob, Uint8Array or an ArrayBuffer. Because you are trying to upload a Data URI, which is a string, you need to use [firebase.storage.Reference#putString()`](https://firebase.google.com/docs/reference/js/firebase.storage.Reference#putstring).
To do this for a data URI, you would use:
someStorageRef.putString(uri, firebase.storage.StringFormat.DATA_URL);
Next, based on these lines:
const filename = values.images + Date.now();
let uri = values.images[0];
values.images is an array, which means that filename will end up being something similar to "[object Object],[object Object]1620528961143".
As I covered in this answer on your question yesterday, this is a poor way to generate IDs as it can lead to duplicates & collisions - use a Push ID instead.
const uri = /* ... */;
const rootRef = firebase.database().ref();
const filename = rootRef.push().key;
const uploadTask = storage.ref(`images/${filename}`)
.putString(uri, firebase.storage.StringFormat.DATA_URL);
uploadTask.on("state_changed", (snapshot) => {
console.log(snapshot);
});
Future Use with Version 9 of the SDK
import { getStorage, ref, uploadBytes } from "firebase/storage";
const uploadImage = async (values) => {
const filename = values.images + Date.now();
const uri = values.images[0];
// Create a root reference
const storage = getStorage();
// Create a reference to 'images/$filename.jpg'
const filesImagesRef = ref(storage, 1images/${filename}.jpg);
await uploadBytes(filesImagesRef, uri).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
}
Let us know how this works for you!

Using Discord's 'message' listener on other files

I'm trying to use commands like message.delete(); in functions from other files. Is there a way to add listeners without the client.on() method?
I.E.
index.js
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.on('message', async message => {
//stuff here like message.delete(); or message.channel.send();
});
And I would like to use it like
example.js
const message = somehow add the listener?
message.delete();
message.author.sen();
You may export your variables with an handler. https://discordjs.guide/command-handling/

React Promise - confusion in coding

I am new to react, and trying to follow a tutorial of Promises. I merged the two files into one as below for convenience. However, I am totally lost as to how to display the desired images. I copied the last bit from another react application.
import React from 'react'
function DemoPromise2() {
function loadImage(url) {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = function () {
resolve(image);
};
image.onerror = function () {
let message = "Could not load image at " + url;
reject(new Error(message));
};
image.src = url;
});
}
// export default loadImage;
let addImg = (src) => {
let imgElement = document.createElement("img");
imgElement.src = src;
document.body.appendChild(imgElement);
};
Promise.all([
loadImage("images/img1.jpg"),
loadImage("images/img2.jpg"),
loadImage("images/img3.jpg"),
loadImage("images/img4.jpg"),
])
.then((images) => {
images.forEach((img) => addImg(img.src));
})
.catch((error) => {
// handle error later
});
return (
<div className="App">
Demo Promise2 -
<br />
???? Question :: how can I display images here??
</div>
);
}
export default DemoPromise2;
#Evert is correct, you need to load this into state to show the images.
TL;DR: Click Run code snippet below to see the code in action.
--
Longer Explanation:
useState will allow the data to be accessed with the component and allow it to be persisted within it. You either get the value with it's name or setValue to update it.
Ex:
const [myvalue, setMyvalue] = useState('defaultValue');
useEffect is use as another React but specifically for when state get modified and given that you give specific things to look for (or watch as an array)
Example Nothing To Watch:
useEffect(() => {
console.log('CODE IS RUN ONLY ONCE, Nothing to watch except when component loads');
}, []);
Example State To Watch:
const [value, setValue] = useState('watch this');
useEffect(() => {
console.log('RUN EACH TIME value is updated including first time set');
}, [value]);
Code:
// main.js
// for your code use: import React, { useState, useEffect } from 'react';
const { useState, useEffect } = React;
const App = () => {
// State / Props
const [images, setImages] = useState([]);
// Load Images Function
const loadImage = (url) => {
return new Promise((resolve, reject) => {
let image = new Image();
image.onload = () => {
resolve(image);
};
image.onerror = () => {
let message = `Could not load ${url}`;
reject(new Error(message));
};
image.src = url;
});
};
// Hook to use when the component is loaded and ready
// Equivalent to something like window.onload
useEffect(() => {
Promise.all([
loadImage('https://picsum.photos/seed/picsum/200/200'),
loadImage('https://picsum.photos/200/200')
])
.then((data) => {
setImages(data);
})
.catch((error) => console.log('ERROR', error));
}, []);
return <div><h1>My Images</h1><p>Images Loaded: {images.length}</p>{images.map((img, index) => <img key={`img-${index}`} src={img.getAttribute('src')} />)}</div>;
};
ReactDOM.render(<App />, document.querySelector('#root'));
<body>
<div id="root"></div>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script type="text/babel" src="main.js"></script>
</body>
====== CLARIFICATIONS ======
Question:
const [images, setImages] = useState([]); ???????????? the above defines const 'images'. Where is 'images' value modified? where is it receiving values/images?
Answer:
Think of this part as destructuring from a variable that's an array, but you're getting the getter and setter from useState.
The same way you would destructure an array like:
const myArray = [1, 2];
const [firstValue, secondValue] = myArray;
// firstValue = 1
// secondValue = 2
But instead of just plain values, you're getting the equivalent of functions returned to get the value and set a new value.
Note that useState is defined by React.
With that in mind, images is updated (set) here:
.then((data) => {
setImages(data);
})
Question:
2. let image = new Image(); ???????? whats the purpose of this sttmt? 'let image = new image()' ??? such was used to set an instance of a class but why is it used for a function? ????????
Answer:
new Image() is a base function baked into the browser, and would be typically be used for creating a new <img> with some event handling, or potentially other custom functionality.
Technically you do not need to use new Image() here if you're just going to rely on the browser to load the images naturally.
In the case of your initial code, the functionality exists to do something when the image is done loading, or handle errors in a specific way, but there isn't really any code except for resolving a promise.
What you would do is something like:
image.onload = () => {
// Images is loaded send message to custom logging software
// OR Image is loaded which works like a tracking pixel sent a message
// OR Image is loaded, append it to DOM and perform a fade in animation
resolve(image);
};
Sometimes you would just use this function to handle ordering images in a sequential way, or control the sequence of loading and animations.
On in the case of your code, wait until all the images are loaded, then show the page vs. loading them one by one natively in the browser.
Question:
3. image.onload = () => {resolve(image); 'image.onload' is just a const , will it hold the 'image'?
Answer:
It does not hold the image, this is just an event function that is defined by Image to handle when the image is done loading. So it's a predefined function that is called by Image, but defined by you.
Question:
?4. image.src = url .. ??
Answer:
This is the part of Image that starts the whole process, that's why it's defined at the end.
The code is saying.
// Before you begin you're going to be getting an image
let image = new Image();
// Before we load the image, I want to tell you how to handle it once
// it loads successfully
image.onload = function {
// custom instructions
};
// Before we load the image, I want to tell you how to handle it
// in case things go wrong
image.onerror = function {
// custom instructions
}
// Ok, we're good to go, start the process, here's the url
image.src = url; // https://picsum.photos/seed/picsum/200/200

Resources