NC-RUNNING-BOT
This file contains 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
import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda"; | |
import * as AWS from "aws-sdk"; | |
import axios from "axios"; | |
import * as moment from "moment"; | |
import { QuantifiedSelfLib } from "quantified-self-lib"; | |
import { WebClient } from "@slack/client"; | |
const DOMParser = require("xmldom").DOMParser; | |
AWS.config.update({ | |
region: "eu-west-1" | |
}); | |
const ddb = new AWS.DynamoDB.DocumentClient(); | |
const tableName = process.env.TABLE; | |
const AUTH_TOKEN = process.env.SLACK_ACCESS_TOKEN; | |
const IDENTITY_TOKEN = process.env.SLACK_ID_TOKEN; | |
const chat: WebClient["chat"] = new WebClient(IDENTITY_TOKEN).chat; | |
axios.defaults.headers.common["Authorization"] = `Bearer ${AUTH_TOKEN}`; | |
const gpxToDistance = (file, user) => | |
axios.get(file, { responseType: "text" }).then(response => { | |
let gpxString = response.data; | |
return QuantifiedSelfLib.importFromGPX(gpxString, DOMParser).then(event => { | |
const distance = event.getDistance().getDisplayValue(); | |
const duration = event.getDuration().getDisplayValue(); | |
const activityId = | |
user + | |
moment(event.startDate) | |
.unix() | |
.toString(); | |
const start = moment(event.startDate) | |
.unix() | |
.toString(); | |
const end = moment(event.endDate) | |
.unix() | |
.toString(); | |
return { activityId, distance, duration, start, end }; | |
}); | |
}); | |
export const main: Handler = ( | |
event: APIGatewayEvent, | |
_context: Context, | |
cb: Callback | |
) => { | |
const slackCallback = () => cb(null, { statusCode: 200 }); | |
const jsonBody = JSON.parse(event.body); | |
let fileURL = jsonBody.event.files[0].url_private; | |
if (!fileURL.includes(".gpx")) { | |
slackCallback(); | |
} | |
axios( | |
`https://slack.com/api/users.info?token=${AUTH_TOKEN}&user=${ | |
jsonBody.event.user | |
}`, | |
{ responseType: "json" } | |
) | |
.then(response => { | |
const user = response.data.user.name; | |
gpxToDistance(fileURL, user) | |
.then(response => { | |
ddb.put( | |
{ | |
TableName: tableName, | |
Item: { | |
...response, | |
user | |
} | |
}, | |
(err, _data) => { | |
if (err) { | |
slackCallback(); | |
} else { | |
try { | |
(async () => { | |
await chat.postMessage({ | |
channel: jsonBody.event.user, | |
text: `🔥🔥🔥🔥🔥🔥 Wow! Nice work ${user}! You did ${ | |
response.distance | |
}km in ${ | |
response.duration | |
}. Added it to Nordcloud Running competition` | |
}); | |
})(); | |
slackCallback(); | |
} catch (_e) { | |
slackCallback(); | |
} | |
} | |
} | |
); | |
}) | |
.catch(slackCallback); | |
}) | |
.catch(slackCallback); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment