我将为您提供一个分步指南,使用 Cloudflare Worker 实现跨平台通知聚合。以下是实现方案:
1. 准备工作
- 注册 Cloudflare 账号并安装 Wrangler CLI
- 准备各平台 API 凭证:
- X/Twitter:Bearer Token
- Mastodon:实例域名 + 访问令牌
- Telegram:Bot Token
- 创建 Cloudflare Worker 项目:
wrangler init notification-aggregator
2. 配置环境变量
在 wrangler.toml
中配置敏感信息:
[vars]
X_BEARER_TOKEN = "your_twitter_bearer_token"
MASTODON_INSTANCE = "your.instance.url"
MASTODON_TOKEN = "your_mastodon_token"
TG_BOT_TOKEN = "your_telegram_bot_token"
3. 核心代码实现
// src/worker.js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// 并发获取三方数据
const [xData, mastoData, tgData] = await Promise.allSettled([
getTwitterMentions(),
getMastodonNotifications(),
getTelegramUpdates()
])
// 统一数据格式
const processed = [
...processX(xData.value),
...processMastodon(mastoData.value),
...processTelegram(tgData.value)
].sort((a, b) => new Date(b.time) - new Date(a.time)) // 按时间倒序
// 返回 JSON 响应
return new Response(JSON.stringify(processed), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // 处理 CORS
}
})
}
// Twitter API 请求示例
async function getTwitterMentions() {
const url = 'https://api.x.com/2/users/me/mentions'
return fetch(url, {
headers: { Authorization: `Bearer ${env.X_BEARER_TOKEN}` }
}).then(r => r.json())
}
// Mastodon API 请求
async function getMastodonNotifications() {
const url = `https://${env.MASTODON_INSTANCE}/api/v1/notifications`
return fetch(url, {
headers: { Authorization: `Bearer ${env.MASTODON_TOKEN}` }
}).then(r => r.json())
}
// Telegram API 请求
async function getTelegramUpdates() {
const url = `https://api.telegram.org/bot${env.TG_BOT_TOKEN}/getUpdates`
return fetch(url).then(r => r.json())
}
// 数据转换函数示例(需根据实际 API 响应调整)
function processX(data) {
return data?.data?.map(item => ({
platform: 'Twitter',
content: item.text,
author: item.author_id,
url: `https://x.com/i/web/status/${item.id}`,
time: item.created_at
})) || []
}
4. 高级功能建议
-
错误处理增强:
function safeParse(data) { try { return data.status === 'fulfilled' ? data.value : [] } catch { return [] } }
-
Telegram Offset 管理(使用 KV 存储):
async function getTelegramUpdates() { const lastOffset = await env.KV_STORE.get('tg_offset') || 0 const url = `https://api.telegram.org/bot${env.TG_BOT_TOKEN}/getUpdates?offset=${lastOffset + 1}` const data = await fetch(url).then(r => r.json()) if(data.result?.length) { await env.KV_STORE.put('tg_offset', data.result.slice(-1)[0].update_id) } return data }
-
缓存优化:
const CACHE_TTL = 60 // 1分钟缓存 const cacheKey = new Request(request.url, request) const cache = caches.default let response = await cache.match(cacheKey) if (!response) { // ...处理数据逻辑... response.headers.append('Cache-Control', `max-age=${CACHE_TTL}`) event.waitUntil(cache.put(cacheKey, response.clone())) }
5. 部署命令
# 测试部署
wrangler dev
# 生产环境发布
wrangler publish
6. 接口调用示例
curl https://your-worker.your-subdomain.workers.dev/
响应示例:
[
{
"platform": "Twitter",
"content": "@user1 你好呀!",
"author": "123456",
"url": "https://x.com/i/web/status/1782549622632223154",
"time": "2024-04-15T09:30:00Z"
},
{
"platform": "Mastodon",
"content": "@user2 欢迎使用长毛象!",
"author": "@user2@mastodon.social",
"url": "https://mastodon.social/@user/123",
"time": "2024-04-15T09:25:00Z"
}
]
注意事项
- 各平台 API 可能有速率限制,建议:
- 添加
setTimeout
控制请求频率 - 使用
Promise.allSettled
防止单个平台故障影响整体
- 添加
- 敏感操作建议启用 Cloudflare 的 WAF 防护
- 实时性要求高时可考虑使用 WebSocket 或 Durable Objects