0Pricing
AI Agents · 课时

列出与管理问题

以编程方式获取、创建、添加标签和关闭问题。

列出与管理问题 是 CoddyKit 上的免费 AI Agents 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。

从仓库获取问题

使用 repo.get_issues() 列出问题。默认情况下,它会返回未关闭的问题;传入 state='closed' 或 state='all' 可获取其他状态的问题。结果是一个 PaginatedList,请遍历它来处理每个问题。

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()}')

筛选问题

get_issues() 支持多个筛选参数:state、labels、assignee、milestone、since 和 sort。组合使用这些参数,即可准确获取代理需要处理的问题。

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}')

访问问题属性

每个 Issue 对象都具有丰富的属性:编号、标题、正文、标签、受指派者、里程碑、状态、评论数量和时间戳。请将它们作为 Python 属性访问。正文是原始 Markdown 文本。

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}')

创建新问题

使用 repo.create_issue() 以编程方式创建新问题。唯一必需的字段是 title。您还可以添加 body(Markdown)、labels(必须已存在)、assignees(GitHub 用户名)和 milestone(里程碑对象)。

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}')

编辑(更新)问题

使用 issue.edit() 更新现有问题的任意属性。您可以在一次调用中更改标题、正文、状态、标签、受指派者或里程碑。只需传入要更改的字段,其他字段会保留不变。

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.')

管理标签

标签用于整理问题。使用 repo.get_labels() 获取仓库中的所有标签,使用 repo.create_label() 创建新标签,并使用 issue.add_to_labels() 和 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')

读取问题评论

使用 issue.get_comments() 获取问题的所有评论。每条评论都包含作者(user.login)、正文和时间戳。请按顺序遍历评论,以查看对话历史。

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]}')

向问题添加评论

使用 issue.create_comment(body) 发布评论。正文支持 Markdown。代理评论应明确表明其为自动生成的评论——请加入“🤖 Automated analysis”标题,以便读者了解这一点。

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}')

批量问题分诊代理

分诊代理会自动处理新问题:读取标题和正文,通过 LLM 对其分类,添加适当的标签,分配给合适的团队,并发布初始评论。这样可以为工程师节省数小时的手动分诊工作。

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'}

将分诊结果应用到问题

将 LLM 的分诊分类应用到问题:根据类型和优先级设置标签,分配给合适的团队负责人,并发布分诊评论。请使用自定义标签跟踪已完成分诊的问题,以避免重复处理。

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)

自动关闭长期未处理的问题

管理长期未处理的问题是一种常见的自动化任务:找出连续 N 天没有活动的未关闭问题,发布警告评论,并在宽限期内没有收到回复时将其关闭。使用 issue.updated_at 检查活动情况,并使用 issue.edit(state='closed') 关闭问题。

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}')

快速检查:issue.edit() 与 create_issue()

测试您对 GitHub 问题管理的理解。

问题管理回顾

现在您的代理可以端到端地管理 GitHub 问题:

  • repo.get_issues(state, labels, assignee, since)——筛选并列出问题
  • repo.get_issue(number)——按编号获取特定问题
  • repo.create_issue(title, body, labels, assignees)——创建新问题
  • issue.edit(state, title, labels, assignees)——更新任意字段
  • issue.create_comment(body)——添加 Markdown 评论
  • repo.create_label() / issue.add_to_labels()——管理标签
  • 始终明确标识代理评论,以便将其与人工活动区分开来
  • 使用 'agent-triaged' 标签防止重复处理

常见问题解答

「列出与管理问题」课时是免费的吗?

是的 — 「列出与管理问题」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。

「列出与管理问题」这节课中我会学到什么?

以编程方式获取、创建、添加标签和关闭问题。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Agents 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「列出与管理问题」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Agents 课中编写并运行代码吗?

能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. GitHub REST API 概览
  2. 列出与管理问题
  3. 自动化 PR 审查评论
  4. 提交历史与差异分析
← 返回 AI Agents