I am looking to display a image / gif url in the embed, if it has embedded content it will show it along with the url. Currently, I only figured out how to display if the message was uploaded to discord as a attachment.
Example, the avatar is shown within the embed. This is the same concept I want for images with embedded content.
const embed = new MessageEmbed()
.setDescription(message.content)
.setColor("#E74C3C")
.setTimestamp()
.setImage(message.attachments.array().length == 0 ? null:message.attachments.first().url)
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: true })
);
From what I understand is you are trying to set an image into your embed of an already existing image to the embed that shows while we put our URL.
You can simply use the MessageEmbed constructor's MessageEmbed#setImage() method along with extracting the image from the link as the URL parameter to the method like so ( for that you need to send it to discord first ) :
const { MessageEmbed } = require("discord.js")
message.channel.send("https://discord.com/").then( (embeddedmessage) => {
let image = embeddedmessage.embeds[0].thumbnail.url
const x = new MessageEmbed()
x.setTitle("Discord URL's Image")
x.setImage(image);
embeddedmessage.edit(x);
});
The message with the URL ( if has an embed ) would have an rich embed object which would justify the image present within it ( here is the example object from the URL we took in our code:
{
"title": "Discord | Your Place to Talk and Hang Out",
"type": "rich",
"description": "Discord is the easiest way to talk over voice, video, and text. Talk, chat, hang out, and stay close with your friends and communities.",
"url": "https://discord.com/",
"timestamp": null,
"color": null,
"fields": [],
"thumbnail": {
"url": "https://discord.com/assets/652f40427e1f5186ad54836074898279.png",
"proxyURL": "https://images-ext-2.discordapp.net/external/pL0w57uLXr8vYKityoLlH1CVuGCs0fB5xnrWKO8Fqoo/https/discord.com/assets/652f40427e1f5186ad54836074898279.png",
"height": 630,
"width": 1200
},
"image": null,
"author": null,
"footer": null
}
Maybe you can try .setURL() ?
if(message.attachments.size > 0) {
embed.setURL(message.attachments.first().url)
}
Related
I am using Expo MediaLibrary to get videos from a specific folder and I am facing this problem.
MediaLibrary.getAssetsAsync() shows there are no media inside an album. while there are media inside the folder.
Code:
let album = await MediaLibrary.getAlbumAsync("GrabTube")
console.log(album )
let assets = await MediaLibrary.getAssetsAsync({album:album })
console.log(assets)
response:
Object {
"assetCount": 1,
"id": "876214992",
"title": "GrabTube",
}
Object {
"assets": Array [],
"endCursor": "0",
"hasNextPage": false,
"totalCount": 0,
}
In the first console.log, it shows there is one item/asset inside the folder. But as shown inside the second console.log it shows the folder is empty.
Is there any fix for this?
For some reason it's necessary to define the mediaType even when you have already defined the album...
to me the solution was change from :
let assets = await MediaLibrary.getAssetsAsync({album:album })
to:
let assets = await MediaLibrary.getAssetsAsync({album:album, mediaType:'audio' })
I using Draft-js to build my text-editor.
What I want to do is on clicking the submit button, the submitted text should appear on right side (as you can see, the blank side)
I'm calling a handleSubmit function to post the content to server:
handleSubmit = e => {
e.preventDefault();
const query = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()));
const payload = {
query:query
}
axios({
url:'http://localhost:9000/queries',
method:'POST',
data: payload
})
}
and to retrieve the content :
getQueries(){
axios.get("http://localhost:9000/queries")
.then(response => {
const data = response.data;
this.setState({queries:data});
})
}
I'm bit confused, on how to use convertFromRaw to convert the content to the desired text.
Where should I call the method ?
Thanks in advance
You have to understand that DraftJS is a library that converts whatever you have inside the editor into it own format.
For Example, apple is converted to,
{
"blocks": [{
"key": "f6b3g",
"text": "apple",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [{
"offset": 0,
"length": 5,
"style": "ITALIC"
}],
"entityRanges": [],
"data": {}
}],
"entityMap": {}
}
Yep, it's that big. So, in order to convert it back from this format to apple you need a component which knows how to interpret it. You cannot just use a div tag. In this case, it's the editor component itself!
So you can do the following to display the content in readonly mode.
<Editor readOnly={true}
editorState={EditorState.createWithContent(this.state.editorState.getCurrentContent())}/>
Now, say if you want to send the editor contents to an API so that you can save it in DB and then get the content from the API and display it.
Convert from Editor Format to JSON
const requestBody = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()))
Post JSON to your API
fetch(url, {
method: 'POST',
body: requestBody
});
Get JSON from your API
const response = await fetch(url, {
method: 'GET'
});
Convert from JSON to Editor format and display using Editor (You can remove readonly if you want the user to edit the contents)
<Editor readOnly={true}
editorState={EditorState.createWithContent(convertFromRaw(JSON.parse(response))}/>
So I am making a geo tool app using reactjs. The design for this part is this, user submit a city's name. The submission will trigger a post request, and the request will loop through a city list.json file to find the matched city and will return the city's geolocation in such format
{
"id": 6167865,
"name": "Toronto",
"state": "",
"country": "CA",
"coord": {
"lon": -79.416298,
"lat": 43.700111
}
}
the post request at front end is
axios.post('http://localhost:5000/weather/loggedin/citySearch',searchCity)
.then((res)=>{
console.log(res.data.coord)//<--here
})
the post request at server side (backend) is
router.post('/loggedin/citySearch',(req,res)=>{
let cityname = req.body.cityName
let countryname = req.body.country
fs.readFile('../public/weatherdata/citylist.json', (err,data)=>{
if(err){
console.log(err)
res.send('Wrong.')
}else{
user_info.cityName = cityname
let selected_city=(JSON.parse(data)).filter(i=>i.name===cityname && i.country===countryname)
console.log(selected_city[0].coord)//<--and here
res.json(selected_city[0])
}
})
})
Can someone tell me why I get different outputs when using
console.log(res.data.coord) //used at axios and it returns the coordinates
vs.
console.log(res.selected_city[0].coord) //used at server.js and it returns undefined
I was wondering if axios and express take dot notation differently?
Disregard the question
I never put selected_city[0]in my code
I am trying to call the backend api which results in the details of the specific product based on id for example the api is http://localhost:54729/api/product/1 the 1 in the api is the id of the specific product. I am using redux and axios to get the data from the api.
EDIT:
The response from the api from which I am getting is the following
[
{
"id": 0,
"title": "TestProductAzure",
"description": "<p>While working with the EF Core Code-First approach, we create the classes for our domain entities first. Later, we’ll create the database from our code by using migrations. This is the opposite of the Database-First approach where we design our database first and then create the classes which match our database design.In the EF Core Code-First approach, we have full control over the code and the database is just a store without any logic. This approach is helpful in situations where we are starting with the development of a new project and we don’t have a clear picture of how our database should look like yet.We don’t have to worry about creating and updating the database. We can just make the changes in our code and then sync everything easily with the database. The important thing to note is that the manual changes that we make to the database could be lost during migration. So we should make changes to the code only.</p>",
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/1",
"type": "Internal",
"rank": 5
},
{
"id": 0,
"title": "Support | example.com",
"description": null,
"owner": null,
"link": "/search/product?url=https://www.example.com/support/",
"url": "https://www.exampl.com/support/",
"type": "External",
"rank": 3
},
{
"id": 0,
"title": "TestProductForAzure",
"description": null,
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/3",
"type": "Internal",
"rank": 0
},
The above response is the response when someone search something with the keyword. Now what I want if the user clicks on the url that has the api like http://localhost:54729/api/product/ I want to check the last number of the api i.e. the id and get the response from that forexample, if the user clicks on http://localhost:54729/api/product/2 . I want to pass the id 2 to the function which will then get pass from action and axios.get give the response.
My Action look like this
export function detailsProduct(id) {
const token = userService.getToken();
console.log(token);
const api = `/product/${id}`;
axios
.get(apiBaseUrl + api, { headers: { Authorization: `Bearer ${token}` } })
.then(res => {
console.log("helloProductDetails", apiBaseUrl + api);
try {
store.dispatch({
type: PRODUCT_DETAILS,
payload: res
});
} catch (err) {
console.log("error", err);
}
});
My Reducer look like this:
case PRODUCT_DETAILS:
console.log(
"action",
action,
"actionPayload",
action.payload,
"state",
state
);
return {
...state,
products: action.payload,
loading: false,
totalRecords: action.payload.length
};
and my .jsx react look like this
function onClickHandler() {
console.log("calling Details Product, HardCodedly");
detailsProduct(1);
}
return (
<div className="row">
<div className="s130">
{/* <div class="col-lg-8 col-xs-8 col-sm-12 col-md-7"> */}
<div className="col-lg">
<div className="container">
{result.type === "Internal" ? (
<Link to={DoctorProductLocation.path} onClick={onClickHandler}>
<h3>{result.title}</h3>
</Link>
) : (
//Try With OnClick Function
<a href={result.url} target="_blank">
<h3>{result.title}</h3>
</a>
)});
As you did notice , I'm sending the id hardcoded for now just to check if I am getting the information, which is working fine. But All I want to do is that when I click on the response it will automatically check the id and send us the response of that.
I thought of splitting the url until the id and pass it to the function action. But I don't know How? Or else if you have any other good idea, I will be thankful to you.
I am using gmailAPI to read an email message. From the JSON returned, I get an attachmentId and then I query gapi.client.gmail.messages.attachments.get to get the attachment itself. I am testing the code below with a png attachment and I do get JSON back and the data attribute I assume is base64 because that is what the header says
//Yes, I know the code below could be better but for now I am trying to figure what is contained in data.
function getAttachmentContent(attachmentDict, attachmentId, isLast) {
var request = gapi.client.gmail.users.messages.attachments.get({
'userId': 'me',
'messageId': getParameterByName('msgid'),
'id': attachmentId
});
request.execute(function (resp) {
attachmentDict[attachmentId].gmailAttachmentItem.Length = resp.size;
attachmentDict[attachmentId].gmailAttachmentItem.Content = resp.data;
if (isLast) {
//Return only the key values as an array.
var attachmentArray = new Array();
for (key in attachmentDict) {
if(key.indexOf("index") < 0)
attachmentArray.push(attachmentDict[key].gmailAttachmentItem);
}
emailMessage.GmailAttachments = attachmentArray.slice(0, attachmentArray.length - 1);
}
});
}
The JSON fragment which contains the attachmentid
{
"partId": "1",
"mimeType": "image/png",
"filename": "unnamed.png",
"headers": [
{
"name": "Content-Type",
"value": "image/png; name=\"unnamed.png\""
},
{
"name": "Content-Description",
"value": "unnamed.png"
},
{
"name": "Content-Disposition",
"value": "attachment; filename=\"unnamed.png\"; size=13258; creation-date=\"Mon, 29 Aug 2016 13:34:23 GMT\"; modification-date=\"Mon, 29 Aug 2016 13:34:24 GMT\""
},
{
"name": "Content-Transfer-Encoding",
"value": "base64"
}
],
"body": {
"attachmentId": "ANGjdJ8d3DgMc6114J2v-R16nU1biO2et7xOQZuC23BQgIXVq7v8mn-Ssn88I_zD-HOo6ArbKmv7vFe-1mkZKjNVkLPqP1n8wwhCgON-wh_BFkrArBkIU6SWN4Zh2uvKY2FQLIyCcJtyHDmZlgZB8b4MlLGiBXldpLJ0ioTH4f3De9YVuq5AxhioxbS9X2bggN2tT4YOZgXknVpBvsZ0O00Z43jAB92g3xMFqJjYeLN_l-vL0Xb73WY-xtwXWLGAPWlyD0wPq6a4Fi-qX_RWTfwMZN12AtGaLFFyrtGEKSfEo1cLKzYN8VosPPSVZHA",
"size": 18146
}
}
I get this response and the content in data is it base64 image?
I am using jsfiddle link to show the data because pasting the entire response exceeds the 30000 characters limit.
The content in the data attribute is base64 image? If not, what is it? According to Google
attachmentid: When present, contains the ID of an external attachment that can be retrieved in a separate messages.attachments.get request. When not present, the entire content of the message part body is contained in the data field.
size: Total number of bytes in the body of the message part.
data: The body data of a MIME message part. May be empty for MIME container types that have no message body or when the body data is sent as a separate attachment. An attachment ID is present if the body data is contained in a separate attachment.
The size I get back when I download an email message 18146 is different from the attachment size 13258. Attachmentid is present, so I should get the attachment when I use gapi.client.gmail.users.messages.attachments.get but the size is different?
How do I get the image which is attached to the email.
Looks like you're calling with message.get(format=FULL) currently? In that case the "attachmentid" can be supplied to a separate message.attachment.get() call to retrieve the attachment content. You can, alternatively, just call message.get(format=RAW) to retrieve the entire email, unparsed, in a single response.