Skip to content

Instantly share code, notes, and snippets.

@DennisAlund
Created April 5, 2017 04:52
Show Gist options
  • Select an option

  • Save DennisAlund/d21235d0c53cdeeac7428a4e0aa0e372 to your computer and use it in GitHub Desktop.

Select an option

Save DennisAlund/d21235d0c53cdeeac7428a4e0aa0e372 to your computer and use it in GitHub Desktop.
Firebase cloud function for Slack button actions in medium article https://medium.com/evenbit/151c1c98641d
export const on_actions = functions.database.ref("actions/{id}").onWrite(async (event) => {
if (!event.data.exists()) {
return "Nothing to do for deletion of processed commands.";
}
// Start by deleting the action request itself from the queue
await event.data.ref.remove();
const action = event.data.val();
if (action.callback_id !== "ping-pong") {
console.error("Only ping pong actions are implemented!");
return;
}
const pongId = admin.database().ref("pong").push().key;
const pingId = action.actions[0].value;
const pingRef = admin.database().ref("ping").child(pingId);
const transactionResult = await pingRef.transaction((ping) => {
if (!ping) {
return null;
}
if (ping.pongs && Object.keys(ping.pongs).length >= 3) {
// Only count the first three pings!
console.log(`User ${action.user.name}@${action.team.domain} was too late to reply to ping ${pingId}`);
return;
}
ping.pongs = ping.pongs || {};
// Slack timestamps comes as Unix Epoch in SECONDS with milliseconds in fraction
ping.pongs[pongId] = Math.round(parseFloat(action.action_ts) * 1000);
return ping;
});
const committed = transactionResult.committed;
const ping = transactionResult.snapshot.exists() ? transactionResult.snapshot.val() : null;
if (!committed) {
return "Not your luck today";
}
const pongTime = ping.pongs[pongId];
const pong: Pong = {
ponged_at: pongTime,
ping_pong_time: pongTime - ping.pinged_at,
user_id: action.user.id,
user_name: action.user.name,
team: action.team.id,
ping: pingId
};
await admin.database().ref("pong").child(pongId).set(pong);
const numberOfPongs = Object.keys(ping.pongs).length;
if (numberOfPongs < 3) {
return "Waiting for more pongs";
}
return sendPingPongScore(pingId);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment