GitHub API Integration for ChatGPT Apps: Developer Workflow Automation

GitHub is the world's largest code hosting platform with 100+ million developers. Integrating GitHub with your ChatGPT app unlocks powerful developer workflow automation: repository management, pull request reviews, CI/CD orchestration, issue tracking, and code analysis—all through natural language conversations.

This comprehensive guide covers GitHub API integration for ChatGPT apps, including REST and GraphQL APIs, OAuth authentication, repository operations, pull request automation, GitHub Actions integration, and advanced features like code scanning and project management. You'll learn how to build production-ready ChatGPT apps that streamline developer workflows and boost team productivity.

Whether you're building a code review assistant, release automation tool, or DevOps chatbot, this guide provides everything you need to integrate GitHub with ChatGPT apps using no-code ChatGPT app builder or custom development.

Why Integrate GitHub with ChatGPT Apps?

Developer Workflow Automation Automate repetitive tasks like creating branches, opening pull requests, managing issues, and triggering deployments through conversational interfaces. Developers can execute complex workflows without leaving ChatGPT.

Code Review Intelligence Analyze pull requests, suggest improvements, detect bugs, and enforce coding standards using AI-powered reviews. ChatGPT can review diffs, comment on code quality, and approve changes automatically.

CI/CD Orchestration Trigger GitHub Actions workflows, monitor build status, deploy applications, and manage releases through natural language commands. Integrate with deployment pipelines and infrastructure as code.

Team Collaboration Manage issues, assign tasks, update project boards, and facilitate discussions through ChatGPT. Streamline communication between developers, product managers, and stakeholders.

GitHub App vs OAuth App: Authentication Types

GitHub Apps (Recommended for Production)

GitHub Apps provide fine-grained permissions, installation-based authentication, and better security than OAuth Apps. They're ideal for ChatGPT apps that need organization-wide access or act on behalf of the app itself.

Key Advantages:

  • Fine-grained repository and organization permissions
  • Installation tokens (1-hour expiration) for enhanced security
  • Webhook events for real-time updates
  • Rate limits per installation (5,000 requests/hour)
  • Can act as the app itself or impersonate users

Installation Flow:

  1. User installs GitHub App on repositories or organizations
  2. App receives installation token via webhook
  3. Use installation token for API requests
  4. Token auto-refreshes before expiration

Permissions Model:

  • Repository permissions: contents, pull requests, issues, actions
  • Organization permissions: members, projects, webhooks
  • Account permissions: email, profile

Best Practices:

  • Request minimal permissions needed for functionality
  • Use installation tokens for repository operations
  • Implement webhook handlers for real-time events
  • Store installation IDs securely in your database

Learn more about building secure ChatGPT apps with proper authentication.

OAuth Apps (User Authorization)

OAuth Apps authenticate individual users and act on their behalf. They're suitable for ChatGPT apps that need user-specific permissions or personal repository access.

Key Characteristics:

  • User-level permissions (read, write, admin)
  • Long-lived access tokens (no automatic expiration)
  • Simpler authorization flow
  • Rate limits per user (5,000 requests/hour)

Authorization Flow:

  1. Redirect user to GitHub OAuth authorization page
  2. User grants permissions
  3. Exchange authorization code for access token
  4. Use access token for API requests on user's behalf

Scopes Required:

  • repo: Full repository access
  • read:org: Read organization data
  • workflow: Update GitHub Actions workflows
  • admin:repo_hook: Manage repository webhooks

Security Considerations:

  • Store access tokens encrypted in your database
  • Implement token refresh mechanism
  • Validate user permissions before operations
  • Use state parameter to prevent CSRF attacks

For more authentication patterns, see OAuth 2.1 for ChatGPT apps.

Repository Operations: Create, Update, and Manage

GitHub OAuth Handler (TypeScript)

This production-ready OAuth handler manages GitHub authentication, token refresh, and API request signing for ChatGPT apps.

import { Octokit } from '@octokit/rest';
import { createAppAuth } from '@octokit/auth-app';
import * as crypto from 'crypto';

interface GitHubOAuthConfig {
  clientId: string;
  clientSecret: string;
  redirectUri: string;
  appId?: string;
  privateKey?: string;
}

interface GitHubTokens {
  accessToken: string;
  refreshToken?: string;
  expiresAt?: Date;
  scope: string[];
}

interface Repository {
  id: number;
  name: string;
  fullName: string;
  owner: string;
  private: boolean;
  defaultBranch: string;
  url: string;
}

export class GitHubOAuthHandler {
  private config: GitHubOAuthConfig;
  private octokit: Octokit | null = null;

  constructor(config: GitHubOAuthConfig) {
    this.config = config;
  }

  /**
   * Generate OAuth authorization URL with PKCE
   */
  generateAuthUrl(state: string, scopes: string[]): string {
    const params = new URLSearchParams({
      client_id: this.config.clientId,
      redirect_uri: this.config.redirectUri,
      scope: scopes.join(' '),
      state: state,
      allow_signup: 'true'
    });

    return `https://github.com/login/oauth/authorize?${params.toString()}`;
  }

  /**
   * Exchange authorization code for access token
   */
  async exchangeCodeForToken(code: string): Promise<GitHubTokens> {
    const response = await fetch('https://github.com/login/oauth/access_token', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        client_id: this.config.clientId,
        client_secret: this.config.clientSecret,
        code: code,
        redirect_uri: this.config.redirectUri
      })
    });

    const data = await response.json();

    if (data.error) {
      throw new Error(`GitHub OAuth error: ${data.error_description}`);
    }

    return {
      accessToken: data.access_token,
      refreshToken: data.refresh_token,
      expiresAt: data.expires_in
        ? new Date(Date.now() + data.expires_in * 1000)
        : undefined,
      scope: data.scope.split(',')
    };
  }

  /**
   * Initialize Octokit with access token
   */
  async authenticate(accessToken: string): Promise<void> {
    this.octokit = new Octokit({
      auth: accessToken,
      userAgent: 'ChatGPT-GitHub-Integration/1.0'
    });
  }

  /**
   * Initialize Octokit as GitHub App
   */
  async authenticateAsApp(installationId: number): Promise<void> {
    if (!this.config.appId || !this.config.privateKey) {
      throw new Error('GitHub App credentials not configured');
    }

    this.octokit = new Octokit({
      authStrategy: createAppAuth,
      auth: {
        appId: this.config.appId,
        privateKey: this.config.privateKey,
        installationId: installationId
      }
    });
  }

  /**
   * Get authenticated user
   */
  async getCurrentUser(): Promise<any> {
    if (!this.octokit) throw new Error('Not authenticated');

    const { data } = await this.octokit.users.getAuthenticated();
    return {
      id: data.id,
      login: data.login,
      name: data.name,
      email: data.email,
      avatarUrl: data.avatar_url,
      bio: data.bio,
      company: data.company
    };
  }

  /**
   * Verify webhook signature
   */
  verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
    const hmac = crypto.createHmac('sha256', secret);
    const digest = 'sha256=' + hmac.update(payload).digest('hex');
    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(digest)
    );
  }

  getOctokit(): Octokit {
    if (!this.octokit) {
      throw new Error('Not authenticated. Call authenticate() first.');
    }
    return this.octokit;
  }
}

Repository Manager (TypeScript)

Comprehensive repository operations including creation, branching, commits, and file management.

import { Octokit } from '@octokit/rest';

interface CreateRepoOptions {
  name: string;
  description?: string;
  private?: boolean;
  autoInit?: boolean;
  gitignoreTemplate?: string;
  licenseTemplate?: string;
}

interface CreateFileOptions {
  owner: string;
  repo: string;
  path: string;
  content: string;
  message: string;
  branch?: string;
}

interface CreateBranchOptions {
  owner: string;
  repo: string;
  branch: string;
  fromBranch?: string;
}

export class RepositoryManager {
  private octokit: Octokit;

  constructor(octokit: Octokit) {
    this.octokit = octokit;
  }

  /**
   * Create a new repository
   */
  async createRepository(options: CreateRepoOptions): Promise<Repository> {
    const { data } = await this.octokit.repos.createForAuthenticatedUser({
      name: options.name,
      description: options.description,
      private: options.private ?? false,
      auto_init: options.autoInit ?? true,
      gitignore_template: options.gitignoreTemplate,
      license_template: options.licenseTemplate
    });

    return {
      id: data.id,
      name: data.name,
      fullName: data.full_name,
      owner: data.owner.login,
      private: data.private,
      defaultBranch: data.default_branch,
      url: data.html_url
    };
  }

  /**
   * Create a new branch
   */
  async createBranch(options: CreateBranchOptions): Promise<string> {
    const { owner, repo, branch, fromBranch } = options;

    // Get the SHA of the source branch
    const sourceBranch = fromBranch || (
      await this.octokit.repos.get({ owner, repo })
    ).data.default_branch;

    const { data: ref } = await this.octokit.git.getRef({
      owner,
      repo,
      ref: `heads/${sourceBranch}`
    });

    // Create new branch
    await this.octokit.git.createRef({
      owner,
      repo,
      ref: `refs/heads/${branch}`,
      sha: ref.object.sha
    });

    return branch;
  }

  /**
   * Create or update a file
   */
  async createOrUpdateFile(options: CreateFileOptions): Promise<string> {
    const { owner, repo, path, content, message, branch } = options;

    // Check if file exists
    let sha: string | undefined;
    try {
      const { data } = await this.octokit.repos.getContent({
        owner,
        repo,
        path,
        ref: branch
      });
      if ('sha' in data) {
        sha = data.sha;
      }
    } catch (error: any) {
      if (error.status !== 404) throw error;
    }

    // Create or update file
    const { data } = await this.octokit.repos.createOrUpdateFileContents({
      owner,
      repo,
      path,
      message,
      content: Buffer.from(content).toString('base64'),
      branch,
      sha
    });

    return data.commit.sha;
  }

  /**
   * Get repository content
   */
  async getFileContent(owner: string, repo: string, path: string, ref?: string): Promise<string> {
    const { data } = await this.octokit.repos.getContent({
      owner,
      repo,
      path,
      ref
    });

    if (Array.isArray(data) || !('content' in data)) {
      throw new Error('Path is a directory, not a file');
    }

    return Buffer.from(data.content, 'base64').toString('utf-8');
  }

  /**
   * List repository branches
   */
  async listBranches(owner: string, repo: string): Promise<string[]> {
    const { data } = await this.octokit.repos.listBranches({
      owner,
      repo,
      per_page: 100
    });

    return data.map(branch => branch.name);
  }

  /**
   * Delete a branch
   */
  async deleteBranch(owner: string, repo: string, branch: string): Promise<void> {
    await this.octokit.git.deleteRef({
      owner,
      repo,
      ref: `heads/${branch}`
    });
  }
}

Explore more API integration patterns for ChatGPT to enhance your developer workflows.

Pull Request Automation: Review, Merge, and Orchestrate

Pull Request Automation (TypeScript)

Automate pull request creation, reviews, status checks, and intelligent merge strategies.

import { Octokit } from '@octokit/rest';

interface CreatePROptions {
  owner: string;
  repo: string;
  title: string;
  head: string;
  base: string;
  body?: string;
  draft?: boolean;
  maintainerCanModify?: boolean;
}

interface ReviewPROptions {
  owner: string;
  repo: string;
  pullNumber: number;
  event: 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';
  body?: string;
  comments?: Array<{
    path: string;
    line: number;
    body: string;
  }>;
}

interface MergePROptions {
  owner: string;
  repo: string;
  pullNumber: number;
  mergeMethod?: 'merge' | 'squash' | 'rebase';
  commitTitle?: string;
  commitMessage?: string;
}

export class PullRequestAutomation {
  private octokit: Octokit;

  constructor(octokit: Octokit) {
    this.octokit = octokit;
  }

  /**
   * Create a pull request
   */
  async createPullRequest(options: CreatePROptions): Promise<number> {
    const { owner, repo, title, head, base, body, draft, maintainerCanModify } = options;

    const { data } = await this.octokit.pulls.create({
      owner,
      repo,
      title,
      head,
      base,
      body: body || '',
      draft: draft ?? false,
      maintainer_can_modify: maintainerCanModify ?? true
    });

    return data.number;
  }

  /**
   * Review a pull request with comments
   */
  async reviewPullRequest(options: ReviewPROptions): Promise<void> {
    const { owner, repo, pullNumber, event, body, comments } = options;

    await this.octokit.pulls.createReview({
      owner,
      repo,
      pull_number: pullNumber,
      event,
      body,
      comments: comments?.map(c => ({
        path: c.path,
        line: c.line,
        body: c.body
      }))
    });
  }

  /**
   * Merge a pull request with strategy
   */
  async mergePullRequest(options: MergePROptions): Promise<string> {
    const { owner, repo, pullNumber, mergeMethod, commitTitle, commitMessage } = options;

    const { data } = await this.octokit.pulls.merge({
      owner,
      repo,
      pull_number: pullNumber,
      merge_method: mergeMethod || 'merge',
      commit_title: commitTitle,
      commit_message: commitMessage
    });

    return data.sha;
  }

  /**
   * Get pull request files and diff
   */
  async getPullRequestFiles(owner: string, repo: string, pullNumber: number): Promise<any[]> {
    const { data } = await this.octokit.pulls.listFiles({
      owner,
      repo,
      pull_number: pullNumber
    });

    return data.map(file => ({
      filename: file.filename,
      status: file.status,
      additions: file.additions,
      deletions: file.deletions,
      changes: file.changes,
      patch: file.patch
    }));
  }

  /**
   * Add labels to pull request
   */
  async addLabels(owner: string, repo: string, pullNumber: number, labels: string[]): Promise<void> {
    await this.octokit.issues.addLabels({
      owner,
      repo,
      issue_number: pullNumber,
      labels
    });
  }

  /**
   * Request reviewers
   */
  async requestReviewers(
    owner: string,
    repo: string,
    pullNumber: number,
    reviewers: string[],
    teamReviewers?: string[]
  ): Promise<void> {
    await this.octokit.pulls.requestReviewers({
      owner,
      repo,
      pull_number: pullNumber,
      reviewers,
      team_reviewers: teamReviewers
    });
  }

  /**
   * Check if pull request is mergeable
   */
  async isMergeable(owner: string, repo: string, pullNumber: number): Promise<boolean> {
    const { data } = await this.octokit.pulls.get({
      owner,
      repo,
      pull_number: pullNumber
    });

    return data.mergeable === true && data.mergeable_state === 'clean';
  }
}

GitHub Actions Integration: CI/CD Orchestration

GitHub Actions Workflow (YAML)

Production-ready GitHub Actions workflow for automated testing, building, and deployment triggered by ChatGPT commands.

name: ChatGPT Triggered Deployment

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Deployment environment'
        required: true
        type: choice
        options:
          - development
          - staging
          - production
      version:
        description: 'Release version'
        required: true
        type: string
      skip_tests:
        description: 'Skip test suite'
        required: false
        type: boolean
        default: false

  repository_dispatch:
    types: [chatgpt-deploy]

  push:
    branches: [main, develop]
    tags: ['v*']

  pull_request:
    branches: [main, develop]

env:
  NODE_VERSION: '20.x'
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  validate:
    name: Validate Code
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Lint code
        run: npm run lint

      - name: Type check
        run: npm run type-check

  test:
    name: Run Tests
    runs-on: ubuntu-latest
    if: ${{ !inputs.skip_tests }}
    needs: validate
    strategy:
      matrix:
        test-suite: [unit, integration, e2e]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run ${{ matrix.test-suite }} tests
        run: npm run test:${{ matrix.test-suite }}
        env:
          CI: true

      - name: Upload coverage
        uses: codecov/codecov-action@v3
        with:
          files: ./coverage/coverage-final.json
          flags: ${{ matrix.test-suite }}

  build:
    name: Build Application
    runs-on: ubuntu-latest
    needs: [validate, test]
    if: ${{ always() && (needs.test.result == 'success' || needs.test.result == 'skipped') }}
    outputs:
      version: ${{ steps.version.outputs.version }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build application
        run: npm run build
        env:
          NODE_ENV: production

      - name: Generate version
        id: version
        run: |
          if [ "${{ inputs.version }}" != "" ]; then
            echo "version=${{ inputs.version }}" >> $GITHUB_OUTPUT
          else
            echo "version=$(git describe --tags --always)" >> $GITHUB_OUTPUT
          fi

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist-${{ steps.version.outputs.version }}
          path: dist/
          retention-days: 30

  deploy:
    name: Deploy to ${{ inputs.environment || 'staging' }}
    runs-on: ubuntu-latest
    needs: build
    if: ${{ github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch' }}
    environment:
      name: ${{ inputs.environment || github.event.client_payload.environment || 'staging' }}
      url: ${{ steps.deploy.outputs.url }}
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist-${{ needs.build.outputs.version }}
          path: dist/

      - name: Deploy to environment
        id: deploy
        run: |
          echo "Deploying version ${{ needs.build.outputs.version }} to ${{ inputs.environment }}"
          echo "url=https://${{ inputs.environment }}.example.com" >> $GITHUB_OUTPUT

      - name: Notify ChatGPT
        uses: peter-evans/repository-dispatch@v2
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          event-type: deployment-complete
          client-payload: |
            {
              "environment": "${{ inputs.environment }}",
              "version": "${{ needs.build.outputs.version }}",
              "url": "${{ steps.deploy.outputs.url }}",
              "status": "success"
            }

Webhook Event Processor (TypeScript)

Process GitHub webhook events for real-time workflow automation in ChatGPT apps.

import { Octokit } from '@octokit/rest';
import * as crypto from 'crypto';

interface WebhookEvent {
  event: string;
  payload: any;
  signature: string;
  delivery: string;
}

interface WorkflowDispatchOptions {
  owner: string;
  repo: string;
  workflowId: string;
  ref: string;
  inputs?: Record<string, any>;
}

export class WebhookEventProcessor {
  private octokit: Octokit;
  private webhookSecret: string;

  constructor(octokit: Octokit, webhookSecret: string) {
    this.octokit = octokit;
    this.webhookSecret = webhookSecret;
  }

  /**
   * Verify webhook signature
   */
  verifySignature(payload: string, signature: string): boolean {
    const hmac = crypto.createHmac('sha256', this.webhookSecret);
    const digest = 'sha256=' + hmac.update(payload).digest('hex');

    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(digest)
    );
  }

  /**
   * Process webhook event
   */
  async processEvent(event: WebhookEvent): Promise<any> {
    const { event: eventType, payload } = event;

    switch (eventType) {
      case 'push':
        return this.handlePush(payload);
      case 'pull_request':
        return this.handlePullRequest(payload);
      case 'workflow_run':
        return this.handleWorkflowRun(payload);
      case 'deployment_status':
        return this.handleDeploymentStatus(payload);
      case 'issue_comment':
        return this.handleIssueComment(payload);
      default:
        console.log(`Unhandled event type: ${eventType}`);
        return null;
    }
  }

  /**
   * Trigger workflow dispatch
   */
  async triggerWorkflow(options: WorkflowDispatchOptions): Promise<void> {
    await this.octokit.actions.createWorkflowDispatch({
      owner: options.owner,
      repo: options.repo,
      workflow_id: options.workflowId,
      ref: options.ref,
      inputs: options.inputs
    });
  }

  /**
   * Get workflow run status
   */
  async getWorkflowRunStatus(owner: string, repo: string, runId: number): Promise<any> {
    const { data } = await this.octokit.actions.getWorkflowRun({
      owner,
      repo,
      run_id: runId
    });

    return {
      id: data.id,
      name: data.name,
      status: data.status,
      conclusion: data.conclusion,
      url: data.html_url,
      createdAt: data.created_at,
      updatedAt: data.updated_at
    };
  }

  private async handlePush(payload: any): Promise<void> {
    console.log(`Push to ${payload.ref} by ${payload.pusher.name}`);
    // Implement custom logic
  }

  private async handlePullRequest(payload: any): Promise<void> {
    console.log(`PR #${payload.number} ${payload.action}`);
    // Implement custom logic
  }

  private async handleWorkflowRun(payload: any): Promise<void> {
    console.log(`Workflow ${payload.workflow.name} ${payload.action}`);
    // Implement custom logic
  }

  private async handleDeploymentStatus(payload: any): Promise<void> {
    console.log(`Deployment ${payload.deployment.environment} ${payload.deployment_status.state}`);
    // Implement custom logic
  }

  private async handleIssueComment(payload: any): Promise<void> {
    console.log(`Comment on issue #${payload.issue.number}`);
    // Implement custom logic
  }
}

Learn more about webhook integration for ChatGPT apps and real-time event processing.

Advanced Features: GraphQL, Issues, and Security

GraphQL Query Builder (TypeScript)

Advanced GraphQL queries for complex GitHub data retrieval in ChatGPT apps.

import { graphql } from '@octokit/graphql';

interface GraphQLConfig {
  token: string;
  baseUrl?: string;
}

interface RepositoryQuery {
  owner: string;
  name: string;
  includePullRequests?: boolean;
  includeIssues?: boolean;
  includeDiscussions?: boolean;
}

export class GraphQLQueryBuilder {
  private graphqlClient: typeof graphql;

  constructor(config: GraphQLConfig) {
    this.graphqlClient = graphql.defaults({
      headers: {
        authorization: `token ${config.token}`
      },
      baseUrl: config.baseUrl
    });
  }

  /**
   * Query repository with nested data
   */
  async queryRepository(query: RepositoryQuery): Promise<any> {
    const result = await this.graphqlClient(
      `
        query($owner: String!, $name: String!) {
          repository(owner: $owner, name: $name) {
            id
            name
            description
            stargazerCount
            forkCount
            isPrivate
            defaultBranchRef {
              name
              target {
                ... on Commit {
                  oid
                  message
                  committedDate
                  author {
                    name
                    email
                  }
                }
              }
            }
            ${query.includePullRequests ? this.getPullRequestsFragment() : ''}
            ${query.includeIssues ? this.getIssuesFragment() : ''}
            ${query.includeDiscussions ? this.getDiscussionsFragment() : ''}
          }
        }
      `,
      {
        owner: query.owner,
        name: query.name
      }
    );

    return result.repository;
  }

  /**
   * Query pull requests with reviews
   */
  async queryPullRequestsWithReviews(owner: string, name: string): Promise<any> {
    const result = await this.graphqlClient(
      `
        query($owner: String!, $name: String!) {
          repository(owner: $owner, name: $name) {
            pullRequests(first: 20, states: OPEN, orderBy: {field: UPDATED_AT, direction: DESC}) {
              nodes {
                number
                title
                state
                author {
                  login
                }
                reviews(first: 10) {
                  nodes {
                    state
                    author {
                      login
                    }
                    body
                    submittedAt
                  }
                }
                commits(last: 1) {
                  nodes {
                    commit {
                      statusCheckRollup {
                        state
                      }
                    }
                  }
                }
              }
            }
          }
        }
      `,
      { owner, name }
    );

    return result.repository.pullRequests.nodes;
  }

  private getPullRequestsFragment(): string {
    return `
      pullRequests(first: 10, states: OPEN) {
        nodes {
          number
          title
          state
          author {
            login
          }
        }
      }
    `;
  }

  private getIssuesFragment(): string {
    return `
      issues(first: 10, states: OPEN) {
        nodes {
          number
          title
          state
          author {
            login
          }
        }
      }
    `;
  }

  private getDiscussionsFragment(): string {
    return `
      discussions(first: 10) {
        nodes {
          title
          author {
            login
          }
        }
      }
    `;
  }
}

Issue Manager (TypeScript)

Comprehensive issue management including creation, labels, assignments, and project boards.

import { Octokit } from '@octokit/rest';

interface CreateIssueOptions {
  owner: string;
  repo: string;
  title: string;
  body?: string;
  assignees?: string[];
  labels?: string[];
  milestone?: number;
}

export class IssueManager {
  private octokit: Octokit;

  constructor(octokit: Octokit) {
    this.octokit = octokit;
  }

  /**
   * Create an issue
   */
  async createIssue(options: CreateIssueOptions): Promise<number> {
    const { owner, repo, title, body, assignees, labels, milestone } = options;

    const { data } = await this.octokit.issues.create({
      owner,
      repo,
      title,
      body,
      assignees,
      labels,
      milestone
    });

    return data.number;
  }

  /**
   * Update issue with AI-generated response
   */
  async updateIssue(
    owner: string,
    repo: string,
    issueNumber: number,
    updates: Partial<CreateIssueOptions>
  ): Promise<void> {
    await this.octokit.issues.update({
      owner,
      repo,
      issue_number: issueNumber,
      title: updates.title,
      body: updates.body,
      assignees: updates.assignees,
      labels: updates.labels,
      milestone: updates.milestone,
      state: 'open'
    });
  }

  /**
   * Add comment to issue
   */
  async addComment(owner: string, repo: string, issueNumber: number, body: string): Promise<void> {
    await this.octokit.issues.createComment({
      owner,
      repo,
      issue_number: issueNumber,
      body
    });
  }

  /**
   * Close issue with reason
   */
  async closeIssue(owner: string, repo: string, issueNumber: number, reason?: string): Promise<void> {
    await this.octokit.issues.update({
      owner,
      repo,
      issue_number: issueNumber,
      state: 'closed',
      state_reason: reason as any
    });
  }

  /**
   * Search issues with filters
   */
  async searchIssues(query: string): Promise<any[]> {
    const { data } = await this.octokit.search.issuesAndPullRequests({
      q: query,
      per_page: 50
    });

    return data.items;
  }
}

Code Scanner Integration (TypeScript)

Integrate GitHub Code Scanning and security alerts into ChatGPT workflows.

import { Octokit } from '@octokit/rest';

interface CodeScanningAlert {
  number: number;
  state: string;
  rule: {
    id: string;
    severity: string;
    description: string;
  };
  tool: {
    name: string;
    version: string;
  };
  mostRecentInstance: {
    location: {
      path: string;
      startLine: number;
      endLine: number;
    };
  };
}

export class CodeScannerIntegration {
  private octokit: Octokit;

  constructor(octokit: Octokit) {
    this.octokit = octokit;
  }

  /**
   * Get code scanning alerts
   */
  async getCodeScanningAlerts(
    owner: string,
    repo: string,
    state?: 'open' | 'closed' | 'dismissed'
  ): Promise<CodeScanningAlert[]> {
    const { data } = await this.octokit.codeScanning.listAlertsForRepo({
      owner,
      repo,
      state,
      per_page: 100
    });

    return data as any[];
  }

  /**
   * Dismiss code scanning alert
   */
  async dismissAlert(
    owner: string,
    repo: string,
    alertNumber: number,
    dismissedReason: string
  ): Promise<void> {
    await this.octokit.codeScanning.updateAlert({
      owner,
      repo,
      alert_number: alertNumber,
      state: 'dismissed',
      dismissed_reason: dismissedReason as any
    });
  }

  /**
   * Get Dependabot alerts
   */
  async getDependabotAlerts(owner: string, repo: string): Promise<any[]> {
    const { data } = await this.octokit.dependabot.listAlertsForRepo({
      owner,
      repo,
      per_page: 100
    });

    return data;
  }
}

Explore security best practices for ChatGPT apps to protect your integrations.

Release Manager (TypeScript)

Automate GitHub releases, tags, and changelog generation through ChatGPT.

import { Octokit } from '@octokit/rest';

interface CreateReleaseOptions {
  owner: string;
  repo: string;
  tagName: string;
  name: string;
  body?: string;
  draft?: boolean;
  prerelease?: boolean;
  targetCommitish?: string;
}

export class ReleaseManager {
  private octokit: Octokit;

  constructor(octokit: Octokit) {
    this.octokit = octokit;
  }

  /**
   * Create a release
   */
  async createRelease(options: CreateReleaseOptions): Promise<number> {
    const { data } = await this.octokit.repos.createRelease({
      owner: options.owner,
      repo: options.repo,
      tag_name: options.tagName,
      name: options.name,
      body: options.body,
      draft: options.draft ?? false,
      prerelease: options.prerelease ?? false,
      target_commitish: options.targetCommitish
    });

    return data.id;
  }

  /**
   * Upload release asset
   */
  async uploadAsset(
    owner: string,
    repo: string,
    releaseId: number,
    filename: string,
    data: Buffer
  ): Promise<void> {
    await this.octokit.repos.uploadReleaseAsset({
      owner,
      repo,
      release_id: releaseId,
      name: filename,
      data: data as any
    });
  }

  /**
   * Generate release notes
   */
  async generateReleaseNotes(
    owner: string,
    repo: string,
    tagName: string,
    previousTagName?: string
  ): Promise<string> {
    const { data } = await this.octokit.repos.generateReleaseNotes({
      owner,
      repo,
      tag_name: tagName,
      previous_tag_name: previousTagName
    });

    return data.body;
  }
}

Project Board Automation (TypeScript)

Automate GitHub Projects (beta) with custom workflows triggered by ChatGPT.

import { graphql } from '@octokit/graphql';

export class ProjectBoardAutomation {
  private graphqlClient: typeof graphql;

  constructor(token: string) {
    this.graphqlClient = graphql.defaults({
      headers: { authorization: `token ${token}` }
    });
  }

  /**
   * Add issue to project board
   */
  async addIssueToProject(projectId: string, issueId: string): Promise<void> {
    await this.graphqlClient(
      `
        mutation($projectId: ID!, $contentId: ID!) {
          addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) {
            item {
              id
            }
          }
        }
      `,
      { projectId, contentId: issueId }
    );
  }

  /**
   * Update project item field
   */
  async updateProjectField(
    projectId: string,
    itemId: string,
    fieldId: string,
    value: string
  ): Promise<void> {
    await this.graphqlClient(
      `
        mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: String!) {
          updateProjectV2ItemFieldValue(
            input: {
              projectId: $projectId
              itemId: $itemId
              fieldId: $fieldId
              value: {text: $value}
            }
          ) {
            projectV2Item {
              id
            }
          }
        }
      `,
      { projectId, itemId, fieldId, value }
    );
  }
}

Build Your GitHub ChatGPT App Today

GitHub API integration transforms developer workflows with intelligent automation, conversational code reviews, and seamless CI/CD orchestration. Whether you're building a code assistant, release automation tool, or DevOps chatbot, GitHub's REST and GraphQL APIs provide the foundation for powerful ChatGPT apps.

Ready to automate your GitHub workflows?

Start building with MakeAIHQ — the no-code platform for creating production-ready ChatGPT apps with GitHub integration. From zero to ChatGPT App Store in 48 hours, no coding required.

Related Resources

External Resources