|
| 1 | +importdotenvfrom"dotenv"; |
| 2 | +importfsfrom"fs"; |
| 3 | +importhttpfrom"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 | +constappId=process.env.APP_ID; |
| 12 | +constprivateKeyPath=process.env.PRIVATE_KEY_PATH; |
| 13 | +constprivateKey=fs.readFileSync(privateKeyPath,"utf8"); |
| 14 | +constsecret=process.env.WEBHOOK_SECRET; |
| 15 | +constmessageForNewPRs=fs.readFileSync("./message.md","utf8"); |
| 16 | + |
| 17 | +// Create an authenticated Octokit client authenticated as a GitHub App |
| 18 | +constapp=newApp({ appId, privateKey,webhooks:{ secret}}); |
| 19 | + |
| 20 | +// Optional: Get & log the authenticated app's name |
| 21 | +const{ data}=awaitapp.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 | +awaitoctokit.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 | +constport=process.env.PORT||3000; |
| 49 | +constpath="/api/webhook"; |
| 50 | +constlocalWebhookUrl=`http://localhost:${port}${path}`; |
| 51 | + |
| 52 | +// See https://github.com/octokit/webhooks.js/#createnodemiddleware for all options |
| 53 | +constmiddleware=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 | +}); |