I need to get the latest tweets of specific user using javascript. I've found some script for that. Here is it:
<script>
$(document).ready(function(){
loadLatestTweet();
});
function loadLatestTweet(){
var numTweets = 1;
var _url = 'https://api.twitter.com/1/statuses/user_timeline/CypressNorth.json?callback=?&count='+numTweets+'&include_rts=1';
$.getJSON(_url,function(data){
for(var i = 0; i< data.length; i++){
var tweet = data[i].text;
var created = parseDate(data[i].created_at);
var createdDate = created.getDate()+'-'+(created.getMonth()+1)+'-'+created.getFullYear()+' at '+created.getHours()+':'+created.getMinutes();
tweet = tweet.parseURL().parseUsername().parseHashtag();
tweet += '<div class="tweeter-info"><div class="uppercase bold">#CypressNorth</div><div class="right">'+createdDate+'</div></div>'
$("body").append('<p>'+tweet+'</p>');
}
});
}
</script>
but i get an error, that says Status Code:401 Unauthorized. I've changed the version code to 1.1, but the same error. So, I want to know, how can I pass the application id or application key to this url. And more, is there any javascript lib which works with the newest twitter api. Thanks a lot
The quick answer to this is version 1.0 is no longer active and version 1.1 requires OAuth for almost every api endpoint url.
Related
I have a Google sheet that automatically changes the urls in cell A28 via another script. The "test()" script is called by the main script to be executed whenever the url changes. I used the code from another thread: Grab data from website HTML table and transfer to Google Sheets using App-Script.
I modified it a bit because what interested me was getting the table with the ID "pgl_basic" and actually the code works as I expected. The only problem is that, in an absolutely random way, sometimes this error is generated: "Cannot read properties of null [0]" and if I then restart the script everything is fine or it crashes before or after the url it has determined the error, therefore it is absolutely random and without an apparent correlation.
function test() {
var tableHtml = 0;
var sheet = SpreadsheetApp.getActive().getSheetByName("2023");
var url = sheet.getRange("A27").getValue();
var html = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getContentText().replace(/(\r\n|\n|\r|\t| )/gm,"");
var tableHtml = html.match(/<table\s.*?id="pgl_basic"[\s\S]*?<\/table>/)[0];
var trs = [...tableHtml.matchAll(/<tr[\s\S\w]+?<\/tr>/g)];
var data = [];
for (var i=0;i<trs.length;i++){
var tds = [...trs[i][0].matchAll(/<(td|th)[\s\S\w]+?<\/(td|th)>/g)];
var prov = [];
for (var j=0;j<tds.length;j++){
donnee=tds[j][0].match(/(?<=\>).*(?=\<\/)/g)[0];
prov.push(stripTags(donnee));
}
data.push(prov);
}
return(data);
}
function stripTags(body) {
var regex = /(<([^>]+)>)/ig;
return body.replace(regex,"");
}
Initially the line:
var tableHtml = 0;
It didn't exist in the original code and I added it thinking it was a tableHtml variable "cache" issue but that didn't fix my problems. Using the code of the aforementioned topic, however, there is no problem or error but that code fetches all the tables included in the website and since they are not all the same, I don't need it but I need that specific table with that specific ID. I also tried to use a simple 2 second delay (via Utilities.sleep) thinking it could be a connection loading problem but this doesn't seem to be the case, also because I repeat that the original code (even with much larger data) works without a hitch. What could be the solution? Thanks.
I have a Google Drive folder filled with many audio files, and I want my website to play one at random when a user clicks a button. I have the logic setup already, and it's working if I manually enter the google drive links into my array like this:
var fileArray = ["https://docs.google.com/uc?export=open&id=XXXXXXX", "https://docs.google.com/uc?export=open&id=XXXXXXXXX"];
The problem is I have hundreds of files, and I update the Drive often so I want it to update by itself. Thus where the Google Drive API comes in. Unfortunately, I have now found myself going from 1 line of code to many lines of code and being totally lost. I have an API_KEY & CLIENT_ID. The documentation at Drive API -> Javascript Quickstart has a "handleAuthClick" function, but I don't want the user to have to sign in as they will never be making changes to the Drive. I don't even see anywhere it enters the folder ID which I don't understand. People talking about javascript origins, redirect uris, google picker api. The documentation at Drive API -> files.get has cURL & http files, and I've also seen people talking about json files storing information like service account details. Is it possible to just keep everything in my javascript script? Here is an example of some code I've tried:
<script src="https://apis.google.com/js/client:platform.js"></script>
<script type="text/javascript">
var fileArray = [];
const API_KEY = 'XXXXX';
const CLIENT_ID = 'XXXXX';
const CLIENT_SECRET = 'XXXXXX';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
const { google } = require('googleapis');
const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
function getFileIDs() {
var folderId = 'XXXXXX';
let response;
try {
response = await gapi.client.drive.files.list({
'fileId': folderId,
'fields': 'files(id)',
});
for (var i = 0; i < files.length; i++){
var currentID = files[i].id;
var currentDriveLink = 'https://docs.google.com/uc?export=open&id=' + currentID;
fileArray.push(currentDriveLink);
}
}
}
</script>
I just want the minimum code to get to file.id, and then I can prepend the URL structure and push it to my array. Any thoughts are helpful thank you.
I am trying to download attachment using Gmail API and below is the code for the that
var Data = req.body;
var parts = Data.payload.parts;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part.filename && part.filename.length > 0) {
var attachId = part.body.attachmentId;
var request = gapi.client.gmail.users.messages.attachments.get({
'id': attachId,
'messageId': message.id,
'userId': userId
});
request.execute(function(attachment) {
callback(part.filename, part.mimeType, attachment);
});
}
}
I have used the link
Gmail API to get the Attachment and since it require autorization as mention so who to pass the refershToken,clientSecret,clientId,accessToken etc..or whether this is required first place.
Currently i am getting Gmail is not defined, i have installed gapi and included it as
var cs = require("coffee-script/register");
var gapi = require('gapi');`
I haven't used gapi inside of nodejs environment, but from my experience in using gapi library in chrome extensions - after loading gapi script you need to load gmail separatelly - something like this:
gapi.client.load('gmail', 'v1', callback);
And after that you can start using it. That's probably reason for getting "Gmail is not defined" error.
Additionally, you can always make API calls without using gapi library.
i have a problem with the Google API.
I want to put pictures of a public album (google+) in some background-image in js.
i am not really familiar with Json
var data = $.getJSON('https://plus.google.com/photos/ACCOUNT_ID/albums/ALBUM_ID');
function displayGallery(data){
var l = data.feed.entry.length;
for (var i = 0; i < l; i++) {
var item = data.feed.entry[i];
$('#m'+ i ).css("backround-image",data);
}
i saw a similar post : Using jQuery $.getJSON() with Google Picasa Data API
But it was hard to understand it (and excuse my english).
Thanks in advance for any help !
I didn't have time to continue this project, but i think i finally took the right direction. I pretty close to the result i want.
$(document).ready(function() {
console.log("hello world");
$.get('https://picasaweb.google.com/data/feed/api/user/userID/albumid/albuID', function(data){
var entries = data.getElementsByTagName('entry');
console.log(entries);
// var entry = entries[0];
for(var i =0; i< entries.length; i++){
console.log(entries[i]);
console.log($(entries[i].getElementsByTagName('content')[0]).attr("src"));
}
});
});
The only real problem is that there is a security on web browser that doesnt permit you to well acces to this infos . You need to desable web security
I'm trying to implement a JSON call to simulate AJAX on a certain page where an AJAX panel isn't a viable option.
I want call my .aspx page when a State is selected from a drop down and populate the Counties drop down.
in my State dropdown, I have this call:
onchange="jsonDropDownLoader('COUNTIES', this, 'Content2_DDLCounties')"
That call is on the page and the code is here:
function jsonDropDownLoader(sType, oParent, oChild) {
var lstrChild = document.getElementById(oChild);
var lstrFilter = ""
if (oParent.value > "") {
lstrFilter = oParent.value
}
lstrChild.options.length = 0;
if (oParent.value > "") {
var JSONobject = {};
var http_request = new XMLHttpRequest();
url = "/AltairWeb.NET/RS/jsonDropDownLoader.aspx?TYPE=" + sType + "&FILTER=" + lstrFilter
http_request.open("GET", url, false);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
JSONobject = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
var JSONarray = eval('(' + http_request.responseText + ')').data
for (var i = 0; i < JSONarray.length; ++i) {
var optn = document.createElement("OPTION");
optn.text = JSONarray[i].text;
optn.value = JSONarray[i].value;
lstrChild.options.add(optn);
}
}
}
It returns a string which I then use to populate the County drop down.
I'm getting data back, but it's not rendering on your QA server. Using the developer tools with IE8, I can see that I have a error on this line:
JSONobject = JSON.parse(http_request.responseText);
it says that JSON is not declared.
It says I also have a syntax error on this line:
var JSONarray = eval('(' + http_request.responseText + ')').data
This works perfectly on my development box. However, my development box has WinXP / IIS 5 on it, whereas, our QA server is a Win2008 server with IIS7.5. We have new development boxes coming, but until then, I'm stuck with the XP machine.
Since it works locally, it seems like it must be a security issue with either Windows or IIS on the QA server, possibly with the http_request call, but I can't find anything via google that has helped me figure this out.
I know I've seen posts that JSON.parse is not supported by IE prior to IE9, but this works perfectly in IE8 when I point to my dev server, but not when I point to the QA server, so it doesn't seem to be a browser issue.
Any ideas?
JSON.parse() is a function of your browser, not the server.
Are you sure the difference is the server ... and not your client browser???
You might also wish to consider using something like jQuery (which can both simplify your coding, and help mediate cross-browser issues like this). for example:
Parse JSON in JavaScript?
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
First, you are using a synchronous call (xhr.open('GET', url, false)) , and you are also using onreadystatechange . This is wrong. Choose one or the other.
https://developer.mozilla.org/en/xmlhttprequest
Next, check your browser support for JSON. See https://stackoverflow.com/a/891306/48082 .
If you are unsure, then use json2.js from json.org.
Finally, do not use eval. Use a proper JSON library.