I have a discord bot
Code:
const Discord = require('discord.js');
const sharp = require('sharp');
const client = new Discord.Client({ intents: ["Guilds", "GuildMessages", "MessageContent"] });
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
client.on('messageCreate', async message => {
if (!message.content.startsWith('!rights') || message.author.bot) return;
console.log("invoked");
// get image link or image attachment
let imageUrl = '';
if (message.attachments.size > 0) {
imageUrl = message.attachments.first().url;
} else {
return message.reply('Please provide an image link or attach an image to the message.');
}
// open image using sharp
let image;
try {
image = await sharp(imageUrl);
} catch (error) {
return message.reply('Invalid image URL or file type.');
}
// add text to image
const text = 'Hello World';
image = await image.composite([{
input: Buffer.from(text),
gravity: 'center'
}])
// send edited image in message
const buffer = await image.toBuffer();
console.log("Sending");
message.channel.send(new Discord.MessageAttachment(buffer));
});
the error says that the image I passed which is a discord image link is missing
I tried different images but the issue is still the same
Related
I'm trying to update user profile using react native expo I can only update all properties except image is giving me this Error :
[Unhandled promise rejection: FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field userImg in document users ? please help
const [image, setImage] = useState(null);
const [uploading,setUploading] = useState(false)
const [ userData, setUserData] = useState(null);
useEffect(()=>{
const getUserData = async ()=>{
db.collection("users")
.doc(auth.currentUser?.uid)
.get()
.then(snap => {
setUserData(snap.data());
});
}
getUserData();
},[])
const updateProfile = async()=>{
let imgUrl = await uploadImage();
if(imgUrl == null && userData.userImg){
imgUrl = userData.userImg
}
db.collection("users")
.doc(auth.currentUser.uid)
.update({
name: userData.name,
userName: userData.userName,
email: userData.email,
phone: userData.phone,
address: userData.address,
userImg:userData.mgUrl
})
}
I can upload the image successfully but I can't fetch it from storage to fire store
const uploadImage = async ()=>{
if(image == null){
return null;
}
const blob = await new Promise((resolve, reject)=>{
const xhr = new XMLHttpRequest();
xhr.onload = function (){
resolve(xhr.response)
};
xhr.onerror = function (){
reject( new TypeError("Network request failed"))
};
xhr.responseType = "blob"
xhr.open("GET",image,true)
xhr.send(null)
});
const ref = firebase.storage().ref().child("images/" + new Date().toISOString())
const snapshot = ref.put(blob)
snapshot.on(
firebase.storage.TaskEvent.STATE_CHANGED,
()=>{
setUploading(true)
},
(error)=>{
setUploading(false)
console.log(error)
blob.close();
return;
},
()=>{
snapshot.snapshot.ref.getDownloadURL().then((url)=>{
setUploading(false);
// Alert.alert('Profile Updated', 'You profile Updated Successfully..!')
console.log('donwload:', url)
setUserData(url)
blob.close()
return null
})
}
)
}
}
so please help me out between I'm using React Native Expo and thank you so much
To start off, the error [Unhandled promise rejection: FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: undefined means that one or more fields has a null value but firebase doesn't allow you to store that.
In your uploadImage function you're able to upload your image fine when the image actually does exist but in cases that it doesn't you're returning null which is where the problem is. Ideally, you can return an empty string which is safe then in cases where you read the image you can just check if the string is empty or not.
Fix
Step 1
Change this
if(image == null){
return null;
}
To this
if(image == null){
return "";
}
Step 2
After you get the download URL your setUserData is replacing all the fields with the URL so consider changing it to
`
setUserData({...userData, imgUrl : url})
Step 3
Also realize that in your update() there is a typo for imgUrl change from
userImg:userData.mgUrl to userImg:userData.imgUrl to properly set the image using the step for line
Hope that fixes It :)
`
Check if below code helps you to upload a Video or Image using firebase.
const uploadImageToFirestore = async (res, type) => {
const uri = res.assets[0].uri;
const filename = uri.substring(uri.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
const storage = getStorage(app);
const fileRef = ref(storage, filename);
const img = await fetch(uploadUri);
const bytes = await img.blob();
let metadata;
if (type == 'video') {
if (filename.includes("mov") || filename.includes("MOV")) {
metadata = {
contentType: 'video/quicktime'
}
} else {
metadata = {
contentType: 'video/mp4',
};
}
} else {
metadata = {
contentType: 'image/jpeg',
};
}
uploadBytes(fileRef, bytes, metadata).then(async (uploadTask) => {
console.log('task', uploadTask)
getDownloadURL(uploadTask.ref).then((url) => {
if (type == 'video') {
setVideoData(url);
} else {
setImageData(url);
}
});
}).catch((err) => {
alert('Error while uploading Image!')
console.log(err);
});
}
First of all sorry for the bad English
I'm trying to do a "tweet" system. I check if the link is true and has an image but if you put something like https://askhdkjahs.png the program thinks is an image and put in the embed giving an error
I need handle the error and put a default image or reply saying 'the image give a error'
thats my code
if (comando === `${prefix}atwt`) {
msg.delete({ timeout: 100 });
if (!argumento[0]) {
msg.reply('pon algo').then(msg => {
msg.delete({ timeout: 10000 });
}).catch(console.error);
}
else if(argumento !== null && argumento !== '') {
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://i.imgur.com/wSTFkRM.png')
.setColor('BLUE')
.setTimestamp();
const url = argumento[0].toString();
if (url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
else{
TweetAnon.setDescription(`**${argumento.join(' ')}**`);
}
const msgEmbed = await msg.channel.send(TweetAnon).catch(TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png'));
await msgEmbed.react('π');
await msgEmbed.react('π');
await msgEmbed.react('π');
}
}
I see something like that and I tried but doesn't work
if (comando === `${prefix}atwt`) {
const url = argumento[0].toString();
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://cdn.discordapp.com/attachments/769965806850670634/854834517709422602/anon.png')
.setColor('BLUE')
.setTimestamp();
msg.delete({ timeout: 100 });
try {
if (!url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
throw new Error('Invalid URL');
}
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
catch (error) {
TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png');
}
// else
// TweetAnon.setDescription(`**${argumento.join(' ')}**`);
// }
const msgEmbed = await msg.channel.send(TweetAnon).catch(err => console.log(err));
await msgEmbed.react('π');
await msgEmbed.react('π');
await msgEmbed.react('π');
}
You could check if the image exists like this:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
Usage:
if(imageExists(argumento[0])){
TweetAnon.setImage(argumento[0]);
}
I would like to know how to make it where if you drop an image in a certain channel, it turns into an embed.
My current code is this:
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const { Client, RichEmbed } = require("discord.js");
module.exports = {
name: 'icon',
run: async(client, message, args) => {
if(message.channel.id === '708914703338045491'){
message.delete();
let usermsg = args.slice(0).join(" ");
const embed = new MessageEmbed()
.setColor("#2f3136")
.setImage(usermsg);
message.delete().catch();
message.channel.send(embed)
}
}
}
If you upload image into message it's will save into message.attachments, so you can use this collection to check. Discord attachment can be a file, or video, so you need to check file format, the simple way - it's check end of the link to the content in it of a valid format, so i create 2 function.
First: for find attachment
Second: for validate url to content an image format in url
const { MessageEmbed } = require("discord.js");
const avalibleFormats = ['png', 'gif', 'jpeg', 'jpg']
module.exports = {
name: 'icon',
run: async(client, message, args) => {
if (message.channel.id !== '708914703338045491') {
return;
}
let image = getImage(message)
if (!image) {
return;
}
let embed = new MessageEmbed();
embed.setImage(image.url)
message.channel.send(embed)
}
}
const getImage = (message) => message.attachments.find(attachment => checkFormat(attachment.url))
const checkFormat = (url) => avalibleFormats.some(format => url.endsWith(format))
I have problem to update my image using react and axios I convert it in a form data but canβt work it always affiche an error in axios data
This is my method to put data when I remove image in the axios data the request go to the api with success when i put image in the axios data the request is unsuccessful ;(
onSubmit = (e) => {
e.preventDefault();
let fd = new FormData();
fd.append('image', this.state.images, this.state.images.name);
console.log(fd);
const { id, nom} = this.state.patient;
axios.put('/patients/' + this.props.match.params.id, {id, nom,fd})
.then((result) => {
this.props.history.push("/show/" + this.props.match.params.id)
if (result.data != null){
this.setState(this.initialState);
}
});
}
This is my handler image
handleFile(e) {
this.setState({ images: e.target.files[0] });
this.setState({ image: '' });
let reader = new FileReader();
let images = e.target.files[0];
reader.onloadend = () => {
this.setState({ file: images, imagePreviewUrl: reader.result });
}
reader.readAsDataURL(images)
}
I am working on a project that need to store images on Firebase storage. I use Ckeditor to upload image, I follow Ckeditor's docs to write my own image upload adapter, but it din't not work. I cannot upload image to firebase and get back the image url. here is what I've tried
class MyUploadAdapter {
constructor(loader) {
this.loader = loader;
}
upload() {
return this.loader.file
.then(file => new Promise((resolve, reject) => {
this._initRequest();
this._initListeners(resolve, reject, file);
this._sendRequest(file);
}));
}
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
_initRequest() {
const xhr = this.xhr = new XMLHttpRequest();
xhr.open('POST', 'https://firebasestorage.googleapis.com/v0/b/smart-farming-e3e2d.appspot.com/o/images/', true);
xhr.responseType = 'json';
}
// Initializes XMLHttpRequest listeners.
_initListeners(resolve, reject, file) {
const xhr = this.xhr;
const loader = this.loader;
const genericErrorText = `Couldn't upload file: ${file.name}.`;
xhr.addEventListener('error', () => reject(genericErrorText));
xhr.addEventListener('abort', () => reject());
xhr.addEventListener('load', () => {
const response = xhr.response;
if (!response || response.error) {
return reject(response && response.error ? response.error.message : genericErrorText);
}
resolve({
default: response.url
});
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', evt => {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
_sendRequest(file) {
const data = new FormData();
data.append('upload', file);
this.xhr.send(data);
}
}
function MyCustomUploadAdapterPlugin(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
return new MyUploadAdapter(loader);
};
}
const editorConfiguration = {
extraPlugins: [MyCustomUploadAdapterPlugin],
};
and I call it to use in my Component like this
<CKEditor
editor={ClassicEditor}
// data="<p>Hello from CKEditor 5!</p>"
onInit={editor => {
// console.log('Editor is ready to use!', editor);
}}
onChange={(event, editor) => {
const data = editor.getData();
console.log({ event, editor, data });
}}
config={editorConfiguration}
/>
Can anyone have experience with upload image from Ckeditor to firebase storage help me? Thanks u.
I have also been trying to fix this for ages now. I have now been able to upload an image to my server by adding CORS to the FireBase URL
xhr.open('POST', `https://cors-anywhere.herokuapp.com/https://firebasestorage.googleapis.com/v0/b/smart-farming-e3e2d.appspot.com/o/${file.name}`, true);
If you are wondering how I got the file attribute you need to pass it in the function
_initRequest(file) {
console.log(file.name)
const xhr = this.xhr = new XMLHttpRequest();
xhr.open('POST', `https://cors-anywhere.herokuapp.com/FIREBASE_URL_HERE{file.name}`, true);
xhr.responseType = 'json';
}
This should now upload your image to your Firebase storage