Last active
December 12, 2016 17:18
-
-
Save alanzchen/1d934c6a647f84d46fa6d1e0d4542519 to your computer and use it in GitHub Desktop.
A scriptr.io script to bridge sendgrid notification and telegram.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//First, we'll require the 'http' library to use later for calling a 3rd party webservice | |
var http = require("http"); | |
//Getting parameters from the request body. For a nested json, we only want the first one. | |
try { | |
var parameters = JSON.parse(request.rawBody); | |
parameters = parameters[0] | |
var ip = parameters.ip; | |
var email = parameters.email; | |
var ua = parameters.useragent; | |
var event = parameters.event; | |
var eventid = parameters.sg_event_id; | |
var msgid = parameters.sg_message_id; | |
var timestamp = parameters.timestamp; | |
} catch(exception) { return exception; } | |
//Suppose you want to make that value available to future running script instances | |
//you can store it in a persistent variable | |
//Ignore duplication detection if the interval between events are more than 5 minutes. | |
if (timestamp - storage.local.prevtimestamp > 300) { | |
var timeout_pass = true; | |
} else { | |
var timeout_pass = false; | |
} | |
if (timeout_pass || (msgid != storage.local.prevmsgid && event != storage.local.prevevent)) { | |
var text = "<b>[Email Notification]</b>\n" + email + " triggered " + event + ".\nIP:<a href=\"http://ipinfo.io/" + ip + "\">" + ip + "</a>\nUA: " + ua | |
if (storage.local.duplicatecount > 1) { | |
text += "\nwith " + storage.local.duplicatecount + " notifications not shown." | |
} | |
var teleRequestObject = { | |
"url": "https://api.telegram.org/bot[your_token]/sendMessage", | |
"params": {"text": text, "parse_mode": "HTML", "chat_id": "[your_chat_id]"}, | |
"method": "POST" // the method is optional, it defaults to GET. | |
} | |
var response = http.request(teleRequestObject); | |
storage.local.prevmsgid = msgid; | |
storage.local.prevevent = event; | |
storage.local.prevtimestamp = timestamp; | |
storage.local.duplicatecount = 0 | |
return response | |
} else { | |
storage.local.duplicatecount += 1 | |
return "Duplicated. Count: " + storage.local.duplicatecount | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment