Discord Embed Image Response - node.js

I am having trouble with a random response command I have for a Discord bot.
At the moment the command sends back everything as intended except for an image link.
I have a number of random responses in an array, mostly text responses and one image response.
When the embed reply does the image response just appears as the image link, can anyone help so when it responds the image appears?
Here is the code from the array and then the main file:
const jokeResponses = [
"joke1",
"joke2",
"joke3",
"https://i.imgur.com/HXLENiv.png"
]
module.exports = {jokeResponses}
const { jokeResponses } = require('./jokeResponses.js');
case "joke":
var response = jokeResponses [Math.floor(Math.random()*jokeResponses .length)];
embed.setColor('#f299cd')
embed.setTitle(message.author.username + '`s joke')
embed.setDescription(response);
message.channel.send(embed);
break;
I don't understand why when the image link comes back it just appears as the link and not the actual image.
Appreciate any help.

.setDescription() is for text only, you would have to use .setImage() to display a gif
.setImage(response)

Related

How to parse video stream coming from the nodejs server

I'm creating a video streaming service, the backend code look like this:
const stream = new Readable();
stream.push(movie.data.slice(start, end + 1));
stream.push(null);
stream.pipe(res);
This when run in postman, postman automatically parses it and give me a video in the response. But when I'm using it in my code, it gives me responses in random characters
`ftypmp42isommp42îmoovlmvhdè'#trak\tkhd&è#hmdia mdhd2òUÄGhdlrvideISO Media file produced by Google Inc.°minf$dinfdrefurl pstblstsdavc1hHHÿÿ2avcCBÀÿágBÀÚ¿åÀZ  AâÅÔhÎ<sttsù4stsc
dstco
õÆSLÕÆH?ÛÔHAÍ°G.4¥¹®4³¤(ù¯- Å
GÐ
î¿østszùHÕ7ÈÕI~hS<
©ÅºÒ 3k 7 (;²w¶¸¯Ð«¥y¾mÙEòÙÕÊ®ß
nºK|'eiõE^H2_&Z£ÇVpÛË?O*z"±ÿ{¢×Õg&°]Øe¡OË¿£½í¯¥^y§t=ª$®Ü'² ²-míÜÆ£%(¶zÎ,4qj z º5ªÓ#ã§
!ßó¢uÌÎÏ£¢¿ß(u;xû/]ù%¡ErµÒà1§5&¬¤'£,i5Ó3óØ(â[¬³föçÑÀH
[`
Now the problem is that I don't know what is this, how to parse it, how to display it as a video... Need help

Alexa - How to send image to user?

I'm using a Lambda function for my Alexa Skill. For my launch intent, I query DynamoDB and return a String that I first want to convert into a QRCode and then I want to return it to the Alexa Device as an Image inside the responseBuilder
Alexa works fine displaying images from external urls such as
const rabbitImage = "https://i.imgur.com/U6eF0oH.jpeg";
return responseBuilder
.speak(say)
.withStandardCard("Welcome to Alexa", "description", rabbitImage, rabbitImage)
.reprompt('try again, ' + say)
.getResponse();
But I'm stuck on how to send the QRCode back to the Alexa Device in the responseBuilder.
I'm using a nodejs library called qrcode that can convert the String into a QRCode and then into base64.
https://www.npmjs.com/package/qrcode
But according to the Alexa docs for sending a "card" aka image, back to the user it has to be a url.
https://developer.amazon.com/en-US/docs/alexa/custom-skills/include-a-card-in-your-skills-response.html
The Alexa Skills Kit provides different types of cards:
A Standard card also displays plain text, but can include an image. You provide the text for the title and content, and the URL for the image to display.
So I'm not sure if the base64 generated by the qrcode library would work in this case.
What's the best way to send the dynamically generated QRCode back to the Alexa Device as a response in this scenario?
const LaunchRequest_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest';
},
handle(handlerInput) {
const responseBuilder = handlerInput.responseBuilder;
//Perform query to DynamoDB
var stringToCreateQRWith = "8306e21d-0c9e-4465-91e9-0cf86fca110d";
//Generate qr code and send back to user here
//???Unsure how to do and what format to send it in
var qrImageToSendToUser = ???
return responseBuilder
.speak(say)
.withStandardCard("Welcome to Alexa", "description", qrImageToSendToUser , qrImageToSendToUser )
.reprompt('try again, ' + say)
.getResponse();
}
As #kopaka proposed, this is the way to go.
There is no way around it.
As per the documentation
They are a few thing you need to have in mind.
On the images itself, you will want to create 2 images with 720px x 480px and 1200px x 800px. To make sure they display nicely on multiple screen size. Otherwise they do not guarantee the best experience for your user, as they may scale up/down the image to fit.
On the storage choice, you need to make sure to be able to serve those images via Https and with a valid ssl certificate trusted by amazon.

How can I transform a canvas object into an image to send as an API response?

So I have a custom node module that works with the canvas module (no browser interaction).
I'm building an expressjs webserver that has an endpoint that should return images. This expressjs app has access to my custom module and can retrieve the canvas objects from it.
My question is - how exactly do I transform the canvas into a png and then send it as a response without actually saving the canvas as png in the server? From other related questions on stackoverflow, I see that sending images as a response is as simple as using the res.sendFile() function, but the issue is I don't actually have the .png file, nor do I want to transform the canvas to a png, save it on the server, and then send it. It must be possible to do this programmatically somehow.
Here's a code example of the endpoint:
app.get('/api/image/:id', async (req, res) => {
let imageId = req.params.id;
let customModule = new CustomImage(imageId);
let imageCanvas = customModule.getCanvas();
let imageName = customModule.getName();
// this next step is what I'm trying to avoid
fs.writeFileSync(`.tmp/${imageName}.png`, imageCanvas.toBuffer("image/png"));
res.sendFile(`./tmp/${imageName}.png`)
} )
Thank you.
Instead of res.sendFile use this, it will do the trick:
//create the headers for the response
//200 is HTTTP status code 'ok'
res.writeHead(
200,
//this is the headers object
{
//content-type: image/png tells the browser to expect an image
"Content-Type": "image/png",
}
);
//ending the response by sending the image buffer to the browser
res.end(imageCanvas.toBuffer("image/png"));

Why do Tenor GIFs result in a Discord poop image in embeds?

Code Introduction
I was making a command where if you type p!shrug it sends a random shrug GIF from Tenor. I'm using Tenor API and node-fetch for my code.
Problem
The bot sends an embed as requested but the image in the embed is a Discord Poop image
My Code
const Discord = require('discord.js');
const fetch = require('node-fetch');
module.exports = {
name: 'shrug',
description: 'Shruggy Shruggy',
async execute(client, message, args){
const url = `https://api.tenor.com/v1/search?q=anime_shrug&key=${process.env.tenorkey}&limit=24`
const res = await fetch(url);
const result = await res.json();
const gif = Math.floor(Math.random() * result.results.length);
const newGIF = new Discord.MessageEmbed()
.setAuthor(`${message.author.username} shrugs~`, message.author.displayAvatarURL())
.setImage(result.results[gif].url)
.setColor('RANDOM')
message.channel.send(newGIF)
.then(console.log(result.results[gif].url))
}
}
More Info
The GIF works when I copy the link of GIF from the embed and paste it, it loads.
Answer
Ok so basically I fixed it with just a small change
result.results[gif].url returns the Tenor GIF link which cannot be used as an image in an embed.
And the change I made was :-
result.results[gif].url to result.results[gif].media[0].url which returns a media link that can be used in an embed.
I would be thankful for further help, but this did fix my problem.

Discord.js sending base64 encoded image to channel

i've been at this for days now and im stuck on this final part.
as the title suggests my creation receives a base64 encoded image. it then loads it into a buffer and attempts to send it to to a channel like so:
sfbuffer = new Buffer.from(base64_img, "base64");
const finalattach = new Discord.MessageAttachment(sfbuffer);
message.channel.send(finalattach);
it does send the buffer however it always results in this
example of base64 data that gets loaded
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAEA and so on...
i've tried sending it with file options (didn't even send), and as an embed using both .setimage and .attachfiles and both produce the same results. please im banging my head over this. all the google links are purple and i don't know what else to do D:
image buffers should NOT contain the
data:image/png;base64, part. only the non-human readable data
split the base64 string at the comma, load it into a attachment as a buffer and send attachment e.g.
const sfbuff = new Buffer.from(base64_img.split(",")[1], "base64");
const sfattach = new Discord.MessageAttachment(sfbuff, "output.png");
message.channel.send(sfattach)
Even though i figured it out, i couldn't of done it without Aviv lo
Thank you all :)
Try something like this:
replyMessage.Attachments.Add(new Attachment()
{
ContentUrl = $"data:image/jpeg;base64,{Convert.ToBase64String(bdata)}"
});
This post is answering similar questions.

Resources