How to get 'captureDate' from values and send it as a message - javascript

So I'm adding a feature to my discord bot to collect the users most recent gameclip, at the moment I'm able to collect all the information in my console log but struggling to understand how to send it in a message. I'm pretty new to this stuff.
This is a snippet of my code right now:
const userXuid = await XboxLiveAPI.getPlayerXUID(gamertag, authInfo).catch(err => message.reply('That gamertag could not be found. Make sure spaces are replaced with \'_\''));
const scores = await XboxLiveAPI.getPlayerScreenshotsFromMediaHub(userXuid, authInfo, num);
console.log(scores);
And this is what gets returned to the console:
{
continuationToken: 'YWJjZGVfdnd4eXoxMDA1',
values: [
{
captureDate: '2016-09-13T19:11:11Z',
contentId: 'e61118b6-c940-4hc9-a32a-49dd53ab4192',
contentLocators: [Array],
CreationType: 'Edited',
localId: '501bf44b-c1b2-4519-b78e-a1f88097f8d1',
ownerXuid: 25332749247888726,
resolutionHeight: 720,
resolutionWidth: 1280,
sandboxId: 'RETAIL',
sharedTo: [],
titleId: 1129121809,
titleName: 'OF: Dragon Rising',
dateUploaded: '2016-09-13T19:12:34.6226406Z',
uploadLanguage: 'en-GB',
uploadRegion: 'GB',
uploadTitleId: 201477059,
uploadDeviceType: 'XboxOne',
commentCount: 0,
likeCount: 0,
shareCount: 0,
viewCount: 2,
contentState: 'Published',
enforcementState: 'None',
safetyThreshold: 'None',
sessions: [],
tournaments: []
}
]
}
Conclusion
So how would I, for example, get captureDate to send in:
message.channel.send(???)
Any help would be appreciated, cheers!

If you're simply talking about accessing captureDate, you'll use scores.values[0].captureDate.

Related

How to to put fetched data into the state?

I am trying to put fetched data into the state but it's not working, please let me know what I am doing wrong here, and also I want specific data to be inside the state like in this example I want only questions, answers, and incorrect answer, also I wanted to put the whole data into the array of object
const [quiz,setQuiz]=useState({});
useEffect(()=>{
const getQuizData =async ()=>{
const res = await fetch("https://opentdb.com/api.php?amount=10")
const data = await res.json();
setQuiz({data});
}
getQuizData();
},[])
what coming from your data is below. I suspect what you want is setQuiz(data.results) also initializing like useState([]) should help too.
const data = {
response_code: 0,
results: [
{
category: 'History',
type: 'multiple',
difficulty: 'medium',
question: 'Joseph Smith was the founder of what religion?',
correct_answer: 'Mormonism',
incorrect_answers: ['Buddhism', 'Christianity', 'Hinduism'],
},
{
category: 'Sports',
type: 'multiple',
difficulty: 'medium',
question: 'In a game of snooker, what colour ball is worth 3 points?',
correct_answer: 'Green',
incorrect_answers: ['Yellow', 'Brown', 'Blue'],
},
],
};

Google sheets api append multiple values with formatting

I have an array of values that i want to insert to a google sheet via API, i need to give color formatting to certain cells depending on the content of the cell like the image below:
I get to insert the values using append but i have no found any example on formatting append requests.
let values = [["Department", "Product", "Cost", "Status"],
["Clothes", "Socks", "12" "On Stock"],
["Clothes", "Hat", "15.99", "Out of stock"],
["Fresh","Apple", "18", "Pending"],
["Fresh", "Bannana", "17" "Out of stock"],
["Kitchen", "Spoon", "0.99", "Out of stock"]]
await googleSheets.spreadsheets.values.append({
auth,
spreadsheetId,
range: "Products",
valueInputOption: "USER_ENTERED",
resource: {
values: values,
},
});
What is the best approach to achieve this? batchUpdate? how would it be implemented with batchUpdate?
In your situation, how about using ConditionalFormatRule? When ConditionalFormatRule is used, when a script is run one time, the colors are automatically reflected. In order to achieve this, a sample script is as follows.
Sample script:
const googleSheets = google.sheets({ version: "v4", auth }); // Please use your authorization script.
const spreadsheetId = "###"; // Please set Spreadsheet ID.
const sheetId = "###"; // Please set Sheet ID.
// These values and colors are from your showing image.
const colorObj = [
{ value: "On Stock", rgb: [182, 215, 168] }, // #b6d7a8
{ value: "Out of stock", rgb: [244, 204, 204] }, // #f4cccc
{ value: "Pending", rgb: [252, 229, 205] }, // #fce5cd
];
const requests = colorObj.map(({ value, rgb }, i) => ({
addConditionalFormatRule: {
index: 0,
rule: {
booleanRule: {
condition: {
values: [
{
userEnteredValue: value,
},
],
type: "TEXT_EQ",
},
format: {
backgroundColor: {
red: rgb[0] / 255,
green: rgb[1] / 255,
blue: rgb[2] / 255,
},
},
},
ranges: [
{
sheetId,
startColumnIndex: 3,
endColumnIndex: 4,
startRowIndex: 1,
},
],
},
},
}));
const res = await googleSheets.spreadsheets.batchUpdate({
spreadsheetId,
resource: { requests },
});
In this modification, this ConditionalFormatRule is reflected in the range of "D2:D".
Note:
I guessed that from your showing script, you might be using googleapis for Node.js. So, this sample scirpt is for googleapis for Node.js.
References:
Method: spreadsheets.batchUpdate
AddConditionalFormatRuleRequest

BigQuery API does not return newest table of a dataset

I need to find the most recent table by creation time in a BigQuery dataset. I have an Google Apps Script function that could find the newest table and it used to work fine when there were only a few tables in the dataset, but ever since there are more tables in the dataset(72 to be exact) it just keeps returning the same "newest" table (e.g tablename_1623468444656), even though I know that there exists a newer one.
The problem seems to be the size of the logger output, because when I log the output it says: "Logging output too large. Truncating output". But regardless of whether I log the output or not, it just returns the allegedly newest table (e.g tablename_1623468444656).
I don't know what I need to change so that the function can find the actual newest table again. The function looks like this:
function findNewestTables() {
const data = BigQuery.Tables.list('Projectname', 'Datasetname');
let
maxSoFar = 0,
id = "";
data.tables.forEach(table => {
const time = parseInt(table.creationTime);
if(time > maxSoFar){
maxSoFar = time;
id = table.id;
}
});
const formattedId = id.replace(":", ".");
// return formattedId;
console.log(data);
console.log(formattedId);
};
Part of the output looks something like this and then it is just abruptly cut off.
Logging output too large. Truncating output. { totalItems: 72,
kind: 'bigquery#tableList',
etag: '7+eK1beNA7CVq0xasdfdsfYw==',
nextPageToken: 'Team_1627356444573',
tables:
[ { id: 'tablename_1623468444656',
type: 'TABLE',
kind: 'bigquery#table',
creationTime: '1628585864499',
tableReference: [Object] },
{ tableReference: [Object],
id: 'tablename_1623554844685',
kind: 'bigquery#table',
creationTime: '1628585864503',
type: 'TABLE' },
{ id: 'tablename_1623641244614',
type: 'TABLE',
kind: 'bigquery#table',
tableReference: [Object],
creationTime: '1628585864573' },
{ tableReference: [Object],
kind: 'bigquery#table',
creationTime: '1628585864714',
type: 'TABLE',
id: 'tablename_1623727644545' },
{ tableReference: [Object],
kind: 'bigquery#table',
type: 'TABLE',
creationTime: '1628585865059',
id: 'tablename_1623814044558' },
{ creationTime: '1628585865037',
id: 'tablename_1623900444676',
type:
Thanks in advance for any tips.
So, this is one of those cases where you need to paginate. See the nextPageToken? If that value isn't empty/nil, it means you can call tables.list again and pass that token as the pageToken GET param in a subsequent request to get the next page of results.
More details about the API: https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/list

Javascript console.log status of Cucumber scenario

I would like to print the status of each cucumber scenario using the afterScenario hook.
I've tried printing out scenario.status (code below) but it prints out "undefined"
afterScenario: (scenario) => {
console.log(scenario.status);
}
When printing out just scenario, I don't see status.
Scenario {
feature:
Feature {
description: undefined,
keyword: 'Feature',
line: 1,
name: 'Sample Test',
tags: [],
uri: '/Users/Daredevil/e2e/features/sampleProject/intro.feature',
scenarios: [ [Circular] ] },
keyword: 'Scenario',
lines: [ 15, 7 ],
name: 'Getting test status',
tags:
[ Tag { line: 6, name: '#WIP' }],
uri: '/Users/Daredevil/e2e/features/sampleProject/intro.feature',
line: 15,
description: undefined,
steps:
[ Step {
arguments: [],
line: 4,
name: 'I am on the app',
scenario: [Circular],
uri: '/Users/Daredevil/e2e/features/sampleProject/intro.feature',
isBackground: true,
keyword: 'Given ',
keywordType: 'precondition' },
Step {
arguments: [],
line: 8,
name: 'I am viewing the splash screen',
scenario: [Circular],
uri: '/Users/Daredevil/e2e/features/sampleProject/intro.feature',
isBackground: false,
keyword: 'Given ',
keywordType: 'precondition' } ] }
I had a read through https://docs.cucumber.io/cucumber/api/#hooks which suggested (from my understanding) to do scenario.failed, but I still get undefined.
Would anyone be able to tell me how I can get the status of a scenario?
I am using cucumber v3.2.1 and wdio-cucumber-framework v1.0.3.
Answer is simple, you should be console logging "scenario.result.status" instead of scenario.status.
Hope this answer helps you!
Below should work-
(tried with wdio-cucumber)
After(function (scenarioResult) {
const scenario = scenarioResult.scenario;
console.log('SCENARIO EXECUTION COMPLETED:',scenario.name);
});
This is not an answer just a suggestion. I would look into how the report.json is built as that report has all the scenarios and their result.
Another pointer is in your cucumber.js file set the reporting format you want to progress which will output progress to the console.
Take a look at https://github.com/cucumber/cucumber-js/blob/master/docs/cli.md#Formats

Paypal integration issue in titanium

I have to implement Paypal into my application. Here I have added some products into the cart. If I click the cart, I have to pay the amount using Paypal.
When clicking the Paypal button, I am getting the following error:
The amounts specified for item price,tax,and shipping do not add up to the total amount.
Why am getting this error?
I am using the following code:
$.paypalWindow.addEventListener('open', function(){
var Paypal = require('ti.paypal');
var u = Ti.Android != undefined ? 'dp' : 0;
var status = Ti.UI.createLabel({ top: 20 + u, height: 50 + u, color: '#333', text: 'Loading, please wait...' });
$.paypalWindow.add(status); var price = totalamount;
var invoiceitemslist = JSON.stringify(data);
var button; function addButtonToWindow() {
if (button) { $.paypalWindow.remove(button); button = null; }
button = Paypal.createPaypalButton({ width: 194 + u, height: 37 + u, buttonStyle: Paypal.BUTTON_194x37, top: 20 + u,
language: 'en_US',
appID: 'APP-80W284485P519543T',
paypalEnvironment: Paypal.PAYPAL_ENV_SANDBOX,
feePaidByReceiver: false,
enableShipping: false,
payment: {
paymentType: Paypal.PAYMENT_TYPE_BUSINESS,
subtotal: price,
tax: 0.00,
shipping: 0.00,
currency: 'USD',
recipient: 'thaibusiness#gmail.com',
customID: 'anythingYouWant',
invoiceItems:
[{"name":"Bajaj 200 mm Ultima PT01 Personal Fan","totalPrice":2997,"itemPrice":999,"itemCount":3},
],
ipnUrl: 'http://www.appcelerator.com/',
merchantName: 'EYMOBINS Insurance',
memo: 'For the insurance with EYMOBINS!'
}
});
button.addEventListener('paymentCancelled', function (e) {
alert('Payment cancelled. Please try again!');
addButtonToWindow();
});
button.addEventListener('paymentSuccess', function (e) {
alert('Payment successfull. Please get your Policy No.!'+" "+e.transactionID);
$.paypalWindow.remove(button);
//addButtonToWindow();
});
button.addEventListener('paymentError', function (e) {
alert('Payment Error. Please try again!');
addButtonToWindow();
});
button.addEventListener('buttonDisplayed', function () {
$.paypalWindow.remove(status);
//alert('Please pay '+Ti.App.totalcost+'$ with Paypal!')
});
button.addEventListener('buttonError', function () {
});
$.paypalWindow.add(button);
}
addButtonToWindow();
});
$.paypalWindow.open();
Please check the code and give me an idea to resolve the above issue.
EDIT:
Here I am facing one issue:
[{"name":"Bajaj 200 mm Ultima PT01 Personal Fan","totalPrice":999,"itemPrice":999,"itemCount":1},{"name":"Average2Excellent CBSE KG EVS MATHS ENG Educational CD ROMS","totalPrice":547,"itemPrice":547,"itemCount":1}]
Here the totalamount is 1546. Here I have printed the invoiceitems in the console, and I am getting the data like above.
So that I have given like:
invoiceItems:invoiceitems,
Like means am getting the issue (the amounts specified for item price, tax, and shipping do not add up to the total amount).
Same thing I have written the code like:
invoiceItems:[{"name":"Bajaj 200 mm Ultima PT01 Personal Fan","totalPrice":999,"itemPrice":999,"itemCount":1},{"name":"Average2Excellent CBSE KG EVS MATHS ENG Educational CD ROMS","totalPrice":547,"itemPrice":547,"itemCount":1}]
it's working perfectly.
It is not working dynamically when assigned the value. Can you please check the code and help?
EDIT:
If i have tried to run this code on android device, as am clicking the paypal button nothing happends. Why the login form is not open in the android device.
Why are you escaping the quotes in this code?
[{"name":"Bajaj 200 mm Ultima PT01 Personal Fan","totalPrice":2997,"itemPrice":999,"itemCount":3}
This is not valid JSON (or Javascript for that matter). Is this required by Paypal? I think it should look like this:
[{"name":"Bajaj 200 mm Ultima PT01 Personal Fan","totalPrice":2997,"itemPrice":999,"itemCount":3}
Edit:
I've had a closer look at your code sample. Can you confirm where totatamount is coming from? As the code sample stands it will be undefined, which would be consistent with the error message you have described. Can you confirm it is definitely the correct value IMMEDIATELY before you submit this data?
The ti.paypal spec has a nice code sample in the README file, which gives a good example of how to setup createPaypalButton. I would recommend looking at this if you haven't already.
button = Paypal.createPaypalButton({
// NOTE: height/width only determine the size of the view that the button is embedded in - the actual button size
// is determined by the buttonStyle property!
width: 194 + u, height: 37 + u,
buttonStyle: Paypal.BUTTON_194x37, // The style & size of the button
bottom: 50 + u,
language: 'en_US',
textStyle: Paypal.PAYPAL_TEXT_DONATE, // Causes the button's text to change from "Pay" to "Donate"
appID: '<<<YOUR APP ID HERE>>>', // The appID issued by Paypal for your application; for testing, feel free to delete this property entirely.
paypalEnvironment: Paypal.PAYPAL_ENV_SANDBOX, // Sandbox, None or Live
feePaidByReceiver: false, // This will only be applied when the transaction type is Personal
enableShipping: false, // Whether or not to select/send shipping information
advancedPayment: { // The payment itself
payments: [
{
isPrimary: true, // Mark this as the primary vendor; this marks this as a chain payment.
merchantName: 'Primary Vendor',
paymentType: Paypal.PAYMENT_TYPE_SERVICE, // The type of payment
paymentSubtype: Paypal.PAYMENT_SUBTYPE_DONATIONS, // The subtype of the payment; you must be authorized for this by Paypal!
subtotal: 13, // The total cost of the order, excluding tax and shipping
tax: 0,
shipping: 0,
recipient: '<<<YOUR RECIPIENT HERE>>>',
customID: 'anythingYouWant',
invoiceItems: [
{ name: 'Shoes', totalPrice: 8, itemPrice: 2, itemCount: 4 },
{ name: 'Hats', totalPrice: 2, itemPrice: 0.5, itemCount: 4 },
{ name: 'Coats', totalPrice: 3, itemPrice: 1, itemCount: 3 }
]
},
{
merchantName: 'Vendor 1',
paymentType: Paypal.PAYMENT_TYPE_SERVICE, // The type of payment
paymentSubtype: Paypal.PAYMENT_SUBTYPE_DONATIONS, // The subtype of the payment; you must be authorized for this by Paypal!
subtotal: 10, // The total cost of the order, excluding tax and shipping
tax: 0,
shipping: 0,
recipient: '<<<YOUR RECIPIENT HERE>>>',
customID: 'anythingYouWant',
invoiceItems: [
{ name: 'Shoes', totalPrice: 8, itemPrice: 2, itemCount: 4 },
{ name: 'Hats', totalPrice: 2, itemPrice: 0.5, itemCount: 4 }
]
},
{
merchantName: 'Vendor 2',
paymentType: Paypal.PAYMENT_TYPE_SERVICE, // The type of payment
paymentSubtype: Paypal.PAYMENT_SUBTYPE_DONATIONS, // The subtype of the payment; you must be authorized for this by Paypal!
subtotal: 3, // The total cost of the order, excluding tax and shipping
tax: 0,
shipping: 0,
recipient: '<<<YOUR RECIPIENT HERE>>>',
customID: 'anythingYouWant',
invoiceItems: [
{ name: 'Coats', totalPrice: 3, itemPrice: 1, itemCount: 3 }
]
}
],
ipnUrl: 'http://www.appcelerator.com/',
currency: 'USD',
memo: 'For the orphans and widows in the world!'
}
});

Categories