Skip to content

Commit 3b5fadf

Browse files
committed
refactor: improved and fixed errors with webhook
1 parent e04c222 commit 3b5fadf

File tree

3 files changed

+127
-72
lines changed

3 files changed

+127
-72
lines changed

.github/scripts/webhook.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
const https = require('https');
2+
3+
async function sendDiscordNotification(webhookUrl, commits, fileCount) {
4+
if (!webhookUrl) {
5+
throw new Error('DISCORD_WEBHOOK_URL secret is missing');
6+
}
7+
8+
if (!commits || commits.length === 0) {
9+
throw new Error('No commits found in this push event');
10+
}
11+
12+
const fields = commits.map((commit) => {
13+
const commitFields = [
14+
{ name: `Commit ${commit.sha}`, value: commit.message, inline: false }
15+
];
16+
17+
const body = commit.full_message.split('\n').slice(1).join('\n').trim();
18+
if (body !== '') {
19+
commitFields.push({ name: 'Details', value: body, inline: false });
20+
}
21+
22+
commitFields.push({ name: 'By', value: commit.author, inline: true });
23+
24+
return commitFields;
25+
}).flat();
26+
27+
fields.push({ name: 'Files Updated', value: `${fileCount} file(s)`, inline: true });
28+
29+
const embed = {
30+
title: 'TDS Statistics Editor Update',
31+
description: `Push contains ${commits.length} commit(s)`,
32+
color: 5763719,
33+
fields,
34+
footer: { text: 'Thank you for using the Statistics Editor!' },
35+
timestamp: new Date().toISOString()
36+
};
37+
38+
const payload = { embeds: [embed] };
39+
const data = JSON.stringify(payload);
40+
41+
return new Promise((resolve, reject) => {
42+
const url = new URL(webhookUrl);
43+
const options = {
44+
hostname: url.hostname,
45+
path: url.pathname + url.search,
46+
method: 'POST',
47+
headers: {
48+
'Content-Type': 'application/json',
49+
'Content-Length': Buffer.byteLength(data),
50+
'User-Agent': 'github-actions/discord-notify'
51+
}
52+
};
53+
54+
const req = https.request(options, (res) => {
55+
let body = '';
56+
res.on('data', (d) => body += d);
57+
res.on('end', () => {
58+
if (res.statusCode < 200 || res.statusCode >= 300) {
59+
reject(new Error(`Failed to post to Discord: HTTP ${res.statusCode} ${body}`));
60+
} else {
61+
resolve('Discord webhook posted successfully');
62+
}
63+
});
64+
});
65+
66+
req.on('error', (err) => reject(new Error(`Failed to post to Discord: ${err.message}`)));
67+
req.write(data);
68+
req.end();
69+
});
70+
}
71+
72+
module.exports = { sendDiscordNotification };

.github/workflows/notify.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ jobs:
1414

1515
steps:
1616
- name: Checkout code
17-
uses: actions/checkout@v4
17+
uses: actions/checkout@v5
1818
with:
1919
fetch-depth: 2
2020

.github/workflows/webhook.yml

Lines changed: 54 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -11,79 +11,62 @@ jobs:
1111
contents: read
1212
steps:
1313
- name: Checkout repository
14-
uses: actions/checkout@v4
14+
uses: actions/checkout@v5
1515
with:
1616
fetch-depth: 0
1717

18-
- name: Send Discord notification (all commits in push)
19-
uses: actions/github-script@v6
20-
env:
21-
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
22-
with:
23-
script: |
24-
const webhookUrl = process.env.DISCORD_WEBHOOK_URL;
25-
if (!webhookUrl) core.setFailed('DISCORD_WEBHOOK_URL secret is missing');
26-
27-
const commits = context.payload?.commits;
28-
if (!commits || commits.length === 0) core.setFailed('No commits found in this push event');
29-
30-
const fields = commits.map(commit => {
31-
const sha = commit.id?.slice(0,7) || '(unknown)';
32-
const msg = commit.message?.split('\n')[0] || '(no message)';
33-
const body = commit.message?.split('\n').slice(1).join('\n') || '';
34-
const author = commit.author?.name || commit.author?.username || '(unknown)';
35-
const fileCount = (commit.added?.length || 0) + (commit.removed?.length || 0) + (commit.modified?.length || 0);
36-
37-
const commitFields = [
38-
{ name: `Commit ${sha}`, value: msg, inline: false }
39-
];
40-
if (body.trim() !== '') commitFields.push({ name: 'Details', value: body, inline: false });
41-
commitFields.push(
42-
{ name: 'Files Updated', value: `${fileCount} file(s)`, inline: true },
43-
{ name: 'By', value: author, inline: true }
44-
);
45-
46-
return commitFields;
47-
}).flat();
18+
- name: Get commit and file details
19+
id: commit
20+
run: |
21+
BEFORE_SHA="${{ github.event.before }}"
22+
AFTER_SHA="${{ github.event.after }}"
23+
24+
if [ "$BEFORE_SHA" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$BEFORE_SHA" 2>/dev/null; then
25+
COMMITS_JSON=$(git log --oneline -10 --pretty=format:'{"sha":"%h","message":"%s","author":"%an"}' |
26+
while IFS= read -r line; do
27+
sha=$(echo "$line" | jq -r '.sha')
28+
full_message=$(git show --no-patch --format="%B" $sha | jq -R -s .)
29+
echo "$line" | jq --arg full_message "$full_message" '. + {full_message: $full_message}'
30+
done | jq -s -c .)
31+
32+
CHANGED_FILES=$(git show --name-only --pretty="" $AFTER_SHA)
33+
FILE_COUNT=$(echo "$CHANGED_FILES" | wc -l)
34+
else
35+
COMMITS_JSON=$(git log --oneline "$BEFORE_SHA..$AFTER_SHA" --pretty=format:'{"sha":"%h","message":"%s","author":"%an"}' |
36+
while IFS= read -r line; do
37+
sha=$(echo "$line" | jq -r '.sha')
38+
full_message=$(git show --no-patch --format="%B" $sha | jq -R -s .)
39+
echo "$line" | jq --arg full_message "$full_message" '. + {full_message: $full_message}'
40+
done | jq -s -c .)
41+
42+
CHANGED_FILES=$(git diff --name-only "$BEFORE_SHA" "$AFTER_SHA")
43+
FILE_COUNT=$(echo "$CHANGED_FILES" | wc -l)
44+
fi
4845
49-
const embed = {
50-
title: 'TDS Statistics Editor Update',
51-
description: `Push contains ${commits.length} commit(s)`,
52-
color: 5763719,
53-
fields,
54-
footer: { text: 'Thank you for using the Statisics Editor!' },
55-
timestamp: new Date().toISOString()
56-
};
46+
ESCAPED_COMMITS_JSON=$(echo "$COMMITS_JSON" | jq -R -s .)
47+
48+
echo "commits_json=$ESCAPED_COMMITS_JSON" >> $GITHUB_OUTPUT
49+
echo "file_count=$FILE_COUNT" >> $GITHUB_OUTPUT
5750
58-
const payload = { embeds: [embed] };
59-
60-
const { request } = require('https');
61-
const u = new URL(webhookUrl);
62-
const data = JSON.stringify(payload);
63-
64-
const options = {
65-
hostname: u.hostname,
66-
path: u.pathname + u.search,
67-
method: 'POST',
68-
headers: {
69-
'Content-Type': 'application/json',
70-
'Content-Length': Buffer.byteLength(data),
71-
'User-Agent': 'github-actions/discord-notify'
72-
}
73-
};
74-
75-
const req = request(options, res => {
76-
let body = '';
77-
res.on('data', d => body += d);
78-
res.on('end', () => {
79-
if (res.statusCode < 200 || res.statusCode >= 300) {
80-
core.setFailed(`Failed to post to Discord: HTTP ${res.statusCode} ${body}`);
81-
} else {
82-
core.info('Discord webhook posted successfully');
83-
}
84-
});
85-
});
86-
87-
req.on('error', err => core.setFailed(`Failed to post to Discord: ${err.message}`));
88-
req.write(data);
89-
req.end();
51+
- name: Send Discord notification
52+
uses: actions/github-script@v7
53+
with:
54+
script: |
55+
const { sendDiscordNotification } = require('./.github/scripts/webhook.js');
56+
57+
// Parse the escaped JSON
58+
const commitsJsonString = process.env.COMMITS_JSON;
59+
const commits = JSON.parse(commitsJsonString);
60+
const fileCount = parseInt(process.env.FILE_COUNT || '0');
61+
62+
await sendDiscordNotification(
63+
process.env.DISCORD_WEBHOOK_URL,
64+
commits,
65+
fileCount
66+
);
67+
68+
console.log('Discord webhook posted successfully');
69+
env:
70+
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
71+
COMMITS_JSON: ${{ steps.commit.outputs.commits_json }}
72+
FILE_COUNT: ${{ steps.commit.outputs.file_count }}

0 commit comments

Comments
 (0)