GitHub Actions如何让Issue过期后自动关闭?触发条件没生效?

Zz玉茂 阅读 31

我在项目里想用GitHub Actions实现Issue过期7天未更新自动关闭,但设置后根本没触发。按照教程用了actions/github-script,检查了时间条件逻辑也没问题,但日志显示没找到符合条件的Issue。这是哪里出错了?

代码配置是这样的:

name: Close Stale Issues
on:
  schedule:
    - cron: "0 0 * * *"
jobs:
  close-stale-issues:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v6
        with:
          script: |
            const issues = await github.issues.listForRepo({
              repo: context.repo.repo,
              state: 'open',
              filter: 'updated',
              direction: 'asc',
              per_page: 0
            });
            const cutoffDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
            issues.data.forEach(issue => {
              if (new Date(issue.updated_at) < cutoffDate) {
                github.issues.update({
                  issue_number: issue.number,
                  state: 'closed'
                });
              }
            });

测试过手动触发工作流,脚本能获取到Issue列表,但执行时if (new Date(issue.updated_at) < cutoffDate)判断总是返回false。明明有些Issue确实超过一周没更新了,可能哪里写错了条件?

我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
小莉霞
小莉霞 Lv1
问题出在两个地方,改一下就行。

第一,per_page: 0 这个参数写错了,GitHub API 不会返回任何数据。应该改成 per_page: 100,这是单次请求能获取的最大数量。如果 Issue 超过 100 条,你还需要处理分页,不过先解决基本问题。

第二,github.issues.update 缺少必要的参数 ownerrepo,调用会失败。需要从 context.repo 里取这些信息。

改完的代码如下:

name: Close Stale Issues
on:
schedule:
- cron: "0 0 * * *"
jobs:
close-stale-issues:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v6
with:
script: |
const cutoffDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const issues = await github.paginate(github.issues.listForRepo, {
repo: context.repo.repo,
owner: context.repo.owner,
state: 'open',
sort: 'updated',
direction: 'asc',
per_page: 100
});
for (const issue of issues) {
if (new Date(issue.updated_at) < cutoffDate) {
await github.issues.update({
...context.repo,
issue_number: issue.number,
state: 'closed'
});
}
};


几点说明:
1. 换成 github.paginate 处理分页,避免 Issue 数量超过 100 时漏掉。
2. 时间判断逻辑没问题,但确保时区一致,GitHub API 返回的时间是 UTC。
3. 如果还是有问题,检查 Actions 的权限设置,确保 token 有操作 Issue 的权限。

试一下这个版本,应该能正常触发了。
点赞 1
2026-02-14 18:00