|
| 1 | +import dotenv from "dotenv"; |
| 2 | +import fs from "fs"; |
| 3 | +import http from "http"; |
| 4 | +import { App } from "octokit"; |
| 5 | +import { createNodeMiddleware } from "@octokit/webhooks"; |
| 6 | + |
| 7 | +// Load environment variables from .env file |
| 8 | +dotenv.config(); |
| 9 | + |
| 10 | +// Set configured values |
| 11 | +const appId = process.env.APP_ID; |
| 12 | +const privateKeyPath = process.env.PRIVATE_KEY_PATH; |
| 13 | +const privateKey = fs.readFileSync(privateKeyPath, "utf8"); |
| 14 | +const secret = process.env.WEBHOOK_SECRET; |
| 15 | +const messageForNewPRs = fs.readFileSync("./message.md", "utf8"); |
| 16 | + |
| 17 | +// Create an authenticated Octokit client authenticated as a GitHub App |
| 18 | +const app = new App({ appId, privateKey, webhooks: { secret }}); |
| 19 | + |
| 20 | +// Optional: Get & log the authenticated app's name |
| 21 | +const { data } = await app.octokit.request("/app"); |
| 22 | + |
| 23 | +// Read more about custom logging: https://github.com/octokit/core.js#logging |
| 24 | +app.octokit.log.debug(`Authenticated as '${ data.name }'`); |
| 25 | + |
| 26 | +// Subscribe to the "pull_request.opened" webhook event |
| 27 | +app.webhooks.on("pull_request.opened", async ({ octokit, payload }) => { |
| 28 | + console.log(`Received a pull request event for #${ payload.pull_request.number }`); |
| 29 | + await octokit.rest.issues.createComment({ |
| 30 | + owner: payload.repository.owner.login, |
| 31 | + repo: payload.repository.name, |
| 32 | + issue_number: payload.pull_request.number, |
| 33 | + body: messageForNewPRs, |
| 34 | + }); |
| 35 | +}); |
| 36 | + |
| 37 | +// Optional: Handle errors |
| 38 | +app.webhooks.onError((error) => { |
| 39 | + if (error.name === "AggregateError") { |
| 40 | + // Log Secret verification errors |
| 41 | + console.log(`Error processing request: ${ error.event }`); |
| 42 | + } else { |
| 43 | + console.log(error); |
| 44 | + } |
| 45 | +}); |
| 46 | + |
| 47 | +// Launch a web server to listen for GitHub webhooks |
| 48 | +const port = process.env.PORT || 3000; |
| 49 | +const path = "/api/webhook"; |
| 50 | +const localWebhookUrl = `http://localhost:${ port }${ path }`; |
| 51 | + |
| 52 | +// See https://github.com/octokit/webhooks.js/#createnodemiddleware for all options |
| 53 | +const middleware = createNodeMiddleware(app.webhooks, { path }); |
| 54 | + |
| 55 | +http.createServer(middleware).listen(port, () => { |
| 56 | + console.log(`Server is listening for events at: ${localWebhookUrl}`); |
| 57 | + console.log('Press Ctrl + C to quit.') |
| 58 | +}); |
0 commit comments