User:A2569875-bot/Code/CleanFrenchCommune.cpp

#include <iostream>
#include <string>
#include <vector>

#include <regex>

using namespace DotNetWikiBot;

#include "BotHeader.h"
//因隱私因素,省略部分本地端標頭檔
int main()
{
	Site^ zhWiki = gcnew Site("https://zh.wikipedia.org", "A2569875");
	auto page_result = zhWiki->getPageNamesFromEmbeddedin("Template:French_Commune_Data/Area", -1)
		.Concat(zhWiki->getPageNamesFromEmbeddedin("Template:French_Commune_Data/Population", -1))
        .Concat(zhWiki->getPageNamesFromEmbeddedin("Template:French_Commune_Data/ElevationMin", -1));
	std::vector<std::string> pages_link = toVector(page_result);

	for (int i = 0; i < pages_link.size(); ++i) {
		try
		{
			Page^ the_page = gcnew Page(zhWiki, page_result->ToArray()[i]);

			auto find_template = regexp("\\|[0-9a-zA-Z\\n\\r\\t_ ]+=[\\n\\r\\t ]*{{[\\n\\r\\t ]*French[\\n\\r\\t ]+Commune[\\n\\r\\t ]+Data[\\n\\r\\t ]*/[^}]+}}({{[\\n\\r\\t ]*French[\\n\\r\\t ]+Commune[\\n\\r\\t ]+Data[\\n\\r\\t ]*/[\\n\\r\\t ]*Population[\\n\\r\\t ]*\\|[\\n\\r\\t ]*ref[\\n\\r\\t ]*}})?[^\\n\\r]*\\n");
			auto find_area = regexp("({{)([\\n\\r\\t ]*French[\\n\\r\\t ]+Commune[\\n\\r\\t ]+Data[\\n\\r\\t ]*/[^}]+}})");
			
			the_page->Load();
			if (the_page->GetNamespace() != 1) continue;
			auto result = the_page->text;

			bool find_text = false;

			auto match_template = find_template->Matches(result);
			if (match_template->Count > 0) {
				result = find_template->Replace(result, "");
				find_text = true;
			}

			auto match_area = find_area->Matches(result);
			if (match_area->Count > 0) {
				result = find_area->Replace(result, "$1safesubst:$2");
				find_text = true;
			}

			if (find_text) {
				the_page->text = result;
				the_page->Save("[[WP:FLOOD|機器用戶]]([[Special:Diff/58063843|批准於58063843]]):替換引用[[phab:T244578]]事件涉事模板。", true);

				Page^ reload_page = gcnew Page(zhWiki, page_result->ToArray()[i]);
				reload_page->Load();
				auto find_cmn = regexp("<!--[\\n\\r\\t ]*-->");
				auto reresult = reload_page->text;
				auto match_cmn = find_cmn->Matches(reresult);
				if (match_cmn->Count > 0) {
					reresult = find_cmn->Replace(reresult, "");
					the_page->text = reresult;
					the_page->Save("[[WP:FLOOD|機器用戶]]([[Special:Diff/58063843|批准於58063843]]):清理因替換引用subst:後殘留的<!---->。", true);
					result = reresult;
				}
				std::cout << "條目" << pages_link[i] << "替換引用完成" << std::endl;
			}
		}
		catch (const std::exception& ex2)
		{
			std::cout << "\n===========\nError!!\n" << std::endl;
			std::cout << ex2.what() << std::endl;
			sleep(rand() % (rand() % 2000) + 500);
			continue;
		}
	}
	std::cout << "Complete!" << std::endl;
	system("PAUSE");
	return 0;
}