0Pricing
AI Agents · Lesson

Listing and Managing Issues

Fetching, creating, labeling, and closing issues programmatically.

Listing and Managing Issues is a free AI Agents lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Getting Issues from a Repository

Use repo.get_issues() to list issues. By default it returns open issues; pass state='closed' or state='all' for other states. The result is a PaginatedList — iterate over it to process each issue.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# Open issues (default)
open_issues = repo.get_issues(state='open')
print(f'Open issues: {open_issues.totalCount}')

# Process first 20
for issue in open_issues[:20]:
    print(f'#{issue.number}: {issue.title}')
    print(f'  Labels: {[l.name for l in issue.labels]}')
    print(f'  Assignee: {issue.assignee.login if issue.assignee else None}')
    print(f'  Created: {issue.created_at.date()}')

Filtering Issues

get_issues() supports several filter parameters: state, labels, assignee, milestone, since, and sort. Combine them to get exactly the issues your agent needs to process.

import datetime
from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# Issues with the 'bug' label, sorted by newest
bug_issues = repo.get_issues(
    state='open',
    labels=['bug'],
    sort='created',
    direction='desc'
)

# Issues updated in the last 7 days
cutoff = datetime.datetime.now() - datetime.timedelta(days=7)
recent_issues = repo.get_issues(
    state='open',
    since=cutoff
)

# Issues assigned to a specific user
my_issues = repo.get_issues(
    state='open',
    assignee='username'
)

print(f'Bug issues: {bug_issues.totalCount}')
print(f'Recent issues: {recent_issues.totalCount}')

Accessing Issue Properties

Each Issue object has rich properties: number, title, body, labels, assignees, milestone, state, comments count, and timestamps. Access them as Python attributes. The body is raw Markdown text.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')
issue = repo.get_issue(42)  # get by number

print(f'Number: #{issue.number}')
print(f'Title: {issue.title}')
print(f'State: {issue.state}')        # 'open' or 'closed'
print(f'Author: {issue.user.login}')
print(f'Body length: {len(issue.body or "")}')
print(f'Labels: {[l.name for l in issue.labels]}')
print(f'Assignees: {[a.login for a in issue.assignees]}')
print(f'Milestone: {issue.milestone.title if issue.milestone else None}')
print(f'Comments: {issue.comments}')
print(f'Reactions: {issue.get_reactions().totalCount}')
print(f'URL: {issue.html_url}')

Creating New Issues

Use repo.create_issue() to create a new issue programmatically. The only required field is title. Add body (Markdown), labels (must already exist), assignees (GitHub usernames), and milestone (milestone object).

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# Create a bug report
bug_body = (
    '## Bug Report\n\n'
    '**Observed:** Login fails with 500 error\n'
    '**Expected:** Successful login\n'
    '**Steps to reproduce:**\n'
    '1. Navigate to /login\n'
    '2. Enter valid credentials\n'
    '3. Click Submit\n\n'
    '**Environment:** Production, v2.3.1'
)

issue = repo.create_issue(
    title='Login endpoint returns 500 for valid credentials',
    body=bug_body,
    labels=['bug', 'priority:high'],
    assignees=['alice'],       # must be repo collaborators
)

print(f'Created issue #{issue.number}: {issue.html_url}')

Editing (Updating) Issues

Use issue.edit() to update any property of an existing issue. You can change the title, body, state, labels, assignees, or milestone in a single call. Pass only the fields you want to change — other fields are preserved.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')
issue = repo.get_issue(42)

# Update title and add new labels
issue.edit(
    title='[URGENT] Login endpoint returns 500',
    labels=['bug', 'priority:critical', 'needs-hotfix']
)

# Close the issue
issue.edit(state='closed')
print(f'Issue #{issue.number} closed')

# Reopen it
issue.edit(state='open')

# Assign to a user
from github import NamedUser
issue.edit(assignees=['bob', 'carol'])

# Update the body
issue.edit(body=issue.body + '\n\n**Update:** Hotfix deployed to production.')

Managing Labels

Labels organize issues. Get all repo labels with repo.get_labels(), create new ones with repo.create_label(), and add/remove labels on an issue with issue.add_to_labels() and issue.remove_from_labels().

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

# List all labels
for label in repo.get_labels():
    print(f'{label.name}: #{label.color}')

# Create a new label if it doesn't exist
existing_names = {l.name for l in repo.get_labels()}
if 'agent-reviewed' not in existing_names:
    repo.create_label(
        name='agent-reviewed',
        color='0075ca',       # hex without #
        description='Reviewed by AI agent'
    )
    print('Created label: agent-reviewed')

# Add a label to an issue
issue = repo.get_issue(42)
issue.add_to_labels('agent-reviewed')

# Remove a label
issue.remove_from_labels('needs-triage')

Reading Issue Comments

Use issue.get_comments() to retrieve all comments on an issue. Each comment has an author (user.login), body text, and timestamps. Iterate in order to see the conversation history.

from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')
issue = repo.get_issue(42)

# Get all comments
comments = list(issue.get_comments())
print(f'Comments on #{issue.number}: {len(comments)}')

for comment in comments:
    print(f'\n{comment.user.login} ({comment.created_at.date()}):')
    print(comment.body[:200])

# Get only recent comments
for comment in issue.get_comments(since=cutoff):
    print(f'Recent: {comment.user.login}: {comment.body[:100]}')

Adding Comments to Issues

Use issue.create_comment(body) to post a comment. The body supports Markdown. Agent comments should clearly identify themselves as automated — include an "🤖 Automated analysis" header to set expectations.

from github import Github
import os
import datetime

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')
issue = repo.get_issue(42)

# Add an agent comment with clear attribution
agent_comment = (
    '**Automated Analysis** (via code-review agent)\n\n'
    '---\n'
    f'**Issue classified as:** Critical Bug\n'
    f'**Suggested priority:** P0\n'
    f'**Suggested assignee:** @backend-team\n\n'
    '**Analysis:**\n'
    'The login 500 error matches pattern #12 in our known issues database.\n'
    'Likely cause: database connection pool exhaustion during peak traffic.\n\n'
    '**Suggested fix:** Increase pool size in `db_config.py` or add circuit breaker.\n\n'
    f'_Generated at {datetime.datetime.now().strftime("%Y-%m-%d %H:%M UTC")}_'
)

comment = issue.create_comment(agent_comment)
print(f'Comment added: {comment.html_url}')

Bulk Issue Triage Agent

A triage agent automatically processes new issues: reads the title and body, classifies them via LLM, adds appropriate labels, assigns to the right team, and posts an initial comment. This saves engineers hours of manual triage work.

import anthropic
import json
import os
from github import Github

g = Github(token=os.environ['GITHUB_TOKEN'])
client = anthropic.Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])

def triage_issue(repo, issue):
    prompt = (
        'Classify this GitHub issue. Return JSON only:\n'
        '{"type": "bug|feature|question|docs", '
        '"priority": "critical|high|medium|low", '
        '"team": "backend|frontend|infra|ml", '
        '"summary": "one sentence"}\n\n'
        f'Title: {issue.title}\n'
        f'Body: {(issue.body or "")[:1000]}'
    )
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=200,
        messages=[{'role': 'user', 'content': prompt}]
    )
    try:
        return json.loads(response.content[0].text)
    except json.JSONDecodeError:
        return {'type': 'question', 'priority': 'medium', 'team': 'backend', 'summary': 'Needs manual review'}

Applying Triage Results to Issues

Apply the LLM triage classification to the issue: set labels based on type and priority, assign to the appropriate team lead, and post a triage comment. Track which issues have been triaged with a custom label to avoid re-processing.

TEAM_ASSIGNEES = {
    'backend': 'alice',
    'frontend': 'bob',
    'infra': 'carol',
    'ml': 'dave'
}

def apply_triage(repo, issue, classification):
    issue_type = classification.get('type', 'question')
    priority = classification.get('priority', 'medium')
    team = classification.get('team', 'backend')
    summary = classification.get('summary', '')

    # Apply labels
    labels_to_add = [f'type:{issue_type}', f'priority:{priority}', 'agent-triaged']
    issue.edit(labels=labels_to_add)

    # Assign to team lead
    assignee = TEAM_ASSIGNEES.get(team, 'alice')
    issue.edit(assignees=[assignee])

    # Post triage comment
    comment = (
        f'**Automated Triage**\n\n'
        f'Type: `{issue_type}` | Priority: `{priority}` | Team: `{team}`\n'
        f'Summary: {summary}\n\n'
        f'Assigned to @{assignee} for follow-up.'
    )
    issue.create_comment(comment)
    print(f'Triaged #{issue.number}: {issue_type}/{priority} -> {assignee}')

# --- demo: minimal stand-in for a GitHub Issue object ---
class _FakeIssue:
    number = 501
    def edit(self, **kwargs):
        print(f'[github] issue.edit({kwargs})')
    def create_comment(self, body):
        print(f'[github] comment posted:\n{body}')

classification = {'type': 'bug', 'priority': 'high', 'team': 'backend',
                   'summary': 'Login fails with 500 when email has a plus sign'}
apply_triage('coddy-agents', _FakeIssue(), classification)

Closing Stale Issues Automatically

Stale issue management is a common automation: find open issues with no activity for N days, post a warning comment, and close them if no response comes within a grace period. Use issue.updated_at to check activity and issue.edit(state='closed') to close.

import datetime
from github import Github
import os

g = Github(token=os.environ['GITHUB_TOKEN'])
repo = g.get_repo('myorg/myrepo')

STALE_DAYS = 90
GRACE_DAYS = 14

now = datetime.datetime.utcnow()
stale_cutoff = now - datetime.timedelta(days=STALE_DAYS)

for issue in repo.get_issues(state='open'):
    last_updated = issue.updated_at.replace(tzinfo=None)
    if last_updated > stale_cutoff:
        continue

    # Check if stale warning already posted
    comments = list(issue.get_comments())
    stale_warned = any('stale' in c.body.lower() for c in comments)

    if not stale_warned:
        issue.create_comment(
            'This issue has been inactive for 90 days. '
            'It will be closed in 14 days unless there is activity.'
        )
        issue.add_to_labels('stale')
        print(f'Stale warning: #{issue.number}')

Quick Check: issue.edit() vs create_issue()

Test your understanding of GitHub issue management.

Issue Management Recap

Your agent can now manage GitHub issues end-to-end:

  • repo.get_issues(state, labels, assignee, since) — filter and list issues
  • repo.get_issue(number) — get a specific issue by number
  • repo.create_issue(title, body, labels, assignees) — open a new issue
  • issue.edit(state, title, labels, assignees) — update any field
  • issue.create_comment(body) — add a Markdown comment
  • repo.create_label() / issue.add_to_labels() — manage labels
  • Always identify agent comments clearly to distinguish from human activity
  • Use 'agent-triaged' labels to prevent re-processing

Frequently asked questions

Is the “Listing and Managing Issues” lesson free?

Yes — the full text of “Listing and Managing Issues” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Listing and Managing Issues”?

Fetching, creating, labeling, and closing issues programmatically. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Listing and Managing Issues” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. GitHub REST API Overview
  2. Listing and Managing Issues
  3. Automated PR Review Comments
  4. Commit History and Diff Analysis
← Back to AI Agents