githubgithub-api

Commenting a pull request in a GitHub action


I am trying to get a regular comment inserted in a pull request from a GitHub action. I can't seem to get it right. Octokit, the underlying library, allows you to create reviewComments to PRs, but those refer to a commit and that's not what I want, I want a simple comment. I figured I can just use octokit.issues.createComment. However, that does not seem to work. Here's the code

import * as core from '@actions/core';
const {GitHub, context} = require('@actions/github')
const parse = require('parse-diff')

async function run() {
    try {
        // get information on everything
        const token = core.getInput('github-token', {required: true})
        const github = new GitHub(token, {} )
        console.log( context )
        const PR_number = context.payload.pull_request.number

        // Check if the body contains required string
        const bodyContains = core.getInput('bodyContains')

        if ( context.payload.pull_request.body.indexOf( bodyContains) < 0  ) {
            core.setFailed("The body of the PR does not contain " + bodyContains);
            console.log( "Actor " + context.actor + " pr number " PR_number)
            const result = await github.issues.createComment({
                owner: context.actor,
                repo: context.payload.repository.full_name,
                issue_number: PR_number,
                body: "We need to have the word " + bodyContains + " in the body of the pull request"
            });
            console.log(result)
       } // more irrelevant stuff below
}}

This simply seems to retur "Not found". I can't seem to be able to find out if it's a type problem, or something different. Theoretically, owner, repo, and issue number, as well as body, should be right, and it's printed correctly. Any help will be appreciated. This is probably a more general question in the realm of GitHub API, with GitHub actions being simply the context, so I might be wrong there.


Solution

  • in 2024 this is how it worked for me:

    name: My name example
    on:
      pull_request:
        types: [opened, edited, synchronize, reopened]
    
    jobs:
      comment-in-pr:
    
        runs-on: ubuntu-latest
        permissions:
          contents: write
          pull-requests: write
          repository-projects: write
          id-token: write
    
        steps:
          - name: Checkout
            uses: actions/checkout@v4
          - uses: actions/github-script@v6
            with:
              script: |
                github.rest.issues.createComment({
                  issue_number: context.issue.number,
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  body: '👋 Thanks for reporting!'
                })