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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
| // ==UserScript==
// @name Bilibili 批量取消关注(简化刷新版)
// @namespace https://space.bilibili.com/
// @version 0.1.1
// @description 右下角开始/停止;每处理完当前页后自动刷新继续下一页
// @match https://space.bilibili.com/*/relation/follow*
// @grant none
// ==/UserScript==
(function () {
'use strict';
var STORAGE_KEY = '__bili_unfollow_simple_state_v1__';
var CONFIG = {
pageSize: 24,
delayMin: 1800,
delayMax: 3200,
batchRestEvery: 20,
batchRestMin: 20000,
batchRestMax: 40000,
retryTimes: 3,
retryPauseMin: 60000,
retryPauseMax: 120000,
pageReloadDelayMin: 2500,
pageReloadDelayMax: 5000,
skipMutual: false,
skipQuiet: false
};
var running = false;
var stopRequested = false;
var btnStart;
var btnStop;
var statusEl;
var panel;
var runnerStarted = false;
function loadState() {
try {
var raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function saveState(state) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
function clearState() {
localStorage.removeItem(STORAGE_KEY);
}
function getState() {
return loadState() || {
running: false,
stopRequested: false,
processed: 0,
success: 0,
failed: 0,
round: 0,
logs: []
};
}
function appendLog(text) {
var state = getState();
var logs = Array.isArray(state.logs) ? state.logs : [];
logs.push('[' + new Date().toLocaleTimeString('zh-CN', { hour12: false }) + '] ' + text);
if (logs.length > 80) logs = logs.slice(logs.length - 80);
state.logs = logs;
saveState(state);
renderStatus();
console.log('[B站批量取关]', text);
}
function cookie(name) {
var m = document.cookie.match(new RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return m ? decodeURIComponent(m[1]) : '';
}
function getCsrf() {
return cookie('bili_jct');
}
function getMyUid() {
return cookie('DedeUserID');
}
function getSpmid() {
var meta = document.querySelector('meta[name="spm_prefix"]');
return meta ? meta.content : '333.1387.0.0';
}
function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function rand(min, max) {
return Math.floor(min + Math.random() * (max - min + 1));
}
function shouldSkip(item) {
if (CONFIG.skipMutual && item.attribute === 6) return true;
if (CONFIG.skipQuiet && item.attribute === 1) return true;
return false;
}
async function fetchPage1() {
var url = new URL('https://api.bilibili.com/x/relation/followings');
url.search = new URLSearchParams({
vmid: getMyUid(),
pn: '1',
ps: String(CONFIG.pageSize),
order: 'desc',
order_type: '',
gaia_source: 'main_web',
web_location: '333.1387'
}).toString();
var resp = await fetch(url.toString(), {
credentials: 'include',
mode: 'cors'
});
var json = await resp.json();
if (json.code !== 0) {
throw new Error(json.message || ('拉取关注列表失败(code=' + json.code + ')'));
}
return json.data && json.data.list ? json.data.list : [];
}
async function unfollowOne(item) {
var act = item.attribute === 1 ? 4 : 2;
var csrf = getCsrf();
var body = new URLSearchParams({
fid: String(item.mid),
act: String(act),
re_src: '11',
gaia_source: 'web_main',
spmid: getSpmid(),
extend_content: JSON.stringify({ entity: 'user', entity_id: item.mid }),
is_from_frontend_component: 'true',
csrf: csrf,
csrf_token: csrf
});
var url = new URL('https://api.bilibili.com/x/relation/modify');
url.search = new URLSearchParams({
statistics: JSON.stringify({ appId: 100, platform: 5 })
}).toString();
var resp = await fetch(url.toString(), {
method: 'POST',
credentials: 'include',
mode: 'cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: body.toString()
});
return await resp.json();
}
async function unfollowWithRetry(item) {
for (var attempt = 1; attempt <= CONFIG.retryTimes; attempt++) {
var res = await unfollowOne(item);
if (res.code === 0) return res;
var msg = res.message || ('code=' + res.code);
if (/频繁|过快|稍后|异常|风险|验证码/i.test(msg) && attempt < CONFIG.retryTimes) {
var pause = rand(CONFIG.retryPauseMin, CONFIG.retryPauseMax);
appendLog('触发频控:' + item.uname + ',' + Math.round(pause / 1000) + ' 秒后重试(' + attempt + '/' + CONFIG.retryTimes + ')');
await sleep(pause);
continue;
}
throw new Error(msg);
}
}
function renderStatus() {
if (!statusEl) return;
var state = getState();
var lines = [];
lines.push('状态:' + (state.running ? (state.stopRequested ? '停止中(本页结束后停)' : '运行中') : '待开始'));
lines.push('轮次:' + (state.round || 0));
lines.push('累计成功:' + (state.success || 0));
lines.push('累计失败:' + (state.failed || 0));
lines.push('累计处理:' + (state.processed || 0));
lines.push('');
var logs = state.logs || [];
for (var i = Math.max(0, logs.length - 8); i < logs.length; i++) {
lines.push(logs[i]);
}
statusEl.textContent = lines.join('\n');
if (btnStart) btnStart.disabled = !!state.running;
if (btnStop) btnStop.disabled = !state.running;
}
function createPanel() {
panel = document.createElement('div');
panel.id = '__bili_unfollow_simple_panel__';
panel.style.position = 'fixed';
panel.style.right = '20px';
panel.style.bottom = '20px';
panel.style.zIndex = '999999';
panel.style.background = 'rgba(255,255,255,.96)';
panel.style.color = '#222';
panel.style.border = '1px solid #ddd';
panel.style.borderRadius = '10px';
panel.style.boxShadow = '0 8px 30px rgba(0,0,0,.12)';
panel.style.padding = '12px';
panel.style.fontSize = '14px';
panel.style.width = '320px';
var title = document.createElement('div');
title.textContent = '批量取消关注(简化刷新版)';
title.style.fontWeight = '700';
title.style.marginBottom = '8px';
panel.appendChild(title);
var desc = document.createElement('div');
desc.textContent = '每页处理完后自动刷新,刷新后自动继续。';
desc.style.fontSize = '12px';
desc.style.color = '#666';
desc.style.marginBottom = '8px';
panel.appendChild(desc);
var btnWrap = document.createElement('div');
btnWrap.style.display = 'flex';
btnWrap.style.gap = '8px';
btnWrap.style.marginBottom = '8px';
btnStart = document.createElement('button');
btnStart.textContent = '开始';
btnStart.style.padding = '6px 10px';
btnStart.style.border = '1px solid #00AEEC';
btnStart.style.borderRadius = '6px';
btnStart.style.cursor = 'pointer';
btnStart.style.background = '#00AEEC';
btnStart.style.color = '#fff';
btnStart.addEventListener('click', start);
btnStop = document.createElement('button');
btnStop.textContent = '停止';
btnStop.style.padding = '6px 10px';
btnStop.style.border = '1px solid #ccc';
btnStop.style.borderRadius = '6px';
btnStop.style.cursor = 'pointer';
btnStop.style.background = '#fff';
btnStop.disabled = true;
btnStop.addEventListener('click', stop);
btnWrap.appendChild(btnStart);
btnWrap.appendChild(btnStop);
panel.appendChild(btnWrap);
statusEl = document.createElement('pre');
statusEl.style.fontSize = '12px';
statusEl.style.lineHeight = '1.5';
statusEl.style.maxHeight = '260px';
statusEl.style.overflow = 'auto';
statusEl.style.whiteSpace = 'pre-wrap';
statusEl.style.margin = '0';
panel.appendChild(statusEl);
document.body.appendChild(panel);
renderStatus();
}
async function start() {
if (running) return;
if (!getMyUid() || !getCsrf()) {
alert('未检测到登录态,请先登录 B 站后再运行。');
return;
}
if (!confirm('确认开始批量取消关注?脚本会处理完当前页后自动刷新并继续。')) {
return;
}
running = true;
stopRequested = false;
saveState({
running: true,
stopRequested: false,
processed: 0,
success: 0,
failed: 0,
round: 0,
logs: []
});
appendLog('任务已启动。');
await runCurrentPage();
}
function stop() {
stopRequested = true;
var state = getState();
state.stopRequested = true;
state.running = true;
saveState(state);
appendLog('已请求停止,本页处理完后停止。');
}
async function runCurrentPage() {
if (runnerStarted) return;
runnerStarted = true;
try {
var state = getState();
if (!state.running) return;
state.round += 1;
saveState(state);
appendLog('开始第 ' + state.round + ' 轮,读取当前页关注列表。');
var list = await fetchPage1();
var candidates = list.filter(function (item) {
return item && !shouldSkip(item);
});
if (!candidates.length) {
appendLog(list.length ? '当前页都被跳过,任务结束。' : '已没有可处理的关注,任务完成。');
clearState();
running = false;
stopRequested = false;
renderStatus();
return;
}
appendLog('本轮待处理:' + candidates.length + ' 个。');
for (var i = 0; i < candidates.length; i++) {
var item = candidates[i];
state = getState();
if (state.stopRequested) {
appendLog('收到停止请求,当前页结束后停止。');
break;
}
try {
appendLog('正在取消:' + item.uname + ' (' + item.mid + ')');
await unfollowWithRetry(item);
state = getState();
state.processed += 1;
state.success += 1;
saveState(state);
appendLog('成功:' + item.uname);
} catch (err) {
state = getState();
state.processed += 1;
state.failed += 1;
saveState(state);
appendLog('失败:' + item.uname + ' -> ' + (err && err.message ? err.message : err));
}
await sleep(rand(CONFIG.delayMin, CONFIG.delayMax));
if ((i + 1) % CONFIG.batchRestEvery === 0 && i + 1 < candidates.length) {
var restMs = rand(CONFIG.batchRestMin, CONFIG.batchRestMax);
appendLog('已处理本页 ' + (i + 1) + ' 个,休息 ' + Math.round(restMs / 1000) + ' 秒。');
await sleep(restMs);
}
}
state = getState();
if (state.stopRequested) {
appendLog('本页处理结束,停止任务。');
clearState();
running = false;
stopRequested = false;
renderStatus();
return;
}
var reloadMs = rand(CONFIG.pageReloadDelayMin, CONFIG.pageReloadDelayMax);
appendLog('本页处理完成,' + Math.round(reloadMs / 1000) + ' 秒后刷新继续。');
await sleep(reloadMs);
location.reload();
} finally {
runnerStarted = false;
}
}
function boot() {
createPanel();
var state = getState();
if (state.running) {
running = true;
stopRequested = !!state.stopRequested;
appendLog('检测到上次任务未结束,刷新后自动继续。');
setTimeout(function () {
runCurrentPage();
}, 1200);
}
}
if (document.body) boot();
else window.addEventListener('DOMContentLoaded', boot);
})();
|