Build and deploy a Telegram bot on Google Cloud Functions to monitor Facebook ad accounts with automated daily reports, hourly critical alerts, and on-demand queries via interactive inline buttons.
This skill has safety concerns that you should review before use. Some patterns were detected that may pose a risk.Safety score: 75/100.
KillerSkills scans all public content for safety. Use caution before installing or executing flagged content.
Build a serverless Telegram bot deployed on Google Cloud Functions that monitors Facebook advertising accounts. The bot provides automated daily reports at 10:00 UTC+6, hourly critical status checks, and on-demand account information via Telegram inline buttons.
Creates a complete serverless monitoring solution with three Google Cloud Functions:
1. **Daily Report Function** - Scheduled comprehensive status report at 10:00 UTC+6 (04:00 UTC)
2. **Hourly Check Function** - Real-time alerts for critical issues (blocks, spending violations, payment issues)
3. **Telegram Webhook Function** - Interactive bot interface with inline keyboard callbacks
The system monitors multiple Facebook ad accounts in parallel, caches data for 5 minutes, and sends structured reports via Telegram with formatted tables and status emojis.
1. **Create project directory structure**
```
fb-ad-monitor/
├── main.py # Cloud Functions entry points
├── facebook_client.py # Facebook Marketing API client
├── telegram_client.py # Telegram Bot API client
├── requirements.txt # Python dependencies
├── deploy.sh # Deployment automation script
├── .gcloudignore # Files to exclude from deployment
└── README.md # Documentation
```
2. **Initialize requirements.txt** with dependencies:
```
requests==2.31.0
facebook-business==18.0.0
python-telegram-bot==20.6
google-cloud-secret-manager==2.16.4
google-cloud-logging==3.8.0
```
3. **Define monitored Facebook accounts** in `main.py`:
```python
FB_ACCOUNTS = [
'1295277935230804', # KZ Astana
'160299730351768', # KZ Almaty
'1779179689511929', # JM_Tanuki_Almaty
'349938931436634', # kaspiika uz
'564758959363164', # bella ciao rest
'848382079950987' # Tanuki UZ
]
```
4. **Implement `facebook_client.py`** with:
- **Account status endpoint**: `/{account_id}?fields=account_status,balance,spend_cap,amount_spent`
- **Spending insights endpoint**: `/{account_id}/insights?time_range={yesterday|last_7d|last_30d}&fields=spend`
- **Activities/errors endpoint**: `/{account_id}/activities?fields=event_type,extra_data`
- **Parallel requests** using `concurrent.futures.ThreadPoolExecutor`
- **5-minute in-memory cache** with timestamp invalidation
- **Rate limiting** to respect Facebook API quotas (200 calls/hour per user)
- **Request timeouts** (10s connection, 30s read) and exponential backoff retry (3 attempts)
5. **Add helper functions**:
- `get_account_status(account_ids)` - Returns dict of account statuses, balances, spend caps
- `get_spending(account_ids, period)` - Returns spending for yesterday/week/month
- `get_critical_issues(account_ids)` - Returns list of blocks, violations, payment issues
- `get_moderation_errors(account_ids)` - Returns current moderation warnings
6. **Implement `telegram_client.py`** with:
- **Main menu inline keyboard**:
```
📈 Account Status | 💰 Balances
📊 Spending | ⚠️ Errors
🔄 Refresh
```
- **Spending submenu** (triggered by 📊 button):
```
Yesterday | This Week | This Month
← Back to Main Menu
```
- **Callback query handler** for button interactions (e.g., `callback_data="spending_yesterday"`)
- **Message formatters**:
- Daily report: Markdown table with account name, status emoji, balance, yesterday spend, limit
- Critical alert: Bold header + bulleted list of issues
- Balance view: Sorted by debt (descending), color-coded emojis (🟢 positive, 🔴 negative)
- Error view: Grouped by account with moderation codes
7. **Add access control**:
- Environment variable `TELEGRAM_CHAT_ID` whitelist
- Reject messages/callbacks from unauthorized chat IDs
8. **Implement `main.py` with three functions**:
**A. Daily Report Function**
```python
def daily_report(event, context):
"""Triggered by Cloud Scheduler at 04:00 UTC (10:00 UTC+6)"""
# 1. Fetch all account statuses, balances, yesterday spending
# 2. Format as comprehensive Markdown table
# 3. Send via Telegram to TELEGRAM_CHAT_ID
# 4. Log execution to Cloud Logging
```
**B. Hourly Check Function**
```python
def hourly_check(event, context):
"""Triggered by Cloud Scheduler every hour"""
# 1. Call get_critical_issues() for all accounts
# 2. If any critical issues found:
# - Format as urgent alert with 🚨 emoji
# - Send immediately to Telegram
# 3. Log check result (issues found or all clear)
```
**C. Telegram Webhook Function**
```python
def telegram_webhook(request):
"""HTTP-triggered function for Telegram bot interactions"""
# 1. Parse incoming update (message or callback_query)
# 2. Verify chat ID against whitelist
# 3. If callback_query:
# - Handle button actions (status, balances, spending_*, errors, refresh)
# - Answer callback to remove loading state
# - Edit original message with new data + inline keyboard
# 4. If message (/start, /help, or unknown):
# - Send main menu with inline keyboard
# 5. Return 200 OK
```
9. **Store secrets in Secret Manager**:
```bash
echo -n "YOUR_FB_TOKEN" | gcloud secrets create fb-access-token --data-file=-
echo -n "YOUR_TELEGRAM_BOT_TOKEN" | gcloud secrets create telegram-bot-token --data-file=-
echo -n "YOUR_CHAT_ID" | gcloud secrets create telegram-chat-id --data-file=-
```
10. **Update Cloud Functions to read secrets**:
```python
from google.cloud import secretmanager
def get_secret(secret_id):
client = secretmanager.SecretManagerServiceClient()
name = f"projects/{PROJECT_ID}/secrets/{secret_id}/versions/latest"
response = client.access_secret_version(request={"name": name})
return response.payload.data.decode("UTF-8")
```
11. **Deploy Cloud Functions** with `deploy.sh`:
```bash
#!/bin/bash
# Deploy daily report function
gcloud functions deploy daily-report \
--runtime python39 \
--trigger-topic daily-report-topic \
--entry-point daily_report \
--memory 512MB \
--timeout 300s \
--region us-central1 \
--service-account fb-monitor-sa@PROJECT_ID.iam.gserviceaccount.com
# Deploy hourly check function
gcloud functions deploy hourly-check \
--runtime python39 \
--trigger-topic hourly-check-topic \
--entry-point hourly_check \
--memory 256MB \
--timeout 120s \
--region us-central1 \
--service-account fb-monitor-sa@PROJECT_ID.iam.gserviceaccount.com
# Deploy telegram webhook function
gcloud functions deploy telegram-webhook \
--runtime python39 \
--trigger-http \
--allow-unauthenticated \
--entry-point telegram_webhook \
--memory 256MB \
--timeout 60s \
--region us-central1 \
--service-account fb-monitor-sa@PROJECT_ID.iam.gserviceaccount.com
# Get webhook URL and set on Telegram
WEBHOOK_URL=$(gcloud functions describe telegram-webhook --format='value(httpsTrigger.url)')
curl -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook" \
-d "url=${WEBHOOK_URL}"
```
12. **Create Cloud Scheduler jobs**:
```bash
# Daily report at 10:00 UTC+6 (04:00 UTC)
gcloud scheduler jobs create pubsub daily-report-job \
--schedule="0 4 * * *" \
--topic=daily-report-topic \
--message-body="{}" \
--time-zone="UTC"
# Hourly critical checks
gcloud scheduler jobs create pubsub hourly-check-job \
--schedule="0 * * * *" \
--topic=hourly-check-topic \
--message-body="{}" \
--time-zone="UTC"
```
13. **Create service account with minimal permissions**:
```bash
gcloud iam service-accounts create fb-monitor-sa \
--display-name="Facebook Ad Monitor Bot"
# Grant Secret Manager access
gcloud secrets add-iam-policy-binding fb-access-token \
--member="serviceAccount:fb-monitor-sa@PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/secretmanager.secretAccessor"
# Repeat for telegram-bot-token and telegram-chat-id secrets
```
14. **Enable required APIs**:
```bash
gcloud services enable cloudfunctions.googleapis.com
gcloud services enable cloudscheduler.googleapis.com
gcloud services enable secretmanager.googleapis.com
gcloud services enable pubsub.googleapis.com
```
15. **Test each function locally** (before deployment):
- Use `functions-framework` package: `pip install functions-framework`
- Run: `functions-framework --target=telegram_webhook --debug`
- Send test POST requests with sample Telegram update payloads
16. **Test deployed functions**:
```bash
# Trigger daily report manually
gcloud scheduler jobs run daily-report-job
# Trigger hourly check manually
gcloud scheduler jobs run hourly-check-job
# Test webhook with curl
curl -X POST https://YOUR_REGION-YOUR_PROJECT.cloudfunctions.net/telegram-webhook \
-H "Content-Type: application/json" \
-d '{"message":{"chat":{"id":YOUR_CHAT_ID},"text":"/start"}}'
```
17. **Monitor logs**:
```bash
# View function logs
gcloud functions logs read daily-report --limit 50
gcloud functions logs read hourly-check --limit 50
gcloud functions logs read telegram-webhook --limit 50
# Or use Cloud Logging console
gcloud logging read "resource.type=cloud_function" --limit 100 --format json
```
18. **Set up alerting** (optional):
- Create log-based metrics for function errors
- Configure Cloud Monitoring alerts for failed executions
- Set up budget alerts for Cloud Functions usage
Once deployed, the bot will:
1. **Send daily report at 10:00 UTC+6** to configured Telegram chat with table:
```
📊 Daily Ad Account Report - 2024-01-15
Account | Status | Balance | Yesterday | Limit
───────────────────────────────────────────────────────
KZ Astana | 🟢 Active | $1,250 | $145 | $2,000
KZ Almaty | 🟡 Limited | -$340 | $89 | $1,500
Tanuki Almaty | 🔴 Blocked | $0 | $0 | N/A
...
```
2. **Send hourly alerts** if critical issues detected:
```
🚨 CRITICAL FACEBOOK AD ISSUES
• KZ Almaty: Spending limit exceeded ($1,678 / $1,500)
• Tanuki UZ: Account disabled - payment issue
• Bella Ciao: 3 new moderation violations
```
3. **Respond to inline button presses** in Telegram with updated data and refreshed keyboard.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/facebook-ad-monitor-bot-gcp/raw