Skip to content

Instantly share code, notes, and snippets.

@naranjja
Created November 8, 2018 22:50
Show Gist options
  • Save naranjja/12dfbb6a9ebc64316747a3190f51163c to your computer and use it in GitHub Desktop.
Save naranjja/12dfbb6a9ebc64316747a3190f51163c to your computer and use it in GitHub Desktop.
Google Analytics implementation using universal-analytics and Dialogflow
TRACKING_ID="UA-XXXXXXXX-Y"
// error handling is done here too
module.exports = (action) => {
switch (action) {
case "":
// do something
}
}
require("dotenv").config() // read .env file variables to process.env
const express = require("express")
const bodyParser = require("body-parser")
const Tracker = require("./Tracker.js")
const handleAction = require("./handleAction.js")
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const actions = [""] // list of actions
app.post("/", (req, res) => {
const agent = new WebhookClient({ request: req, response: res })
const PSID = req.body.originalDetectIntentRequest.data.sender.id
const actionHandler = (agent) => {
try {
if (~actions.indexOf(agent.action)) {
const tracker = new Tracker(PSID) // instance tracker using PSID
tracker.sendEvent("messages", agent.action, agent.query)
handleAction(agent.action)
} else if (agent.action) {
tracker.sendEvent("errors", `unhandled action ${agent.action}`, agent.query)
}
} catch (err) {
tracker.sendEvent("errors", `unhandled error`, agent.query)
}
}
agent.handleRequest(actionHandler)
}
{
"dependencies": {
"bluebird": "^3.5.2",
"body-parser": "^1.18.3",
"dialogflow-fulfillment": "^0.6.1",
"dotenv": "^6.0.0",
"express": "^4.16.3",
"universal-analytics": "^0.4.20"
}
}
const ua = require("universal-analytics")
const bluebird = require("bluebird")
module.exports = class Tracker {
constructor (uid) {
this._uid = "" + uid // cast to string
this._visitor = ua(process.env.TRACKING_ID, this._uid, { strictCidFormat: false })
bluebird.promisifyAll(this._visitor)
}
sendEvent (category, action, label) {
if (!this._visitor) return
this._visitor.eventAsync(category, action, label).catch((err) => console.error(err))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment