我如何使用 Python 和 GitHub Actions 构建每日连击记录器
发布: (2026年1月17日 GMT+8 07:06)
2 min read
原文: Dev.to
Source: Dev.to
思路
目标很简单:
- 获取每日一句(让 commit 更有意义)。
- 用新句子更新
README.md。 - 每天自动提交并推送更改。
技术栈
- Python – 用来获取句子并更新文件。
- GitHub Actions – 用于每天调度脚本运行。
代码
Python 脚本 (update_quote.py)
import requests
import datetime
def get_quote():
url = "https://dummyjson.com/quotes/random"
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return f"\"{data['quote']}\" — {data['author']}"
else:
return "Could not fetch a quote today. Keep coding!"
except Exception as e:
return f"Error fetching quote: {e}"
def update_readme(quote):
date_str = datetime.datetime.now().strftime("%Y-%m-%d")
# Template for the README
readme_content = f"""
🚀 Daily Streak Keeper
This repository automatically updates itself every day at 12:00 PM Nairobi Time to keep my GitHub contribution streak alive.
📅 Quote for {date_str}
> {quote}
---
Last updated automatically by GitHub Actions.
"""
with open("README.md", "w", encoding="utf-8") as file:
file.write(readme_content)
if __name__ == "__main__":
quote = get_quote()
update_readme(quote)
自动化工作流 (daily-quote.yml)
name: Daily Quote Update
on:
schedule:
# 09:00 UTC = 12:00 PM Nairobi Time
- cron: '0 9 * * *'
workflow_dispatch:
jobs:
update-readme:
runs-on: ubuntu-latest
permissions:
contents: write
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 -r requirements.txt
- name: Run Python script
run: |
python update_quote.py
- name: Commit and Push
run: |
git config --global user.name "Quote Bot"
git config --global user.email "${{ github.actor }}@users.noreply.github.com"
git add README.md
if git diff-index --quiet HEAD; then
echo "No changes to commit"
else
git commit -m "Daily Quote: Updated README with new inspiration 📜"
git push
fi
结论
这个小项目在保持我的个人资料活跃的同时,每天提供一句新颖的名言。它展示了 GitHub Actions 在自动化简单任务方面的强大与便捷。
查看仓库中的代码,随意 fork 来创建属于自己的 streak keeper 吧。