Update Currency Rates and Posts #1
This file contains hidden or 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
| # .github/workflows/update_rates.yml | |
| name: Update Currency Rates | |
| on: | |
| schedule: | |
| - cron: '0 */12 * * *' | |
| workflow_dispatch: | |
| jobs: | |
| update-rates: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Check out repo | |
| uses: actions/checkout@v4 | |
| - name: Set up Python | |
| uses: actions/setup-python@v5 | |
| with: | |
| python-version: '3.10' | |
| - name: Install dependencies | |
| run: pip install requests pyyaml | |
| - name: Fetch rates and write to file | |
| env: | |
| API_KEY: ${{ secrets.CURRENCY_API_KEY }} # Securely access the API key | |
| run: | | |
| import os | |
| import requests | |
| import yaml | |
| from datetime import datetime, timezone | |
| # Fetch the API key from environment variables | |
| api_key = os.environ['API_KEY'] | |
| url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/PKR" | |
| # Make the API call | |
| response = requests.get(url) | |
| response.raise_for_status() # This will raise an error for a bad response (4xx or 5xx) | |
| data = response.json() | |
| # Prepare the data structure for the YAML file | |
| output_data = { | |
| 'last_updated_utc': datetime.now(timezone.utc).isoformat(), | |
| 'rates': data['conversion_rates'] | |
| } | |
| # Write the data to the _data/rates.yml file | |
| with open('_data/rates.yml', 'w') as f: | |
| yaml.dump(output_data, f) | |
| print("Successfully updated _data/rates.yml") | |
| # Step 5: Commit the updated rates.yml file back to your repository | |
| - name: Commit and push if changed | |
| uses: stefanzweifel/git-auto-commit-action@v5 | |
| with: | |
| commit_message: "Automated: Update currency exchange rates" | |
| file_pattern: "_data/rates.yml" | |
| commit_user_name: "GitHub Actions Bot" | |
| commit_user_email: "github-actions-bot@users.noreply.github.com" |