Skip to content

Instantly share code, notes, and snippets.

@HugoDF
Last active July 6, 2020 01:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HugoDF/22b1ef7bb54d3b39e0c8ec404cca9532 to your computer and use it in GitHub Desktop.
Save HugoDF/22b1ef7bb54d3b39e0c8ec404cca9532 to your computer and use it in GitHub Desktop.
Simple Analytics -> Telegram with Netlify Functions and quickchart.io - used on codewithhugo.com

Getting started

JS dependencies

There's a package.json + lockfile missing, you probably want to use netlify-lambda (npm i --save netlify-lambda) to bundle your code.

Dependencies you need for the code to work:

  • axios - v0.18.x npm i --save axios
  • date-fns - v1.30.x `npm i --save date-fns

One-liner for depencies: yarn add axios date-fns netlify-lambda or npm install --save axios date-fns netlify-lambda.

Telegram Bot

Pre-requisite: Create a new Telegram bot by talking to @BotFather

Environment Variables

Environment variables you need and how to procure them:

  • TELEGRAM_TOKEN from @BotFather (probably)
  • TELEGRAM_CHAT_ID by hacking around with your new bot
    1. send it a message
    2. then ping the bot's "getUpdates" endpoint (I think, let me know if it isn't this and I'll update the instructions here).
  • SITE_URL your site URL as tracked in Simple Analytics

Deploy + test

Deploy on Netlify, curl $YOUR_DEPLOYMENT/.netlify/functions/sa-tg and you should get a Telegram message from your bot.

Going Further

Create 3-4 IFTTT hooks to ping the lambda $YOUR_DEPLOYMENT/.netlify/functions/sa-tg at certain times every day and at the end of the week.

Acknowledgments

The MIT License (MIT)
Copyright (c) 2019 Hugo Di Francesco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
import axios from 'axios';
import {startOfWeek, addDays, format} from 'date-fns';
import {sendMessage, sendPhoto} from './telegram';
const SITE_URL = process.env.SITE_URL || 'codewithhugo.com';
const SIMPLE_ANALYTICS_BASE_URL =
`https://simpleanalytics.io/${SITE_URL}.json`;
function weekStartDate(date) {
return startOfWeek(date, {weekStartsOn: 1});
}
const saFormat = date => format(date, 'YYYY-MM-DD');
async function getAnalyticsData(startDate, endDate) {
const start = saFormat(startDate);
const end = saFormat(endDate);
const res = await axios.get(
`${SIMPLE_ANALYTICS_BASE_URL}?start=${start}&end=${end}`
);
return res.data && res.data.visits;
}
async function makeReport() {
const today = new Date();
const twoWeeksAgo = addDays(today, -14);
const data = await getAnalyticsData(twoWeeksAgo, today);
const dateToData = data.reduce((acc, curr) => {
acc[curr.date] = curr;
return acc;
}, {});
const weekAgo = addDays(today, -7);
const saFormattedToday = saFormat(today);
const saFormattedWeekAgo = saFormat(weekAgo);
const {pageviews: visitsToday} = dateToData[saFormattedToday];
const {pageviews: visitsSameDayLastWeek} = dateToData[saFormattedWeekAgo];
const weekStart = saFormat(weekStartDate(today));
const lastWeekStart = saFormat(weekStartDate(weekAgo));
const viewsPerDayThisWeek = data
.filter(({date}) => date >= weekStart && date <= saFormattedToday)
.map(({pageviews}) => pageviews);
const viewsPerDayLastWeek = data
.filter(({date}) => date >= lastWeekStart && date < weekStart)
.map(({pageviews}) => pageviews);
const visitsThisWeek = viewsPerDayThisWeek.reduce(
(acc, curr) => acc + curr,
0
);
const visitsLastWeek = viewsPerDayLastWeek.reduce(
(acc, curr) => acc + curr,
0
);
const chartBaseUrl = 'https://quickchart.io/chart';
const weekChartConfig = {
type: 'bar',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [
{
label: 'Last Week',
backgroundColor: 'lightgrey',
data: viewsPerDayLastWeek
},
{
label: 'This Week',
backgroundColor: 'chartreuse',
data: viewsPerDayThisWeek
}
]
}
};
const dayChartConfig = {
type: 'bar',
data: {
labels: [],
datasets: [
{
label: saFormattedWeekAgo,
backgroundColor: 'lightgrey',
data: [visitsSameDayLastWeek]
},
{
label: 'Today',
backgroundColor: 'chartreuse',
data: [visitsToday]
}
]
},
options: {
legend: {
display: false
}
}
};
const dayChartUrl = `${chartBaseUrl}?c=${encodeURIComponent(
JSON.stringify(dayChartConfig)
)}&w=200`;
const weekChartUrl = `${chartBaseUrl}?c=${encodeURIComponent(
JSON.stringify(weekChartConfig)
)}`;
return {
visitsToday,
visitsSameDayLastWeek,
visitsThisWeek,
visitsLastWeek,
dayChartUrl,
weekChartUrl
};
}
const displayPercent = ratio => {
const percentageDifference = -100 + Math.floor(ratio * 100);
const sign = percentageDifference > 0 ? '+' : '';
return `${sign}${percentageDifference}%`;
};
const makeReportCaptions = ({
visitsToday,
visitsSameDayLastWeek,
visitsThisWeek,
visitsLastWeek
}) => ({
dayCaption: `Today vs same day last week, ${visitsToday.toLocaleString()} vs ${visitsSameDayLastWeek.toLocaleString()} (${displayPercent(
visitsToday / visitsSameDayLastWeek
)})`,
weekCaption: `This week vs last, ${visitsThisWeek.toLocaleString()} vs ${visitsLastWeek.toLocaleString()} (${displayPercent(
visitsThisWeek / visitsLastWeek
)})`
});
export async function handler(event) {
if (event.httpMethod !== 'POST') {
console.log(event.headers && event.headers.referer);
return {statusCode: 404};
}
try {
const report = await makeReport();
const {dayCaption, weekCaption} = makeReportCaptions(report);
console.log(`Sending daily report message: "${dayCaption}"`);
await sendMessage(`${dayCaption} [See chart](${report.dayChartUrl}`, {
parse_mode: 'Markdown',
disable_web_page_preview: true
});
console.log(
`Sending weekly analytics chart with caption: "${weekCaption}"`
);
await sendPhoto(report.weekChartUrl, weekCaption);
return {
statusCode: 200,
body: JSON.stringify({
...report,
dayCaption,
weekCaption
})
};
} catch (error) {
console.error(error.stack);
console.log(error.response);
return {
statusCode: 500,
body: JSON.stringify({message: error.toString()})
};
}
}
import axios from 'axios';
const {TELEGRAM_CHAT_ID, TELEGRAM_TOKEN} = process.env;
if (!TELEGRAM_CHAT_ID || !TELEGRAM_TOKEN) {
throw new Error('ChatId and Token need to be set');
}
const TELEGRAM_BASE_URL = `https://api.telegram.org/bot${TELEGRAM_TOKEN}`;
export function sendMessage(message, options = {}) {
return axios.post(`${TELEGRAM_BASE_URL}/sendMessage`, {
...options,
chat_id: TELEGRAM_CHAT_ID,
text: message
});
}
export function sendPhoto(url, caption) {
return axios.post(`${TELEGRAM_BASE_URL}/sendPhoto`, {
chat_id: TELEGRAM_CHAT_ID,
photo: url,
caption
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment