Skip to content

Instantly share code, notes, and snippets.

@fats
Last active May 10, 2020 11:45
Show Gist options
  • Save fats/1391fda158d1c4ecaed3b77b606674c4 to your computer and use it in GitHub Desktop.
Save fats/1391fda158d1c4ecaed3b77b606674c4 to your computer and use it in GitHub Desktop.
Post your latest commit to a Discord channel with a post-commit hook (Node.js)
// Post your latest commit to a Discord channel
// Run this script from a post-commit hook, or run manually from the top level of your project
const path = require('path')
const https = require('https')
const crypto = require('crypto')
const child_process = require('child_process')
// Fill your webhook id & token below
// Project name is set to the current folder name
const config =
{
webhook:
{
id: '',
token: ''
}
}
function post(url, object)
{
const data = JSON.stringify(object)
const options =
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(url, options, (res) =>
{
res.on('data', (d) => { process.stdout.write(d) })
})
req.on('error', (error) => { console.error(error) })
req.write(data)
req.end()
}
function exec(command)
{
return new Promise((resolve, reject) =>
{
child_process.exec(command, (error, stdout, stderr) =>
{
if (error)
reject()
else
resolve(stdout.trim())
})
})
}
(async () =>
{
const project_name = path.basename(path.resolve())
// test a specific commit
const hash = ''
const commit = {}
commit.author = {}
commit.author.name = await exec(`git log -1 --pretty=%an ${hash}`)
commit.author.email = await exec(`git log -1 --pretty=%ae ${hash}`)
const email_hash = crypto.createHash('md5').update(commit.author.email).digest('hex')
commit.author.avatar = `https://gravatar.com/avatar/${email_hash}?size=128`
commit.subject = await exec(`git log -1 --pretty=%s ${hash}`)
commit.body = await exec(`git log -1 --pretty=%b ${hash}`)
commit.author_date = await exec(`git log -1 --pretty=%aI ${hash}`)
const embed =
{
color: 0x0099ff,
title: commit.subject,
author:
{
name: commit.author.name,
icon_url: commit.author.avatar
},
description: commit.body,
timestamp: new Date(commit.author_date),
footer:
{
text: project_name
}
}
console.log(embed)
const data = { embeds: [ embed ] }
post(`https://discordapp.com/api/webhooks/${config.webhook.id}/${config.webhook.token}`, data)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment