code icon Code

Comment on GitHub Pull Request

Add a comment to an existing GitHub pull request

Source Code

const [owner, repo, pr_number, body] = process.argv.slice(2);

const token = process.env.GITHUB_TOKEN || "PLACEHOLDER_TOKEN";

async function addComment() {
  // PRs use the issues endpoint for general comments
  const url = `https://api.github.com/repos/${owner}/${repo}/issues/${pr_number}/comments`;

  console.log(`Adding comment to ${owner}/${repo} PR #${pr_number}...`);

  const response = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/vnd.github+json",
      "X-GitHub-Api-Version": "2022-11-28",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ body }),
  });

  if (!response.ok) {
    const error = await response.json();
    console.error("ERROR: GitHub API request failed.");
    console.error(`  Status: ${response.status}`);
    console.error(`  Message: ${error.message || response.statusText}`);
    console.error("  Check that the PR exists and you have access to comment.");
    process.exit(1);
  }

  const remaining = response.headers.get("X-RateLimit-Remaining");
  if (remaining && parseInt(remaining) < 100) {
    console.log(`⚠️ Rate limit warning: ${remaining} requests remaining`);
  }

  const comment = await response.json();

  console.log(`✅ Added comment to PR #${pr_number}`);
  console.log(`   URL: ${comment.html_url}`);
}

try {
  await addComment();
} catch (error) {
  console.error("ERROR: Unexpected failure adding comment to PR.");
  console.error(`  ${error.message}`);
  process.exit(1);
}