个人 Reddit 监视器会跟踪您在所有 Reddit 子版块中关心的主题,并向您发送新讨论的每日摘要。与仅适用于订阅社区的 Reddit 通知不同,此监视器会在整个平台上搜索您的关键字。每次搜索费用为 0.005 美元,因此每天监控 10 个关键字的费用为 0.05 美元/天。
前置条件
- Python 3.8+
- 请求库
- 来自 scavio.dev 的 Scavio API 密钥
- 要监控的关键字或主题
操作指南
步骤 1: 配置监控关键字
设置您想要在 Reddit 上跟踪的关键字和主题。
Python
import os, requests, json, sqlite3, hashlib
from datetime import datetime
API_KEY = os.environ['SCAVIO_API_KEY']
SH = {'x-api-key': API_KEY, 'Content-Type': 'application/json'}
MONITOR_CONFIG = {
'keywords': [
'scavio api', 'serp api recommendation', 'search api for agents',
'mcp search tool', 'web scraping alternative 2026'
],
'digest_email': '[email protected]',
'min_relevance': 2 # Minimum keyword matches to include
}
db = sqlite3.connect('reddit_monitor.db')
db.execute('''CREATE TABLE IF NOT EXISTS seen (
hash TEXT PRIMARY KEY, title TEXT, link TEXT,
keyword TEXT, first_seen TEXT
)''')
db.commit()
print(f'Monitoring {len(MONITOR_CONFIG["keywords"])} keywords on Reddit')
print(f'Daily cost estimate: ${len(MONITOR_CONFIG["keywords"]) * 0.005:.3f}')步骤 2: 在 Reddit 中搜索每个关键字
提取每个受监控关键字的最近讨论。
Python
def search_keyword(keyword):
data = requests.post('https://api.scavio.dev/api/v1/search',
headers=SH, json={'query': keyword, 'platform': 'reddit', 'country_code': 'us'}).json()
results = data.get('organic_results', [])
new_posts = []
for r in results[:10]:
link = r.get('link', '')
post_hash = hashlib.md5(link.encode()).hexdigest()
# Check if already seen
existing = db.execute('SELECT hash FROM seen WHERE hash=?', (post_hash,)).fetchone()
if not existing:
post = {'hash': post_hash, 'title': r.get('title', '')[:100],
'link': link, 'snippet': r.get('snippet', '')[:200],
'keyword': keyword}
new_posts.append(post)
db.execute('INSERT INTO seen VALUES (?,?,?,?,?)',
(post_hash, post['title'], link, keyword, datetime.now().isoformat()))
db.commit()
return new_posts
all_new = []
for kw in MONITOR_CONFIG['keywords']:
new = search_keyword(kw)
all_new.extend(new)
print(f' "{kw}": {len(new)} new posts')
print(f'\nTotal new posts: {len(all_new)}')步骤 3: 按相关性对帖子进行评分
根据新帖子匹配的受监控关键字数量对新帖子进行排名。
Python
def score_relevance(post, all_keywords):
text = f"{post['title']} {post['snippet']}".lower()
matches = sum(1 for kw in all_keywords if kw.lower() in text)
return matches
def rank_posts(posts, keywords, min_relevance=1):
for post in posts:
post['relevance'] = score_relevance(post, keywords)
ranked = [p for p in posts if p['relevance'] >= min_relevance]
ranked.sort(key=lambda x: x['relevance'], reverse=True)
return ranked
ranked = rank_posts(all_new, MONITOR_CONFIG['keywords'], MONITOR_CONFIG['min_relevance'])
print(f'\nHigh-relevance posts ({len(ranked)}):')
for p in ranked[:10]:
print(f' [{p["relevance"]}] {p["title"][:60]}')
print(f' via: "{p["keyword"]}"')步骤 4: 生成每日摘要
将所有新发现格式化为电子邮件或终端输出的摘要。
Python
def daily_digest(new_posts, ranked_posts):
now = datetime.now().strftime('%Y-%m-%d')
cost = len(MONITOR_CONFIG['keywords']) * 0.005
lines = []
lines.append(f'Reddit Monitor Digest - {now}')
lines.append(f'Keywords: {len(MONITOR_CONFIG["keywords"])} | New posts: {len(new_posts)} | Cost: ${cost:.3f}')
lines.append('')
if ranked_posts:
lines.append('HIGH RELEVANCE:')
for p in ranked_posts[:10]:
lines.append(f' [{p["relevance"]}] {p["title"][:65]}')
lines.append(f' {p["link"]}')
lines.append('')
# Keyword breakdown
lines.append('BY KEYWORD:')
keyword_counts = {}
for p in new_posts:
kw = p['keyword']
keyword_counts[kw] = keyword_counts.get(kw, 0) + 1
for kw, count in sorted(keyword_counts.items(), key=lambda x: -x[1]):
lines.append(f' {kw}: {count} new posts')
# Stats
total_seen = db.execute('SELECT COUNT(*) FROM seen').fetchone()[0]
lines.append(f'\nTotal posts tracked: {total_seen}')
lines.append(f'Monthly cost estimate: ${cost * 30:.2f}')
digest = '\n'.join(lines)
print(digest)
# Save digest
with open(f'digest_{now}.txt', 'w') as f:
f.write(digest)
return digest
daily_digest(all_new, ranked)Python 示例
Python
import os, requests
SH = {'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'}
def monitor(keywords):
for kw in keywords:
data = requests.post('https://api.scavio.dev/api/v1/search',
headers=SH, json={'query': kw, 'platform': 'reddit', 'country_code': 'us'}).json()
results = data.get('organic_results', [])[:3]
print(f'{kw}: {len(results)} posts')
for r in results:
print(f' - {r.get("title", "")[:60]}')
print(f'Cost: ${len(keywords) * 0.005:.3f}')
monitor(['serp api', 'search api recommendation'])JavaScript 示例
JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
async function monitor(keywords) {
for (const kw of keywords) {
const data = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST', headers: SH,
body: JSON.stringify({ query: kw, platform: 'reddit', country_code: 'us' })
}).then(r => r.json());
console.log(`${kw}: ${(data.organic_results || []).length} posts`);
(data.organic_results || []).slice(0, 2).forEach(r => console.log(` - ${r.title.slice(0, 60)}`));
}
}
monitor(['serp api', 'search api recommendation']).catch(console.error);预期输出
JSON
Monitoring 5 keywords on Reddit
Daily cost estimate: $0.025
"scavio api": 3 new posts
"serp api recommendation": 5 new posts
"search api for agents": 4 new posts
"mcp search tool": 2 new posts
"web scraping alternative 2026": 3 new posts
Total new posts: 17
Reddit Monitor Digest - 2026-05-19
Keywords: 5 | New posts: 17 | Cost: $0.025
HIGH RELEVANCE:
[3] Looking for a serp api recommendation for my AI agent project
https://reddit.com/r/...
[2] Best search API for agents in 2026? Need MCP support
https://reddit.com/r/...
Monthly cost estimate: $0.75