feat: add support for Mastodon, X/Twitter, and Facebook Page notifications

This commit is contained in:
poli0981 committed 2026-04-13 13:49:34 +07:00
1 parent 4b7c5d9d6f
commit 779499c1bf
3 files changed
+400 -13

No files matched your search

+15
View File
@@ -24,12 +24,27 @@ jobs:
- name: Run notification script
env:
# Required
YOUTUBE_CHANNEL_ID: ${{ secrets.YOUTUBE_CHANNEL_ID }}
# Telegram
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
# Bluesky
BLUESKY_HANDLE: ${{ secrets.BLUESKY_HANDLE }}
BLUESKY_APP_PASSWORD: ${{ secrets.BLUESKY_APP_PASSWORD }}
# Discord (optional)
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
# Mastodon (optional)
MASTODON_INSTANCE_URL: ${{ secrets.MASTODON_INSTANCE_URL }}
MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }}
# X / Twitter (optional)
X_API_KEY: ${{ secrets.X_API_KEY }}
X_API_SECRET: ${{ secrets.X_API_SECRET }}
X_ACCESS_TOKEN: ${{ secrets.X_ACCESS_TOKEN }}
X_ACCESS_SECRET: ${{ secrets.X_ACCESS_SECRET }}
# Facebook Page (optional)
FACEBOOK_PAGE_ID: ${{ secrets.FACEBOOK_PAGE_ID }}
FACEBOOK_PAGE_TOKEN: ${{ secrets.FACEBOOK_PAGE_TOKEN }}
run: python scripts/notify.py
- name: Commit state file
+156
View File
@@ -0,0 +1,156 @@
# 🆕 Hướng Dẫn Thiết Lập Platform Mới
---
## Mastodon
### Lấy Access Token
1. Đăng nhập Mastodon instance (e.g. `https://mastodon.social`)
2. Vào **Preferences → Development → New Application**
3. Tên: `YouTubeAutoPost`
4. Scopes: chỉ cần ✅ `write:statuses`
5. Submit → copy **Access Token**
### Secrets cần thêm
| Secret | Giá trị | Ví dụ |
|-------------------------|----------------------------------|---------------------------|
| `MASTODON_INSTANCE_URL` | URL instance (không có `/` cuối) | `https://mastodon.social` |
| `MASTODON_ACCESS_TOKEN` | Token từ bước trên | `abc123...` |
### Test nhanh
```bash
curl -X POST "https://mastodon.social/api/v1/statuses" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d "status=Test post from API&visibility=direct"
```
Dùng `visibility=direct` để test mà không public.
---
## X / Twitter
### Tạo App & Lấy Keys
1. Vào [developer.x.com](https://developer.x.com) → Developer Portal
2. Tạo Project + App (Free tier cho phép 1 app)
3. **User authentication settings**:
- App permissions: **Read and Write** ← quan trọng!
- Type of App: Web App
- Callback URL: `https://example.com` (placeholder, không dùng)
4. Vào **Keys and Tokens** tab:
- **API Key and Secret** → copy cả 2
- **Access Token and Secret** → Generate → copy cả 2
- ⚠️ Access Token phải được generate **sau** khi set Read and Write
### Secrets cần thêm
| Secret | Giá trị |
|-------------------|------------------------------|
| `X_API_KEY` | API Key (Consumer Key) |
| `X_API_SECRET` | API Secret (Consumer Secret) |
| `X_ACCESS_TOKEN` | Access Token |
| `X_ACCESS_SECRET` | Access Token Secret |
### Lưu ý
- Free tier: **1 tweet / 15 phút** — phù hợp vì workflow chạy mỗi 15 phút
- Nếu gặp 403: kiểm tra App permissions phải là **Read and Write**, sau đó **regenerate** Access Token
- API Key ≠ Bearer Token — script dùng OAuth 1.0a (4 keys), không dùng Bearer Token
---
## Facebook Page
### Lấy Page Access Token (Never-Expiring)
Quy trình hơi dài nhưng chỉ cần làm 1 lần:
#### Bước 1: Tạo Facebook App
1. Vào [developers.facebook.com](https://developers.facebook.com)
2. **My Apps → Create App** → chọn "Business" type
3. Thêm product: **Facebook Login for Business**
#### Bước 2: Lấy Short-Lived User Token
1. Vào [Graph API Explorer](https://developers.facebook.com/tools/explorer/)
2. Chọn app vừa tạo
3. Permissions cần thêm:
- `pages_manage_posts`
- `pages_read_engagement`
4. **Generate Access Token** → đăng nhập + cấp quyền
5. Copy token này (short-lived, 1-2 giờ)
#### Bước 3: Đổi sang Long-Lived User Token
```bash
curl "https://graph.facebook.com/v21.0/oauth/access_token?\
grant_type=fb_exchange_token&\
client_id=YOUR_APP_ID&\
client_secret=YOUR_APP_SECRET&\
fb_exchange_token=SHORT_LIVED_TOKEN"
```
Copy `access_token` trả về (long-lived, 60 ngày).
#### Bước 4: Lấy Never-Expiring Page Token
```bash
curl "https://graph.facebook.com/v21.0/me/accounts?\
access_token=LONG_LIVED_USER_TOKEN"
```
Tìm Page trong kết quả → copy `access_token` của Page đó.
Token này **không hết hạn** nếu User Token là long-lived.
#### Bước 5: Xác nhận token không hết hạn
```bash
curl "https://graph.facebook.com/v21.0/debug_token?\
input_token=PAGE_TOKEN&\
access_token=PAGE_TOKEN"
```
Kiểm tra `"expires_at": 0` hoặc `"data_access_expires_at"` rất xa → OK.
### Secrets cần thêm
| Secret | Giá trị |
|-----------------------|----------------------------------------------------------|
| `FACEBOOK_PAGE_ID` | Page ID (tìm trong Page Settings → About hoặc trong URL) |
| `FACEBOOK_PAGE_TOKEN` | Never-expiring Page Access Token từ bước 4 |
### Test nhanh
```bash
curl -X POST "https://graph.facebook.com/v21.0/PAGE_ID/feed" \
-d "message=Test post from API" \
-d "access_token=PAGE_TOKEN"
```
---
## Tổng Hợp Secrets
| Secret | Platform | Bắt buộc |
|-------------------------|-----------|----------|
| `YOUTUBE_CHANNEL_ID` | YouTube | ✅ |
| `TELEGRAM_BOT_TOKEN` | Telegram | ✅ |
| `TELEGRAM_CHAT_ID` | Telegram | ✅ |
| `BLUESKY_HANDLE` | Bluesky | ✅ |
| `BLUESKY_APP_PASSWORD` | Bluesky | ✅ |
| `DISCORD_WEBHOOK_URL` | Discord | Tuỳ chọn |
| `MASTODON_INSTANCE_URL` | Mastodon | Tuỳ chọn |
| `MASTODON_ACCESS_TOKEN` | Mastodon | Tuỳ chọn |
| `X_API_KEY` | X/Twitter | Tuỳ chọn |
| `X_API_SECRET` | X/Twitter | Tuỳ chọn |
| `X_ACCESS_TOKEN` | X/Twitter | Tuỳ chọn |
| `X_ACCESS_SECRET` | X/Twitter | Tuỳ chọn |
| `FACEBOOK_PAGE_ID` | Facebook | Tuỳ chọn |
| `FACEBOOK_PAGE_TOKEN` | Facebook | Tuỳ chọn |
Mỗi platform tự skip nếu không có secret tương ứng — không cần cấu hình tất cả cùng lúc. Thêm dần khi sẵn sàng.
+229 -13
View File
@@ -5,17 +5,25 @@ Polls YouTube RSS feed for new videos and posts to:
- Telegram (Bot API)
- Bluesky (AT Protocol)
- Discord (Webhook, optional)
- Mastodon (REST API, optional)
- X / Twitter (OAuth 1.0a, optional)
- Facebook Page (Graph API, optional)
"""
import os
import sys
import json
import re
import hmac
import hashlib
import base64
import time
import uuid
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.parse import urlencode, quote
from urllib.error import HTTPError, URLError
@@ -27,6 +35,14 @@ TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
BLUESKY_HANDLE = os.environ.get("BLUESKY_HANDLE", "")
BLUESKY_APP_PASSWORD = os.environ.get("BLUESKY_APP_PASSWORD", "")
DISCORD_WEBHOOK_URL = os.environ.get("DISCORD_WEBHOOK_URL", "").strip()
MASTODON_INSTANCE_URL = os.environ.get("MASTODON_INSTANCE_URL", "").strip().rstrip("/")
MASTODON_ACCESS_TOKEN = os.environ.get("MASTODON_ACCESS_TOKEN", "")
X_API_KEY = os.environ.get("X_API_KEY", "")
X_API_SECRET = os.environ.get("X_API_SECRET", "")
X_ACCESS_TOKEN = os.environ.get("X_ACCESS_TOKEN", "")
X_ACCESS_SECRET = os.environ.get("X_ACCESS_SECRET", "")
FACEBOOK_PAGE_ID = os.environ.get("FACEBOOK_PAGE_ID", "")
FACEBOOK_PAGE_TOKEN = os.environ.get("FACEBOOK_PAGE_TOKEN", "")
STATE_FILE = Path(__file__).parent.parent / "data" / "last_video.txt"
@@ -218,7 +234,6 @@ def post_bluesky(video: dict) -> bool:
# Build facets for the URL (makes it clickable)
url_start = text.index(video["url"])
url_end = url_start + len(video["url"])
url_bytes_start = len(text[:url_start].encode("utf-8"))
url_bytes_end = url_bytes_start + len(video["url"].encode("utf-8"))
@@ -290,18 +305,12 @@ def post_bluesky(video: dict) -> bool:
def normalize_webhook_url(url: str) -> str:
"""Normalize Discord webhook URL to the correct format."""
# Replace legacy discordapp.com with discord.com
url = url.replace("https://discordapp.com/", "https://discord.com/")
# Ensure URL uses /api/webhooks/ path
url = url.replace(
"https://discord.com/webhooks/",
"https://discord.com/api/webhooks/",
)
# Remove trailing slash
url = url.rstrip("/")
return url
@@ -313,13 +322,11 @@ def post_discord(video: dict) -> bool:
webhook_url = normalize_webhook_url(DISCORD_WEBHOOK_URL)
# Validate URL format
if "/api/webhooks/" not in webhook_url:
print(
f"[ERROR] Discord: invalid webhook URL format. "
f"Expected: https://discord.com/api/webhooks/ID/TOKEN"
)
print(f"[DEBUG] Got: {webhook_url[:60]}...")
return False
payload = json.dumps(
@@ -344,13 +351,11 @@ def post_discord(video: dict) -> bool:
try:
with urlopen(req, timeout=30) as resp:
# Discord returns 204 No Content on success
print(f"[OK] Discord: posted successfully (status {resp.status}).")
return True
except HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] Discord webhook: {e.code} — {body}")
if e.code == 403:
print(
"[HINT] 403 Forbidden — possible causes:\n"
@@ -363,13 +368,221 @@ def post_discord(video: dict) -> bool:
print("[HINT] 404 Not Found — webhook was deleted. Create a new one.")
elif e.code == 429:
print("[HINT] 429 Rate Limited — too many requests. Will retry next run.")
return False
except URLError as e:
print(f"[ERROR] Discord webhook: {e}")
return False
# ─── Mastodon (Optional) ─────────────────────────────────────────
def post_mastodon(video: dict) -> bool:
"""Post to Mastodon instance via REST API."""
if not MASTODON_INSTANCE_URL or not MASTODON_ACCESS_TOKEN:
print("[SKIP] Mastodon: missing instance URL or access token.")
return False
text = (
f"🎬 New Video / Video Mới\n\n"
f"{video['title']}\n\n"
f"▶️ {video['url']}\n\n"
f"#gaming #gameplay #nocommentary"
)
payload = urlencode({"status": text, "visibility": "public"}).encode("utf-8")
url = f"{MASTODON_INSTANCE_URL}/api/v1/statuses"
req = Request(
url,
data=payload,
headers={
"Authorization": f"Bearer {MASTODON_ACCESS_TOKEN}",
"User-Agent": "YouTubeAutoPost/1.0",
},
)
try:
with urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
if result.get("id"):
print(f"[OK] Mastodon: posted successfully (id: {result['id']}).")
return True
else:
print(f"[ERROR] Mastodon: unexpected response — {result}")
return False
except HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] Mastodon: {e.code} — {body}")
if e.code == 401:
print("[HINT] 401 Unauthorized — access token is invalid or revoked.")
elif e.code == 422:
print("[HINT] 422 — status might be too long or contain invalid content.")
return False
except URLError as e:
print(f"[ERROR] Mastodon: {e}")
return False
# ─── X / Twitter (Optional) ──────────────────────────────────────
def x_create_oauth_header(method: str, url: str, params: dict) -> str:
"""Create OAuth 1.0a Authorization header for X/Twitter API v2."""
oauth_params = {
"oauth_consumer_key": X_API_KEY,
"oauth_nonce": uuid.uuid4().hex,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": str(int(time.time())),
"oauth_token": X_ACCESS_TOKEN,
"oauth_version": "1.0",
}
# Combine all params for signature base
all_params = {**oauth_params, **params}
sorted_params = urlencode(sorted(all_params.items()))
# Create signature base string
base_string = f"{method}&{quote(url, safe='')}&{quote(sorted_params, safe='')}"
# Create signing key
signing_key = f"{quote(X_API_SECRET, safe='')}&{quote(X_ACCESS_SECRET, safe='')}"
# Generate signature
signature = base64.b64encode(
hmac.new(
signing_key.encode("utf-8"),
base_string.encode("utf-8"),
hashlib.sha1,
).digest()
).decode("utf-8")
oauth_params["oauth_signature"] = signature
# Build Authorization header
auth_header = "OAuth " + ", ".join(
f'{quote(k, safe="")}="{quote(v, safe="")}"'
for k, v in sorted(oauth_params.items())
)
return auth_header
def post_x(video: dict) -> bool:
"""Post to X/Twitter via API v2 with OAuth 1.0a."""
if not all([X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET]):
print("[SKIP] X/Twitter: missing API credentials.")
return False
text = (
f"🎬 New Video / Video Mới\n\n"
f"{video['title']}\n\n"
f"▶️ {video['url']}\n\n"
f"#gaming #gameplay #nocommentary"
)
# X/Twitter API v2 endpoint
url = "https://api.x.com/2/tweets"
body = json.dumps({"text": text})
auth_header = x_create_oauth_header("POST", url, {})
req = Request(
url,
data=body.encode("utf-8"),
headers={
"Authorization": auth_header,
"Content-Type": "application/json",
"User-Agent": "YouTubeAutoPost/1.0",
},
)
try:
with urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
tweet_id = result.get("data", {}).get("id", "")
if tweet_id:
print(f"[OK] X/Twitter: posted successfully (id: {tweet_id}).")
return True
else:
print(f"[ERROR] X/Twitter: unexpected response — {result}")
return False
except HTTPError as e:
body_text = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] X/Twitter: {e.code} — {body_text}")
if e.code == 401:
print("[HINT] 401 — OAuth credentials are invalid or expired.")
elif e.code == 403:
print(
"[HINT] 403 — app may lack write permissions. "
"Check: Developer Portal → App → User authentication settings → "
"App permissions = Read and Write."
)
elif e.code == 429:
print("[HINT] 429 — rate limited. Free tier: 1 tweet / 15 min.")
return False
except URLError as e:
print(f"[ERROR] X/Twitter: {e}")
return False
# ─── Facebook Page (Optional) ────────────────────────────────────
def post_facebook(video: dict) -> bool:
"""Post to Facebook Page via Graph API."""
if not FACEBOOK_PAGE_ID or not FACEBOOK_PAGE_TOKEN:
print("[SKIP] Facebook: missing page ID or access token.")
return False
text = (
f"🎬 New Video / Video Mới\n\n"
f"{video['title']}\n\n"
f"▶️ {video['url']}"
)
url = f"https://graph.facebook.com/v21.0/{FACEBOOK_PAGE_ID}/feed"
payload = urlencode(
{
"message": text,
"link": video["url"],
"access_token": FACEBOOK_PAGE_TOKEN,
}
).encode("utf-8")
req = Request(
url,
data=payload,
headers={"User-Agent": "YouTubeAutoPost/1.0"},
)
try:
with urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
post_id = result.get("id", "")
if post_id:
print(f"[OK] Facebook: posted successfully (id: {post_id}).")
return True
else:
print(f"[ERROR] Facebook: unexpected response — {result}")
return False
except HTTPError as e:
body_text = e.read().decode("utf-8", errors="replace")
print(f"[ERROR] Facebook: {e.code} — {body_text}")
if e.code == 190 or "OAuthException" in body_text:
print(
"[HINT] Token expired. Facebook Page tokens need to be refreshed.\n"
" → Use a long-lived token (60 days) or a never-expiring page token.\n"
" → Guide: Graph API Explorer → Get Page Access Token → Extend."
)
elif e.code == 403:
print("[HINT] 403 — app may lack pages_manage_posts permission.")
return False
except URLError as e:
print(f"[ERROR] Facebook: {e}")
return False
# ─── Main ─────────────────────────────────────────────────────────
@@ -398,6 +611,9 @@ def main() -> None:
"telegram": post_telegram(video),
"bluesky": post_bluesky(video),
"discord": post_discord(video),
"mastodon": post_mastodon(video),
"x_twitter": post_x(video),
"facebook": post_facebook(video),
}
# Save state only if at least one post succeeded