Llevo años haciendo blogs como afición ( ojala fuera como profesión, pero no, no da dinero para eso :) ) y uno de los problemas que siempre he tenido es el de ir mirando las visitas de los blogs uno a uno para llevar el control del tráfico. Si tienes dos blogs no es un problema pero si tienes 20 ( o más ) puede ser realmente tedioso.
Es por ello que he montado un script que se conecta a la API de Blogger saca la información de tus blogs y te dice cuantas visitas has tenido en cada uno de ellos. El resultado lo da en forma de web, de este estilo:
Es un script relativamente sencillo y al que le podéis sacar mucho partido, pero si no tenéis experiencia en GAS os recomiendo que primero os miréis este link:
http://googleappscriptsweb.blogspot.com.es/2015/03/como-crear-una-web-dinamica-con-google.html
Os dejo el código:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table.table1{
font-family: "Trebuchet MS", sans-serif;
font-size: 16px;
font-weight: bold;
line-height: 1.4em;
font-style: normal;
border-collapse:separate;
}
.table1 thead th
{
padding:15px;
color:#fff;
text-shadow:1px 1px 1px #568F23;
border:1px solid #93CE37;
border-bottom:3px solid #9ED929;
background-color:#9DD929;
background:-webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.02, rgb(123,192,67)),
color-stop(0.51, rgb(139,198,66)),
color-stop(0.87, rgb(158,217,41))
);
background: -moz-linear-gradient(
center bottom,
rgb(123,192,67) 2%,
rgb(139,198,66) 51%,
rgb(158,217,41) 87%
);
-webkit-border-top-left-radius:5px;
-webkit-border-top-right-radius:5px;
-moz-border-radius:5px 5px 0px 0px;
border-top-left-radius:5px;
border-top-right-radius:5px;
}
.table1 thead th:empty
{
background:transparent;
border:none;
}
.table1 tbody th{
color:#fff;
text-shadow:1px 1px 1px #568F23;
background-color:#9DD929;
border:1px solid #93CE37;
border-right:3px solid #9ED929;
padding:0px 10px;
background:-webkit-gradient(
linear,
left bottom,
right top,
color-stop(0.02, rgb(158,217,41)),
color-stop(0.51, rgb(139,198,66)),
color-stop(0.87, rgb(123,192,67))
);
background: -moz-linear-gradient(
left bottom,
rgb(158,217,41) 2%,
rgb(139,198,66) 51%,
rgb(123,192,67) 87%
);
-moz-border-radius:5px 0px 0px 5px;
-webkit-border-top-left-radius:5px;
-webkit-border-bottom-left-radius:5px;
border-top-left-radius:5px;
border-bottom-left-radius:5px;
}
.table1 tfoot td{
color: #9CD009;
font-size:32px;
text-align:center;
padding:10px 0px;
text-shadow:1px 1px 1px #444;
}
.table1 tfoot th{
color:#666;
}
.table1 tbody td{
padding:1px;
text-align:center;
background-color:#DEF3CA;
border: 2px solid #E7EFE0;
-moz-border-radius:2px;
-webkit-border-radius:2px;
border-radius:2px;
color:#666;
text-shadow:1px 1px 1px #fff;
}
.table1 tbody span.check::before{
content : url(../images/check0.png)
}
</style>
<script>
function Response(string)
{
document.getElementsByName("ejemplo")[0].innerHTML = string;
}
function InitWeb()
{
google.script.run.withSuccessHandler(Response).Init();
}
</script>
</head>
<body>
<script>
InitWeb();
</script>
<div name='ejemplo'>
<p> Loading.... wait</p>
</div>
</body>
</html>
codigo.gs
//Para obtener las credenciales: https://developers.google.com/blogger/docs/3.0/using#auth
var CLIENT_ID = 'TU_CLIENTE';
var CLIENT_SECRET = 'TU_CLAVE';
function getService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('blogger')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
// this is blogger read only scope for write access is:
// https://www.googleapis.com/auth/blogger
.setScope('https://www.googleapis.com/auth/blogger')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var bloggerService = getService();
var isAuthorized = bloggerService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
var Data;
function GetViewsOfBlog( id , name , blog )
{
var api_all = "https://www.googleapis.com/blogger/v3/blogs/" + id + "/pageviews?range=all" ;
var api_month = "https://www.googleapis.com/blogger/v3/blogs/" + id + "/pageviews?range=30DAYS" ;
var api_week = "https://www.googleapis.com/blogger/v3/blogs/" + id + "/pageviews?range=7DAYS" ;
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true ,
};
//Histórico
var response = UrlFetchApp.fetch(api_all, options);
var json = JSON.parse(response.getContentText());
for (var i in json.counts)
{
blog.push(json.counts[i].count);
}
//Mensual
var response = UrlFetchApp.fetch(api_month, options);
var json = JSON.parse(response.getContentText());
for (var i in json.counts)
{
blog.push(json.counts[i].count);
}
//Semanal
var response = UrlFetchApp.fetch(api_week, options);
var json = JSON.parse(response.getContentText());
for (var i in json.counts)
{
blog.push(json.counts[i].count);
}
return blog;
}
// Modified from http://ctrlq.org/code/20068-blogger-api-with-google-apps-script
function bloggerAPI()
{
var string = "";
Data = new Array(); //Inicializamos la estructura que contiene toda la información
var Total = new Array(3);
Total[0] = 0;
Total[1] = 0;
Total[2] = 0;
var service = getService();
if (service.hasAccess()) {
var api = "https://www.googleapis.com/blogger/v3/users/self/blogs";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(api, options);
var string = "";
var json = JSON.parse(response.getContentText());
for (var i in json.items)
{
var blog = new Array();
blog.push(json.items[i].name);
blog.push(json.items[i].url);
blog = GetViewsOfBlog(json.items[i].id,json.items[i].name,blog);
Data.push(blog); //Para cada blog ponemos su info
}
Data.sort(function(a, b){return b[4] - a[4]});
string += "<table class=\"table1\">";
string += "<thead>";
string += "<tr>";
string += "<td> Blog </td >";
string += "<td> Histórico </td >";
string += "<td> Mes </td >";
string += "<td> Semana </td >";
string += "</tr>";
string += "</thead>";
for (var i in Data)
{
Total[0] += Math.round(Data[i][2]);
Total[1] += Math.round(Data[i][3]);
Total[2] += Math.round(Data[i][4]);
}
string += "<tbody>";
for (var i in Data)
{
string += "<tr>";
string += "<td> <a href=" + Data[i][1] +">" + Data[i][0] + "</a> </td>" ;
string += "<td>" + Data[i][2] + "(" + Math.round((Data[i][2]*100/Total[0])*100)/100 + "%) </td>" ;
string += "<td>" + Data[i][3] + "(" + Math.round((Data[i][3]*100/Total[1])*100)/100 + "%) </td>" ;
string += "<td>" + Data[i][4] + "(" + Math.round((Data[i][4]*100/Total[2])*100)/100 + "%) </td>" ;
string += "</tr>";
}
string += "<tr>";
string += "<td> TOTAL </td>" ;
string += "<td>" + Total[0] + "</td>" ;
string += "<td>" + Total[1] + "</td>" ;
string += "<td>" + Total[2] + "</td>" ;
string += "</tr>";
string += "</tbody>";
string += "</table>";
}
else
{
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
return string;
}
function Init()
{
return bloggerAPI();
}
//Retorna la página principal
function doGet()
{
return HtmlService.createHtmlOutputFromFile('index');
}
El tema credenciales puede ser puñetero, si os da problemas ponedme un comentario y os intentaré ayudar.
Ya me explicareis si os va bien o si os ha dado problemas
Nos vemos
NOTA: Tengo un versión mejorada de este código a la venta. Incluye mejoras en la velocidad, obtención de datos de adsense y la posibilidad de customizarlo como necesitéis: Aquí tenéis el
link