how to get list of retweeters using streaming api - twitter

Is there a way to get the list of retweeters ids using streaming api
REST api has "GET statuses/:id/retweeted_by/ids" for getting the list of retweeters
Streaming api has a "statuses/retweet", but is not a generally available resources.
So the idea is to use "statuses/filter" and filter based on tweet ids.
Thank you

In the results returned by the streaming API, retweeters (if any) are listed here:
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
Here's a page which shows the ids of retweeters for a stream filtered with a search for the word 'love' — make sure to use your Twitter username and password. Note that the APIs only return the first 100 retweeters.
<html><body>
<?php
echo(str_pad("START<br>",2048));
#ob_flush();
flush();
$opts = array(
'http'=>array(
'method' => "POST",
'content' => 'track=love',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create($opts);
$username = 'your_twitter_username';
$password = 'your_twitter_password';
while (1){
$instream = fopen('http://'.$username.':'.$password.'#stream.twitter.com/1/statuses/filter.json','r' ,false, $context);
while(! feof($instream)) {
if(! ($line = stream_get_line($instream, 20000, "\n"))) {
continue;
}else{
$tweet = json_decode($line);
$retweeters = array();
$retweeters = $tweet->{'retweeted_status'}->{'activities'}->{'retweeters'};
//We store the new post in the database, to be able to read it later
if (sizeof($retweeters) > 0) {
echo("<br><br>");
print_r($retweeters);
}
#ob_flush();
flush();
}
}
}
?>
</html></body>

Related

How to get the page Info.totalResults from the youtube api Search: list

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}
echo $json_data['pageInfo']['totalResults'];

Youtube api Where will write this code

Too bad my php knowledge.I'm using YouTube-api.Where will write this code: Retrieve Youtube Channel info for "Vanity" channel
If you are talking about this line :
GET https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}
You are simply making a get request, you can use file_get_contents to get the response for you :
$response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}");
Two notes :
You have to replace {YOUR_API_KEY} with the developer key. You can easily request one from youtube: http://code.google.com/apis/youtube/dashboard/
This is just an example in one line of code, I suggest you use a better approach for making this request like the following :
// Encode the parameters of the link
function encode_param($params) {
foreach ($params as $field => $value){
$encoded_params[] = $field . '=' . urlencode($value);
}
return $encoded_params;
}
// Get the response
function get_response($url) {
$response = file_get_contents($url);
// If error, send message back to the client
if ($response === false) {
exit("Couldn't get response from the api");
}
return $response;
}
$params = array(
"part" => "snippet,contentDetails,statistics",
"id" => "UC6ltI41W4P14NShIBHU8",
"key" => "-----------", // Your API key
);
$encoded_params = encode_param($params);
$request_url = "https://www.googleapis.com/youtube/v3/channels?".implode('&', $encoded_params);
$response = get_response($request_url);
//............

Youtube api v3 Get list of user's videos

With Youtube api v2, there's easy way to get videos. Just send a query like this:
http://gdata.youtube.com/feeds/mobile/videos?max-results=5&alt=rss&orderby=published&author=OneDirectionVEVO
The Youtube api v2 also has an interactive demo page for building query:
http://gdata.youtube.com/demo/index.html
With Youtube api v3, I don't know the corresponding way. Please point me the way with api v3.
Thank you!
The channels#list method will return a JSON with some information about the channel, including the playlist ID for the "uploads" playlist:
https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=OneDirectionVEVO&key={YOUR_API_KEY}
With the playlist ID you can get the videos with the playlistItems#list method:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key={YOUR_API_KEY}
You can test those at the end of the documentation pages.
This should do it. This code just gets and outputs the title but you can get any details you want
// Get Uploads Playlist
$.get(
"https://www.googleapis.com/youtube/v3/channels",{
part : 'contentDetails',
forUsername : 'USER_CHANNEL_NAME',
key: 'YOUR_API_KEY'},
function(data) {
$.each( data.items, function( i, item ) {
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
});
}
);
//Get Videos
function getVids(pid){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part : 'snippet',
maxResults : 20,
playlistId : pid,
key: 'YOUR_API_KEY'},
function(data) {
var results;
$.each( data.items, function( i, item ) {
results = '<li>'+ item.snippet.title +'</li>';
$('#results').append(results);
});
}
);
}
<!--In your HTML -->
<ul id="results"></ul>
If quota cost is a consideration, it may be beneficial to follow this simple algorithm.
First grab the data from https://www.youtube.com/feeds/videos.xml?channel_id=... This is a simple XML feed which will give you the video ID's, but you cannot specify further 'parts' (stats, etc).
Using the video ID's from that list, do a query on the /videos API endpoint which allows for a comma-separated-list of video ID's which should only result in 1 quota cost, plus 0-2 for any additional part parameters. As #chrismacp points out, using the /search endpoint is simpler but has a quota cost of 100, which can add up quickly.
There is a resource consideration here (cpu, memory, etc) as you are making a second call, but I believe in many scenarios this can be a useful method.
Things have changed alot in V3 of the API. Here is a video that walks you through the v3 API calls needed to get a list of the videos uploaded in a given channel, with live demos using the API Explorer.
YouTube Developers Live: Getting a Channel's Uploads in v3 - https://www.youtube.com/watch?v=RjUlmco7v2M
In case it helps anyone here this is what I discovered and so far seems to be working well for me. I am authenticating the member via OAuth 2.0 prior to making this request, which will give me the authenticated members videos. As always, your personal mileage may vary :D
curl https://www.googleapis.com/youtube/v3/search -G \
-d part=snippet \
-d forMine=true \
-d type=video \
-d order=date \
-d access_token={AUTHENTICATED_ACCESS_TOKEN}
The equivalent of the request you posted is actually a search in the 3.0 api, not a playlist request. It's easier too to do it that way. You do need to excange the username for a channel ID though.
ex. GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUGhCVGZ0ZSpe5hJHWyiLwHA&key={YOUR_API_KEY}
Here is some code using the offical Google APIs Node library (https://github.com/google/google-api-nodejs-client)
const readJson = require("r-json");
const google = require('googleapis');
const Youtube = google.youtube('v3');
// DONT store your credentials in version control
const CREDENTIALS = readJson("/some/directory/credentials.json");
let user = "<youruser>";
let numberItems = 10;
let channelConfig = {
key: CREDENTIALS.youtube.API_KEY,
part: "contentDetails",
forUsername: user
};
Youtube.channels.list(channelConfig, function (error, data) {
if (error) {
console.log("Error fetching YouTube user video list", error);
return;
}
// Get the uploads playlist Id
let uploadsPlaylistId = data.items[0].contentDetails.relatedPlaylists.uploads;
let playlistConfig = {
part : 'snippet',
maxResults : size,
playlistId : uploadsPlaylistId,
key: CREDENTIALS.youtube.API_KEY
};
// Fetch items from upload playlist
Youtube.playlistItems.list(playlistConfig, function (error, data) {
if (error) {
console.log("Error fetching YouTube user video list", error);
}
doSomethingWithYourData(data.items);
});
});
An alternative method may be to get the playlists for the currently oauth authenticated user via: property mine=true
where the oauth access_token is retrieved following authentification:
https://developers.google.com/youtube/v3/guides/authentication
https://www.googleapis.com/youtube/v3/playlists?part=id&mine=true&access_token=ya29.0gC7xyzxyzxyz
Please don't use playlistitems.list if you want to get the videos of playlist with more then 300 videos. You can try it live in google link "https://developers.google.com/youtube/v3/docs/playlistItems/list" in "Try it" section. It returns undefined.
I have used in my project also. It returns undefined only.
In PHP:
I used pageToken attribute to go to all page of playlist.I hope it can help you.
//step 1: get playlist id
$response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?key={$api_key}&forUsername={$channelName}&part=contentDetails");
$searchResponse = json_decode($response,true);
$data = $searchResponse['items'];
$pid = $data[0]['contentDetails']['relatedPlaylists']['uploads'];
//step 2: get all videos in playlist
$nextPageToken = '';
while(!is_null($nextPageToken)) {
$request = "https://www.googleapis.com/youtube/v3/playlistItems?key={$api_key}&playlistId={$pid}&part=snippet&maxResults=50&pageToken=$nextPageToken";
$response = file_get_contents($request);
$videos = json_decode($response,true);
//get info each video here...
//go next page
$nextPageToken = $videos['nextPageToken'];
}
In node.js, it can be achieved with following code.
Requires authKey and channelId as options object parameter.
cb callback is called after data is fetched.
async function fetchChannelInfo(options) {
const channelUrl = `https://www.googleapis.com/youtube/v3/channels?part=contentDetails,statistics&id=${
options.channelId
}&key=${options.authKey}`;
const channelData = await axios.get(channelUrl);
return channelData.data.items[0];
}
function fetch(options, cb) {
fetchChannelInfo(options).then((channelData) => {
options.playlistId = channelData.contentDetails.relatedPlaylists.uploads;
const paylistUrl = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${
options.playlistId
}&key=${options.authKey}`;
axios
.get(paylistUrl)
.then((response) => {
const payloadData = ;
const videoList = [];
response.data.items.forEach((video) => {
videoList.push({
publishedAt: video.snippet.publishedAt,
title: video.snippet.title,
thumbnails: thumbnails,
videoId: video.snippet.resourceId.videoId,
});
});
cb(null, videoList);
})
.catch((err) => {
cb(err, null);
});
});
}
Note: axios is used for RESTful requests. To install
npm install axios
$.get(
"https://www.googleapis.com/youtube/v3/channels",{
part: 'snippet,contentDetails,statistics,brandingSettings',
id: viewid,
key: api},
function(data){
$.each(data.items, function(i, item){
channelId = item.id;
pvideo = item.contentDetails.relatedPlaylists.uploads;
uploads(pvideo);
});
});
Uploads Function can be
function uploads(pvideo){
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",{
part: 'snippet',
maxResults:12,
playlistId:pvideo,
key: api},
function(data){
$.each(data.items, function(i, item){
videoTitle = item.snippet.title;
videoId = item.id;
description = item.snippet.description;
thumb = item.snippet.thumbnails.high.url;
channelTitle = item.snippet.channelTitle;
videoDate = item.snippet.publishedAt;
Catagoryid = item.snippet.categoryId;
cID = item.snippet.channelId;
})
}
);
}
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$(".form-control").click(function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 20,
order: "viewCount",
publishedAfter: "2017-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId ,"descrip":item.snippet.description ,"date":item.snippet.publishedAt ,"channel":item.snippet.channelTitle ,"kind":item.id.kind ,"lan":item.id.etag}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("YOUR API KEY .... USE YOUR KEY");
gapi.client.load("youtube", "v3", function() {
// yt api is ready
});
}
Check the Complete code here https://thecodingshow.blogspot.com/2018/12/youtube-search-api-website.html

Is there a field for knowing if the youtube channel is verified from the Youtube API?

I am using the Youtube data API and I needed to know if there is any way of finding that the youtube channel is a Verified one.
just ran into this today, and while the channelBranding of the V3 youtube API looks promising, I couldn't get it to return if the account/channel user id was verified or not
so I threw up a pretty lame php script that uses DOM model searching to examine the html directly.
to return true if the following element is present.
<a href="//support.google.com/youtube/bin/answer.py?answer=3046484&hl=en" class="qualified-channel-title-badge" target="_blank">
As of today (9/8/2014) a verified user will return true..
<?php
function isVerified($youtubeUser)
{
$youtubeUser = trim($youtubeUser);
$url = '\''."https://www.youtube.com/user/".$youtubeUser.'\'';
$url = "https://www.youtube.com/user/".$youtubeUser ;
$Verified = false;
echo "<BR>looking at $url ";
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument;
#$dom->loadHTML($html);
foreach ( $dom->getElementsByTagName('a') as $link ) {
$myVar = $link->getAttribute('class');
$search = "qualified-channel-title-badge";
$found=false;
$found = strpos($myVar, $search);
if ( $found !== false) {
$Verified = true; //echo "<BR><font color=green>TRUE</font>";
} else {
$Verified = false; //echo "<BR><font color=red>FALSE</font>";
}
}
if ( $Verified ) {
return true;
} else {
return false;
}
}
?>
Bye for now!
RE: mpgn's solution, note that there's a distinction between whether the G+ account is Verified and whether one or more of the accounts YouTube channels are Verified. It's possible for an account to have more than one channel, and each of those channels are verified independently, and for channels to be unverified even though the associated G+ account is verified.
As #Paul Blakely suggests, the current best way to do this is to check the status.longUploadStatus flag, per https://developers.google.com/youtube/v3/docs/channels
As of November, 2022, the YouTube Data API provides no method for determining whether or not a given YouTube channel is or is not verified. Instead, the current approach that yields reliable results is to scrape the channel, and parse a bit of JSON, and search the resulting structure.
We'll start by loading the server response for a given channel. Below I have a channel ID hard-coded in as the id variable:
const id = 'UCFNTTISby1c_H-rm5Ww5rZg';
const response = await needle( 'get', `https://www.youtube.com/channel/${id}` );
With our response object, we should now proceed to check that a 200 OK was received, indicating there were no issues retrieving the page data, and that it is safe to proceed:
if ( response.statusCode === 200 ) {
// proceed to search for verification status
}
Within the block following the condition is where we can start to retrieve the initial data for the YouTube page. When serving a channel page, YouTube will also serve initial data for the channel itself, presumably to speed up delivery among other reasons.
We'll look for this initial data, parse it as JSON, and sift through the results:
const json = response.body.match( /ytInitialData = (.*?);<\/script>/ )[1];
const parsed = JSON.parse( json );
With our data parsed, we'll turn our attention now to one piece of the resulting structure, the c4TabbedHeaderRenderer property. This is where badges for the page (such as a verification badge) are stored. We'll also define a verifiedLabel, to explain what it is we're seeking:
const header = parsed.header.c4TabbedHeaderRenderer;
const verifiedLabel = 'BADGE_STYLE_TYPE_VERIFIED';
Lastly we need to confirm that badges is an array (it may not be, in the event the channel has no badges to enumerate), and follow that up with a check for our verifiedLabel badge:
const verified = Array.isArray(header.badges) && header.badges.some( badge => {
return badge.metadataBadgeRenderer.style === verifiedLabel
});
At this point, verified is either true (if the channel is verified), or false. I hope this helps!
On verified channels, the class "has-badge" is present.
Work in 2018:
<?php
$key = 'has-badge';
$channel = file_get_contents('https://www.youtube.com/...');
if( stripos($channel, $key) !== FALSE )
echo "Verified";
else
echo "Not Verified";
?>
If may be possible to check infer the verified status of a youtube channel via the status.longUploadsStatus flag being either allowed or eligible, as currently this feature requires the associated youtube account to be verified.
source : https://developers.google.com/youtube/v3/docs/channels

Get LIKED youtube videos via API

I know how to get the count of 'liked' videos using the YouTube API, but I want to get a list of those videos.
After reading the docs, I think it can be done by getting the 'liked' playlist, but I do not know exactly how.
Can I get the 'liked' video list through the Javascript API?
If you're using v3 of the API, then you can get your liked video list. First, do a call to your channels feed, like this:
https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true&key={YOUR_API_KEY}
Then, in the response, you'll have a list of related playlists -- one will be keyed "likes." Take that playlist ID and request its items feed:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={PLAYLIST_ID}&key={YOUR_API_KEY}
If you don't use v3 of the API, you probably won't have a lot of success in getting the liked videos.
As of 2020, the /videos endpoint lets you filter directly for liked videos, e.g.:
GET https://www.googleapis.com/youtube/v3/videos?myRating=like&part=snippet
Authorization: Bearer <oauth token>
If you pass the following arguments to playlistItems.list, you can get the liked videos' playlist associated with the authorized acccount.
auth: "your_auth_key"
playlistId: "LL"
Here's a code snippet from the script I ran to get the liked videos in a text file.
Note: I used the helper code provided in the YouTube API Documentation to get the authkey and pass it to my function.
// get all the liked videos by a channel
async function get_liked_playlist(authkey){
fs.writeFile("./output/"+"all_liked_videos"+".txt", "\n"+time_stamp, { flag: 'a+' }, e => console.log(e) );
let nextPageToken_ = null;
let text__ = "";
let i = 0;
do {
await API.playlistItems.list({
key: process.env.API_KEY,
auth: authkey,
part: "snippet",
maxResults: 50, // 50 is the max value
playlistId: "LL",
pageToken: nextPageToken_
})
.then(res => {
let results = res.data.items;
nextPageToken_ = res.data.nextPageToken;
results.forEach(item => {
// console.log(`Title: ${item.snippet.title}\tURL: https://youtu.be/${item.snippet.resourceId.videoId}`)
i++;
text__ += "\nTitle: "+item.snippet.title+"\tURL: https://youtu.be/"+item.snippet.resourceId.videoId;
});
console.log("items done: "+i+"\tnextPageToken: "+nextPageToken_);
})
.then( fs.writeFile("./output/"+"all_liked_videos"+".txt", text__ , { flag: 'a+' }, e => { if(e) console.log("error with fs\t"+e); }) )
.then( text__ = "" )
.catch( e => console.log("error here\t" + e) )
} while (nextPageToken_ != null)
if(text__.length>1) fs.writeFile("./output/"+"all_liked_videos"+".txt", text__ , { flag: 'a+' }, e => { if(e) console.log("error with fs\t"+e); });
}

Resources