So i managed to get username from a link but im unsure of how to actually get the userid back.
I want it so when it to say the username which works perfectly, but down in thumbnail when i try to fetch the userId it comes up as "userId is not defined".
I'm it sure what the solution is but I want to keep both userId and username.
here is my code!
const getUsername = userId => new Promise(resolve => {
fetch('https://users.roblox.com/v1/users/' + userId)
.then(res => res.json())
.then(body => resolve(body.name || 'Unknown'))
.catch(() => resolve('Unknown'))
})
(async () => {
const username = await getUsername(nextInQueue.offers[0].userId);
consola.success(`[${username}] has ok items`)
fetch(config.webhook, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
"content": null,
"embeds": [
{
"title": ":tada: Trade sent to: " + username + " :tada:",
"color": 28420,
"fields": [
{
"name": "Cool Items:",
"value": itemNameList.join('\n')
},
{
"name": "Okay items:",
"value": toreceiveList.join('\n')
}
],
"author": {
"name": "Expoorttoo",
"icon_url": "https://i.pinimg.com/736x/4b/69/74/4b6974aef5d96580140ef2686072af3f.jpg"
},
"footer": {
"text": Sentto.toLocaleString() + " sent & " + tradeQueue.length.toLocaleString() + " set in queue"
},
"thumbnail": {
"url": "https://www.roblox.com/headshot-thumbnail/image?userId=" + userId + "&width=420&height=420&format=png"
}
}
]
})
})
})().catch();
}
oh yeah by the way its a webhook which it sends to on discord. It works without thumbnail but doesnt work with the thumbnail saying userid.
You are missing
const userId = nextInQueue.offers[0].userId;
Related
i want to render an email of all the users for testing purpose, In fact i have done that using this method. --- {dataFromApi.map((item, i) => {item.email})} but still it didn't work
const [dataFromApi, setDataFromApi] = useState([]);
const URL = 'http://localhost:5000/users'
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]);
}).catch( (err) => {
console.log(err);
})
}
return (
<div className="login">
<h1 className="loginTitle">Choose a Login Method</h1>
<p>{dataFromApi}</p>
<div className="wrapper">
.
.
.
.
.
here is the API response
[
{
"id": 1,
"email": "test1234#gm.com",
"password": null
},
{
"id": 2,
"email": null,
"password": null
},
{
"id": 3,
"email": "test#123.com",
"password": "12345678"
},
{
"id": 4,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 5,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 6,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 7,
"email": "NEWtest#231.com",
"password": "123"
}
]
but getting this error
react_devtools_backend.js:4012 The above error occurred in the component:
and
react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {id, email, password}). If you meant to render a collection of children, use an array instead.
Like Adam said in the comments, you are trying to pack a collection of things into a tag meant for a single thing. You should iterate over the list rendering a thing for each item.
{dataFromApi.map((item, i) => <p key={i}>{item.email}</p>)}
I got the answer why i'm not getting the expected output because in this code
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]); // this will store only one object into an array
}).catch( (err) => {
console.log(err);
})
}
here setDataFromApi(data[0]) will store only 1 object and to access the email from the object, we have to use only dataFromApi.email else dataFromApi will give only object which we can't render so that's why it is giving an error.
In React Javascript - how would I send a message to a post with a specific id? Here's a sample object:
{
"success": true,
"error": null,
"data": {
"post": {
"location": "Bronx, NY",
"willDeliver": false,
"messages": [],
"active": true,
"_id": "5e8d1bd48829fb0017d2233b",
"title": "Schwinn Bicycle",
"price": "3.88",
"description": "This is a 19 speed bicycle, barely used.",
"author": {
"_id": "5e8d1a02829c8e0017c20b55",
"username": "joe1234"
},
"createdAt": "2020-04-08T00:33:24.157Z",
"updatedAt": "2020-04-08T00:33:24.157Z",
"__v": 0,
"isAuthor": true
}
}
}
I must be grabbing the id incorrectly because the message isn't sending to the right post.
I have a useState initialized with an empty string to store the post id so I can pass it into the fetch URL request.
const [postId, setPostId] = useState("");
const response = await fetch(`${API_URL}/posts/${id}/messages`
Here's the code I have so far
const sendMessage = async (token, id, content) => {
try {
const response = await fetch(`${API_URL}/posts/${id}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
message: {
content: content,
},
}),
});
const data = await response.json();
alert("message successfully sent");
return data;
} catch (err) {
console.error(err);
}
};
<form
name="message"
onSubmit={(event) => {
event.preventDefault();
posts.map((post) => {
setPostId(post._id);
});
}}
<label htmlFor="content">Content: </label>
<input
type="text"
name="content"
value={messageContent}
required
onChange={(event) => {
setMessageContent(event.target.value);
}}
/>
<button
onClick={() => {
sendMessage(token, postId, messageContent);
}}
>
Send
</button>
Thanks for any hints or help!
I'm using Slack Bolt Framework with Javascript and I'm trying to do a http request. The problem is that the code is not waiting the request to be finished even using async/await. It always gives 'undefined'
The endpoint I'm requesting is 'https://viacep.com.br/ws/' + cep + '/json/' where cep is a parameter set by the user (like 09784100 for instance).
Here is the code that call the http request function:
// Action listener function called when an interactive component with action_id of “submitCEPButton” is triggered
app.action('submitCEPButton', async ({ ack, body, client, say, text}) => {
// Acknowledge action request before anything else
await ack();
let channelID = body.channel.id
let userID = body.user.id
var cep = body.state.values['inputBlock']['inputCEP'].value
if(isValidCep(cep)){
//console.log('É valido');
let data = await getAddressData(cep);
console.log(data);
await say({
"blocks": [
{
"type": "header",
"block_id": "headerBlock",
"text": {
"type": "plain_text",
"text": "🔍 Busca de Endereço - Resultado",
"emoji": true
}
},
{
"type": "divider",
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Rua: * " + data.logradouro
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Complemento: * " + data.complemento
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Bairro: * " + data.bairro
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Cidade: * " + data.localidade
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Estado: * " + data.uf
}
}
]
})
}
else{
await client.chat.postEphemeral({
channel: channelID,
user: userID,
text: `<#${userID}> ❌ CEP inválido. Verifique o CEP digitado e tente novamente.`
});
}
});
And here is the code that make the http request:
//Make http request
async function getAddressData(cep){
var url = 'https://viacep.com.br/ws/' + cep + '/json/';
let data = '';
https.get(url, res =>{
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
data = JSON.parse(data);
//return data;
})
})
return data;
}
You're mixing async models between callbacks and async/await methodology. Instead, try this (using superagent, which has async native mechanisms, to simplify the code I'm writing):
const superagent = require('superagent');
async function getAddressData(cep){
const url = 'https://viacep.com.br/ws/' + cep + '/json/';
const response = await superagent.get(url);
return response.body;
}
As an alternative, you could also use a Promise if you want to stick with vanilla Javascript HTTP Request.
I've been doing some work with the Slack API and with their
interactive messages
I post a message with the interactive message attachment here:
export const postMessage = (msg, channel) => {
request({
method: 'POST',
uri: 'https://slack.com/api/chat.postMessage',
headers: {
'content-type': 'application/json;charset=UTF-8',
Authorization: `Bearer ${process.env.SLACKTOKEN}`,
},
body: JSON.stringify({
token: process.env.SLACKTOKEN,
attachments: [
{
"text": "",
"fallback": "If you could read this message, you'd be choosing something fun to do right now.",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "command_selection",
"actions": [
{
"name": "command_list",
"text": "Choose a command",
"type": "select",
"options": [
{
"text": "Register Team",
"value": "registerTeam"
},
{
"text": "Edit Team",
"value": "editTeam"
},
{
"text": "Get By Url",
"value": "getByUrl"
},
{
"text": "Report Issue",
"value": "reportIssue"
},
{
"text": "Find Team",
"value": "findTeam"
},
{
"text": "List Teams",
"value": "listTeams"
}
]
}
]
}
],
text: msg,
channel,
as_user: true,
})
}, (err, res, body) => {
if (err) {
console.log('error posting msg: ', err);
} else {
console.log('post message to channel: ', body);
}
})
}
Slack then sends a POST request to this URL with a response_url parameter in their payload. This is where I'm getting the payload from in my code:
api.post('/interactivity', (req, res) => {
const { body } = req;
const { payload } = body;
const parsedPayload = JSON.parse(payload)
res.send(parsedPayload.response_url)
var message = {
"text": payload.user.name+" clicked: "+payload.actions[0].name,
"replace_original": false,
}
util.sendMessageToSlackResponseURL(parsedPayload.response_url, message)
})
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
json: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
For some reason though, the response_url is giving an invalid_payload error when I click on the link and I can't figure out if its the payload I'm sending in the original message I posted or something's up with the POST request that Slack sent
The issue is with utility method on line json: JSONmessage which should be body: JSONmessage
Updated code,
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
Hope this works!
I have problem with sending data via POST method in fetch(). So the problem is that from this >> body: JSON.stringify({ id: uuid(), name, password }) it sends couple of times almost the same data (i receive unique id, and diplicated name and password). In the othet words: with one form submission, I've got few objects with differnt id, and same name and password. Code:
const handleSubmit = e => {
e.preventDefault();
users.map(user =>
user.name !== name && name.length >= 3 && password.length >= 5
? fetch('http://localhost:3003/users', {
method: 'POST',
body: JSON.stringify({ id: uuid(), name, password }),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.ok) {
return res.json();
}
throw new Error('Error');
})
.then(c => setUser([...users, c]))
.then(errorUserChange(false))
: errorUserChange(true)
);
};
db.json:
{
"users": [
{
"id": "c1a10ab0-24c7-11ea-af77-3b28fe4ea407",
"name": "cccccc",
"password": "cccccc"
},
{
"id": "cbf73890-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
},
{
"id": "cbf786b0-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
}
]
}
Of course I know that's not the best way to hold password, I'm just practicing json server and fetch().
Thanks for any help!