Retrieving information using Twitch API - javascript

So with the code below I am able to get the information shown below e.g. streamTitle.
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName)), true);
if ($json_array['stream'] != null) {
$currentGame = $json_array['stream']['channel']['game'];
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$viewers = $json_array['stream']['viewers'];
}
But what I want to do is to get what comes after self: e.g.(https://api.twitch.tv/kraken/streams/woohaa666) of an API response like the one below which has a specified game and limit, but I'm not sure how to do so. I tried something similar to the code above $channelurlAPI = $json_array['streams']['self'], but it displays nothing.
https://api.twitch.tv/kraken/streams?game=Diablo+III&limit=1

Im not sure how much this will help you but i was doing work with the twitch API a few months ago I found it very hard but was able to get game searches working and to bring in streams
hope it helps here is the code that i used
//Twitch Streams //Ref: https://github.com/justintv/Twitch-API/blob/master/embedding.md
function getTwitch(title){
$.getJSON("https://api.twitch.tv/kraken/search/streams?q="+title+"&limit=20&type=top&callback=?", function (data) {
var temp = "";
$.each(data.streams.slice(0,5), function (index, item) {
temp = temp + "<a target='frame1' href='http://www.twitch.tv/widgets/live_embed_player.swf?channel=" + item.channel.name + "'><button>"+item.channel.display_name+"</button></a><br />";
});
$("#StreamList").html(temp);
});
}
Here is a sample jsfiddle i build using the original api code that u my use as a jumping of point aswell but the code above is the final code I used
http://jsfiddle.net/F4tsM/10/

You should try
$json_array['_links']['self']

Related

Salesforce, Locker: Cannot "createObjectURL" using a unsecure [object File]

I'm having some problem with a lightning component that was done by other developer that left the company, users are telling me that the tool was working perfectly 1 month ago but i don't have any idea of what is happening then
The error is :
This page has an error. You might just need to refresh it. Action
failed: c:EMB_CCW_Panel$controller$onPickFile [Locker: Cannot
"createObjectURL" using a unsecure [object File]!] Failing descriptor:
{c:EMB_CCW_Panel$controller$onPickFile}
and the javascript method is this one
onPickFile : function(component, event, helper) {
var catalog = component.get("v.catalogWrapper");
var brandsList = component.get("v.brandsList");
console.log("onPickFile", catalog);
var file = event.target.files[0];
var fileURL = URL.createObjectURL(file);
var req = new XMLHttpRequest();
req.open('GET', fileURL);
req.onload = function() {
URL.revokeObjectURL(fileURL);
component.set("v.catalogWrapper",
helper.fillCatalogWithXMLData(catalog, helper.extractSlideNotesFromODTContentXML(this.responseXML), brandsList));
};
req.onerror = function() {
URL.revokeObjectURL(fileURL);
console.log('Error loading XML file.');
};
req.send();
},
and the helper methods,
extractSlideNotesFromODTContentXML : function(xmlDoc){
var output = [];
var slides = xmlDoc.getElementsByTagName("draw:page");
for(var s=0;s<slides.length;s++){
var notes = slides[s].getElementsByTagName("presentation:notes")[0].getElementsByTagName("draw:frame")[0].getElementsByTagName("draw:text-box")[0].getElementsByTagName("text:p");
var slideNotesList = [];
for(var i =0;i<notes.length;i++){
slideNotesList.push(notes[i].textContent);
}
output.push(slideNotesList);
}
return output;
},
fillCatalogWithXMLData : function(catalog, slidesList, brandsList){
try {
var referenceRegEX = /^(\d){9}/;
for(var i=0;i<slidesList.length;i++){
catalog.slides.splice(i, 0, this.generateSlideObject(i+1));
for(var j=0;j<slidesList[i].length;j++){
var wholeLine = slidesList[i][j];
var firstWord = wholeLine.split(" ")[0].toUpperCase();
console.log('firstWord', firstWord)
// Lines that begin with a number are references (SAP Id code). Consider the rest brand names:
if(referenceRegEX.test(firstWord) && firstWord.length == 9){
catalog.slides[i].referencesText += wholeLine+"\n";
}else{
// That's not a reference, check if it's a brand:
// 1.- Check if the whole line is a brand (removing leading and trailing spaces)
if(brandsList.includes(wholeLine.trim())){
// Found brand:
catalog.slides[i].brandsText += wholeLine + "\n";
}else{
// Not found, not recognized:
catalog.slides[i].unrecognizedText += wholeLine + "\n";
}
}
}
}
component.set("v.catalogWrapper", catalog);
} catch(err) {
}
return catalog;
}
anyone can't help me or tell me how can i fixe it !
thanks
If it used to work 1 month ago it's probably something Salesforce patched in Summer release. No idea what (if anything) is unsecure in your code but sounds like you're hit by Lightning Locker Service. Do you get same result in different browsers?
See if it works if you knock back the API version of component to version 39. It's a hack but might be a temp relief while you figure out what to do.
This suggests File is supported all right: https://developer.salesforce.com/docs/component-library/tools/locker-service-viewer
Maybe you need to read the file's content different way, maybe you need to give up on parsing it with JavaScript and push to server-side apex? I don't know what your functionality is.
If you go to setup -> lightning components -> debug mode and enable for yourself it might help a bit. You will see more human-friendly code generated in browser's developer tools, debugging might be simpler. Lesson learned would be to pay more attention to release preview windows (from ~September 12th we can preview Winter'21 release, SF should publish blog post about it in 1-2 weeks)
This looks promising: https://salesforce.stackexchange.com/a/245232/799
Maybe your code needs proper Aura accessors, event.getSource().get("v.files")[0] instead of event.target.files[0]. You really would have to debug it and experiment in browser's console, see what sticks.

Flask Javascript Json Data - Undefined

I did have this code working a few years ago and have recently come back to it, i have a javascript refreshing data on a web page. Im calling the server using json and receiving back what i think is ok.
My python database code, which seems to work fine.
cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
return jsonify(cur.fetchall())
Received Json
[["BoilerRoom",24.94],["Cylinder1",49.94],["Cylinder2",42.38],["Cylinder3",41.88],["Sensor1",85],["SolidFuelFlow",59],["SolidFuelReturn",41.62]]
Im trying to get the number thats associated with Cylinder2 = 42.38
My js code that worked previously is as follows
<script type=text/javascript>
function get_temps() {
$.getJSON("_status",
function (data) {
$('#CylTop').text(data.Cylinder1 + "°")
$('#CylMid').text(data.Cylinder2 + "°")
$('#CylBot').text(data.Cylinder3 + "°")
$('#Solid_flow').text(data.SolidFuelFlow)
$('#Solid_return').text(data.SolidFuelReturn)
$('#BRoom').text(data.BoilerRoom);
console.log(data)
console.log(data.Cylinder1)
}
);
}
setInterval('get_temps()', 5000);
</script>
The console shows the (data) fine in the browser, its when i try and show anything else. ' console.log(data.Cylinder1) ' that shows undefined.
Im a newbie so im assuming some indexing needs to happen as its a array but im a bit lost.
Any guidance will be greatly appreciated.
Many Thanks
C Dabbs
You seem to be accessing the properties in the data as an object. As per the response, it is an array inside an array. So you will have to flatten it before accessing it the way you have it.
function get_temps() {
$.getJSON("_status",
function(data) {
let flattendData = data.reduce(function(acc, item) {
return Object.assign({}, acc, {
[item[0]]: item[1]
});
}, {});
$('#CylTop').text(flattendData.Cylinder1 + "°")
$('#CylMid').text(flattendData.Cylinder2 + "°")
$('#CylBot').text(flattendData.Cylinder3 + "°")
$('#Solid_flow').text(flattendData.SolidFuelFlow)
$('#Solid_return').text(flattendData.SolidFuelReturn)
$('#BRoom').text(flattendData.BoilerRoom);
console.log(flattendData)
console.log(flattendData.Cylinder1)
}
);
}

javascript How to check the same data is available for the second time

I have a tricky requirement which im not able to fix.
I have a button and if i click on that button, Im getting below data from a REST web service ..
{
"results": [{
"Reqdate": "\/Date(1520899200000)\/",
"Tooltip": "13.03.2018 Blood Donation Approved ",
"Legendid": "GROUP_LEVEL1"
},{
"Reqdate": "\/Date(1523836800000)\/",
"Tooltip": "16.04.2018 Privilege Leave Sent ",
"Legendid": "BADVALUE_LIGHT",
},{
"Reqdate": "\/Date(1524528000000)\/",
"Tooltip": "24.04.2018 Privilege Leave Sent ",
"Legendid": "BADVALUE_LIGHT",
}]
}
If im getting the above data for the first time. Im going to display one section. Now again if i click on the same button, If i get the same data in the service then i have to hide the section. But im not able to check the same data for the second time.
Im trying to fix this issue by storing the data in a variable like below..
var firstTimeResults = data.results;
Now im not able to check if the same data is coming for the second time. Actually im not able to produce the sample code too. Im sorry for that
Can someone please help me to fix this issue.
I am not fully understand your problem but I think you can store your data as JSON and check if the same data is return from the second time onwards?
Code example
// Variable declaration
var firstTimeResults = null;
// When data return
var dataJson = JSON.stringify(data.results);
if (firstTimeResults === null) {
firstTimeResults = dataJson;
}
else {
// check to see if the data is the same as the firstTimeResults
var isSame = firstTimeResults === dataJson;
if (isSame) {
// Same
} else {
// Not the same
}
}
You can simply try with Lodash library.
It makes JavaScript easier to work with arrays, numbers, objects, strings, etc.
https://lodash.com/
var firstResult = null;
var secondResult;
var showSection;
function getData() {
// here goes your API request to get the data
};
function onButtonClick() {
this.getData().then(function(value) {
if !(firstResult) {
firstResult = value;
showSection = true;
return;
}
secondResult = value;
if (_.isEqual(firstResult, secondResult)) {
showSection = false;
}
})
};
Hope this will be helpful to you!

Google Script not Appending Spreadsheet

I'm trying to write a little script to make my coworkers and mine lives easier. I am trying to append lines to a spreadsheet based on information entered into a custom form. The code posted below just the doPost block which should be appending the google spreadsheet.
function doPost(form) {
var PN = form.PartNumber;
var REV = form.Revision;
var DATE = form.RevisionDate;
var DESC = form.Description;
var NOTE = form.PartNotes;
var URL = form.myFile.getURL();
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
I am unsure why it isn't writing to the spreadsheet but it isn't throwing me any errors. If you can offer any insight as to what is wrong I would greatly appreciate it; there are many guides online but most seem to be based on deprecated functions/code/etc.
Thanks for your time.
Instead of using doPost, set up a "On form submit" trigger.
You need to get the namedValues to be able to pull specific values and take the first output.
Also, it should be "getSheetByName('Uploads')" .
As pointed out in the previous answer, it is unclear what you are trying to achieve by "form.myFile.getURL();" If you want to get the form url you might as well create it as a string, as it always stays the same.
Here is a working example of your code:
function doPost(form) {
var formResponses = form.namedValues;
var PN = formResponses.PartNumber[0];
var REV = formResponses.Revision[0];
var DATE = formResponses.RevisionDate[0];
var DESC = formResponses.Description[0];
var NOTE = formResponses.PartNotes[0];
//var URL = form.myFile.getURL(); //Not sure what you are tyring to get here as form URL will always be the same.
var URL = "Your form's url"; //You can put the form url in here so it will be pushed in to every row.
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetByName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
The form fields are nested in a "parameter" property in the doPost parameter.
So, you should access them using:
function doPost(form) {
var actualForm = form.parameter;
var PN = actualForm.PartNumber;
//etc
To double check all parameters your receiving and their names, you could append to your sheet everything stringfied, like this:
sheet.appendRow([JSON.stringify(form)]);
--edit
This form.myFile.getURL() also looks odd. I guess another good debugging trick you could do is to wrap everything in a try-catch and email yourself any errors you get. For example:
function doPost(form) {
try {
//all your code
} catch(err) {
MailApp.sendMail('yourself#etc', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
On form submit
onFormSubmit works. "doPost" looks wrong.
Simple example:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
Full example - Scroll down to the code http://www.labnol.org/internet/google-docs-email-form/20884/ (Note: example sends email)
Trigger docs: https://developers.google.com/apps-script/guides/triggers/events
Notes: I think the problem is doPost, Does it work with google Forms? Never seen it used with google forms.
First and foremost, thank you everyone who has responded with information thus far. None of the solutions posted here worked for my particular implementation (my implementation is probably to blame, it is very crude), but they definitely set me down the path to a working version of my form which we now lightly use. I have posted some of the code below:
function sheetFill(form, link) {
try {
var formResponses = form.namedValues;
var toForm = [0,0,0,0,0,0,0];
for (i=0;i < form.PartNumber.length;i++){
toForm[0] = toForm[0]+form.PartNumber[i];
}
... (several for loops later)
var d = new Date();
var ss = SpreadsheetApp.openById("IDHERE");
var sheet = ss.getCurrentSheet;
ss.appendRow([toForm[0], toForm[1], toForm[2], toForm[3], toForm[4], toForm[5], toForm[6], link, d]);
} catch(err) {
MailApp.sendEmail('EMAIL', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
It is not very versatile or robust and isn't elegant, but it is a starting point.

Nested getJson() & PHP PDO

I have looked at other questions and answers regarding this, but can't seem to wrap my head around it...
I have a javascript function:
function getStates(theDiv){
var stateGroupData;
var stateData;
var theGHtml = "";
var theHtml = "<h4>MyPage</h4>";
theHtml = theHtml+"<h5>select a state...</h5>";
$.getJSON("getStateGroups.php", function(data) {
stateGroupData = data;
theHtml = theHtml+"<ul>";
$.each(stateGroupData, function(i,jsonData) {
theHtml = theHtml+"<li><a href='#"+jsonData.groupName+"'>"+jsonData.groupID+"</a></li><br/>";
var theSQL = "getStates.php?gid="+jsonData.groupName;
theGHtml = theGHtml+"<div id='"+jsonData.groupName+"'>";
$.getJSON(theSQL, function(data2) {
stateData = data2;
$.each(stateData, function(i,jsonData2) {
alert(jsonData2.stateName);
theGHtml = theGHtml+"<span sname='"+jsonData2.stateName+"' lat='"+jsonData2.centerLat+"' lon='"+jsonData2.centerLon+"' zom='"+jsonData2.zoom+"'>"+jsonData2.stateName+"</span> ";
});
});
theGHtml = theGHtml+"</div>";
});
theHtml = theHtml+"</ul>";
});
theDiv.html = theHtml+theGHtml;
}
The second (ie. nested) getJson does not return any thing... Both PHP files just use PDO to request data from the SAME table. I run the SQL in each file without any issues, so the SQL seems OK.
Is this an sync v. async issue with the calls to getJson?
Is this an sync v. async issue with
the calls to getJson?
Probably. I think this is your problem:
stateData = data2;
Try changing that to:
var stateData = data2;
The first one sets a global variable. The second one sets a variable that is local to that function.
You might benefit from refactoring this whole process such that you only need to make one AJAX call. It looked like you were pulling individual people associated with a group. You'd get better performance on the server from a single script which can, when needed, return people associated with the group but otherwise just returns the group.
Remember, every AJAX call is another hit to your server.

Categories

Resources