甬哥的订阅连接保活脚本,ChatGPT修改方案

甬哥的订阅连接保活脚本,ChatGPT修改方案

https://raw.githubusercontent.com/flower-wins/sb-nodejs/refs/heads/main/workers_keep.js

ChatGPT修改方案

✅ 方法一:从环境变量读取(适用于 Cloudflare Worker)

如果你在使用 Cloudflare Worker,可以通过环境变量来导入 URL 字符串:

1. 修改脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
addEventListener('scheduled', event => event.waitUntil(handleScheduled()));

// 从环境变量中读取 URL 字符串
const TIMEOUT = 5000;

async function fetchWithTimeout(url) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), TIMEOUT);
try {
await fetch(url, { signal: controller.signal });
console.log(`✅ 成功: ${url}`);
} catch (error) {
console.warn(`❌ 访问失败: ${url}, 错误: ${error.message}`);
} finally {
clearTimeout(timeout);
}
}

async function handleScheduled(event) {
console.log('⏳ 任务开始');

// 从环境变量导入 URL 列表
const urlString = URLS || '';
const urls = urlString.split(/[\s,,]+/).filter(Boolean);

await Promise.all(urls.map(fetchWithTimeout));
console.log('📊 任务结束');
}

2. 在 Cloudflare Worker 的 Dashboard 设置变量:

在 “Settings” > “Variables” 中设置:

Name Value
URLS https://example1.com https://example2.com

✅ 方法二:从 KV 或远程文件加载

如果 URL 是动态变更的,你可以将其放到 KV(Key-Value 存储)或从远程 JSON 文件中获取,例如:

KV 示例(Worker 使用 KV 命名空间):

1
2
3
4
5
6
7
8
9
10
11
12
const kvNamespace = MY_KV; // 在 Worker 绑定时指定

async function handleScheduled() {
console.log('⏳ 任务开始');

const urlString = await kvNamespace.get('keepalive_urls') || '';
const urls = urlString.split(/[\s,,]+/).filter(Boolean);

await Promise.all(urls.map(fetchWithTimeout));
console.log('📊 任务结束');
}

设置 keepalive_urls 的值(在 Dashboard 或 API 中设置):

1
https://a.com https://b.com https://c.com

✅ 方法三:从远程地址加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
async function loadUrls() {
try {
const res = await fetch('https://your-domain.com/urls.txt');
const text = await res.text();
return text.split(/[\s,,]+/).filter(Boolean);
} catch (e) {
console.warn('❌ 无法加载远程 URL:', e.message);
return [];
}
}

async function handleScheduled() {
console.log('⏳ 任务开始');

const urls = await loadUrls();
await Promise.all(urls.map(fetchWithTimeout));

console.log('📊 任务结束');
}