Collect Traffic Data #57
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Collect Traffic Data | |
on: | |
schedule: | |
- cron: "0 0 * * *" | |
workflow_dispatch: | |
permissions: | |
contents: write | |
jobs: | |
collect-traffic: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v4 | |
- name: Set up Python | |
uses: actions/setup-python@v4 | |
with: | |
python-version: "3.x" | |
- name: Install dependencies | |
run: pip install requests | |
- name: Collect traffic data | |
run: | | |
python3 -c " | |
import json, os | |
from datetime import datetime, timedelta | |
import requests | |
repo = 'ExpTechTW/trem-plugins' | |
api_url = f'https://api.github.com/repos/{repo}/traffic/views' | |
headers = { | |
'Authorization': f'Bearer {os.environ['GITHUB_TOKEN']}', | |
'Accept': 'application/vnd.github.v3+json' | |
} | |
response = requests.get(api_url, headers=headers) | |
new_data = response.json() | |
new_data['collected_at'] = datetime.utcnow().isoformat() | |
# 確保 data 目錄存在 | |
os.makedirs('data', exist_ok=True) | |
# 讀取現有數據或創建新的 | |
if os.path.exists('data/traffic.json'): | |
with open('data/traffic.json', 'r') as f: | |
existing_data = json.load(f) | |
else: | |
existing_data = new_data | |
# 判斷是否需要更新數據 | |
if 'views' in existing_data and existing_data['views']: | |
last_date = datetime.fromisoformat(existing_data['collected_at']) | |
if datetime.utcnow() - last_date > timedelta(hours=12): | |
existing_data = new_data | |
else: | |
existing_data = new_data | |
# 保存數據 | |
with open('data/traffic.json', 'w') as f: | |
json.dump(existing_data, f, separators=(',', ':')) | |
" | |
env: | |
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }} | |
- name: Commit and push if changes | |
run: | | |
git config --local user.email "github-actions[bot]@users.noreply.github.com" | |
git config --local user.name "github-actions[bot]" | |
git add data/traffic.json | |
git commit -m "Update traffic data" || exit 0 | |
git push |