Next: , Previous: , Up: GitHub API Authentication---GitHub Actions   [Index]


1.1.3.2 Creating a comment using JavaScript

We will use GitHub’s ‘Create a comment’ REST API endpoint to create the comment on every new pull request using octokit.request.

  1. Create a package.json file in the folder you cloned your repository into:
npm init
  1. After that, install @octokit/action
npm install @octokit/action
  1. Next, create the .github/actions/pr-comment.js file
// GITHUB_EVENT_PATH always exists when run by an Action,
// see https://git.io/JvUf7 for a full list
const eventPayload = require(process.env.GITHUB_EVENT_PATH);
const { Octokit } = require("@octokit/action");

createPrComment();

async function createPrComment() {
  // No need to pass process.env.GITHUB_TOKEN, `@octokit/action`
  // is using it directly and throws an error if it is not present.
  const octokit = new Octokit();

  // See https://developer.github.com/v3/issues/comments/#create-a-comment
  const { data } = await octokit.request(
    "POST /repos/:repository/issues/:pr_number/comments",
    {
      repository: process.env.GITHUB_REPOSITORY,
      pr_number: eventPayload.pull_request.number,
      body: "Thank you for your pull request!"
    }
  );

  console.log("Comment created: %d", data.html_url);
}
  1. Commit and push your changes
git add .
git commit -m 'add GitHub Action workflow to comment on new PRs'
git push origin master
  1. Now create a new pull request on your repository. After a short delay, the Action will show up in the list of checks as pending