GitHub Actions如何让Issue过期后自动关闭?触发条件没生效?
我在项目里想用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确实超过一周没更新了,可能哪里写错了条件?
第一,
per_page: 0这个参数写错了,GitHub API 不会返回任何数据。应该改成per_page: 100,这是单次请求能获取的最大数量。如果 Issue 超过 100 条,你还需要处理分页,不过先解决基本问题。第二,
github.issues.update缺少必要的参数owner和repo,调用会失败。需要从context.repo里取这些信息。改完的代码如下:
几点说明:
1. 换成
github.paginate处理分页,避免 Issue 数量超过 100 时漏掉。2. 时间判断逻辑没问题,但确保时区一致,GitHub API 返回的时间是 UTC。
3. 如果还是有问题,检查 Actions 的权限设置,确保 token 有操作 Issue 的权限。
试一下这个版本,应该能正常触发了。