octokit / go-sdk

A generated Go SDK from GitHub's OpenAPI specification. Built on Kiota.
MIT License
71 stars 8 forks source link

[BUG]: Unable to create comment in PR #107

Closed JCzz closed 2 months ago

JCzz commented 3 months ago

What happened?

func for creating comment. Problem now is I can not find any Post function only Get:

// createComment sends a request to GitHub API to create a comment on an issue or PR
func createComment(client *pkg.Client, owner, repo string, issueNumber int, body string) error {

    queryParams := &issues.IssuesRequestBuilderGetQueryParameters{}
    requestConfig := &abs.RequestConfiguration[issues.IssuesRequestBuilderGetQueryParameters]{
        QueryParameters: queryParams,
    }

    _, err := client.Issues().Get(context.Background(), requestConfig)
    return err
}

Versions

go list -m github.com/octokit/go-sdk

0.0.26

Full example

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strings"

    "github.com/octokit/go-sdk/pkg"
    "github.com/octokit/go-sdk/pkg/github/issues"
)

func handleWebhook(w http.ResponseWriter, r *http.Request, client *pkg.Client) {
    var event map[string]interface{}
    if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
        http.Error(w, "Invalid request payload", http.StatusBadRequest)
        return
    }

    eventType := r.Header.Get("X-GitHub-Event")
    switch eventType {
    case "pull_request":
        // handlePullRequestEvent(event, client)
    case "issue_comment":
        handleIssueCommentEvent(event, client)
    default:
        log.Printf("Unhandled event type: %s", eventType)
    }

    fmt.Println(r)
    w.WriteHeader(http.StatusOK)
}

// handleIssueCommentEvent processes issue_comment events and replies to comments
func handleIssueCommentEvent(event map[string]interface{}, client *pkg.Client) {
    // Extract necessary fields from the event
    comment, ok := event["comment"].(map[string]interface{})
    if !ok {
        log.Println("Invalid comment payload")
        return
    }

    user, _ := comment["user"].(map[string]interface{})
    commentBody, _ := comment["body"].(string)
    commentAuthor, _ := user["login"].(string)

    // Extract repository and issue details
    issue, _ := event["issue"].(map[string]interface{})
    repo, _ := event["repository"].(map[string]interface{})
    repoName, _ := repo["name"].(string)
    repoOwner, _ := repo["owner"].(map[string]interface{})
    repoOwnerName, _ := repoOwner["login"].(string)
    issueNumber, _ := issue["number"].(float64)

    // Convert issueNumber to int
    issueNumberInt := int(issueNumber)

    // Check if comment contains the keyword and is from the right author
    if commentBody != "" && commentAuthor != "" {
        if commentBodyContainsApply(commentBody) {
            responseBody := "Thanks for applying - I will now run terraform apply and test each cluster before proceeding!"
            err := createComment(client, repoOwnerName, repoName, issueNumberInt, responseBody)
            if err != nil {
                log.Printf("Error creating comment: %v", err)
            } else {
                log.Println("Reply comment created successfully")
            }
        } else {
            log.Println("Ignoring comment. It doesn't contain 'apply'.")
        }
    }
}

// commentBodyContainsApply checks if the comment body contains the keyword "apply"
func commentBodyContainsApply(body string) bool {
    return containsIgnoreCase(body, "apply")
}

// containsIgnoreCase checks if a substring is present in a string, ignoring case
func containsIgnoreCase(str, substr string) bool {
    return strings.Contains(strings.ToLower(str), strings.ToLower(substr))
}

// createComment sends a request to GitHub API to create a comment on an issue or PR
func createComment(client *pkg.Client, owner, repo string, issueNumber int, body string) error {

    queryParams := &issues.IssuesRequestBuilderGetQueryParameters{}
    requestConfig := &abs.RequestConfiguration[issues.IssuesRequestBuilderGetQueryParameters]{
        QueryParameters: queryParams,
    }

    _, err := client.Issues().Get(context.Background(), requestConfig)
    return err
}

Code of Conduct

github-actions[bot] commented 3 months ago

👋 Hi! Thank you for this contribution! Just to let you know, our GitHub SDK team does a round of issue and PR reviews twice a week, every Monday and Friday! We have a process in place for prioritizing and responding to your input. Because you are a part of this community please feel free to comment, add to, or pick up any issues/PRs that are labeled with Status: Up for grabs. You & others like you are the reason all of this works! So thank you & happy coding! 🚀

kfcampbell commented 2 months ago

That route is underneath the Repos umbrella here, so your call would look something like:

issue, err := client.Repos().ByOwnerId("octokit").ByRepoId("go-sdk").Issues().ByIssue_number(42).Comments().Post(ctx, body, requestConfig)

In general, a good way to find the method you want is to find the API doc first (in this case https://docs.github.com/en/rest/issues/comments?apiVersion=2022-11-28#create-an-issue-comment), and then searching for the docs link (note the format difference, with the missing "en" in the path and without the apiVersion parameter) in the go-sdk code:

https://github.com/octokit/go-sdk/blob/9d26873c93cc3d98b12d3e9289b1fa65659670a1/pkg/github/repos/item_item_issues_item_comments_request_builder.go#L72

Does that help?

JCzz commented 2 months ago

Thanks @kfcampbell Great help.