Хэрэглэгшэ:TohaomgBot

Сүлөөтэ Нэбтэрхэй Толи — Википеэдиһээ
Шууд ошохо: тамаралга, хайха

Этот бот заменяет все вхождения определённого растрового изображения на его аналог в формате SVG, например "какое-то_изображение.jpg" на "какое-то_изображение.svg". Пара изображений подбирается вручную. Код программы можно увидеть внизу (Я разрешаю кому угодно использовать, распространять и изменять его, но не получать от него финансовую прибыль). Бот написан на языке C# с использованием библиотеки DotNetWikiBot.

Код

  1 using System;
  2 using System.Net;
  3 using System.Threading;
  4 using System.Collections.Generic;
  5 using System.Text.RegularExpressions;
  6 using DotNetWikiBot;
  7 
  8 class ImageReplacer:Bot
  9 {
 10  [STAThread]
 11  public static void Main(string[] args)
 12  {
 13   string username = args[0], password = args[1];
 14   string new_img;
 15   List<string> sites_list = new List<string>();
 16   Dictionary<string, string> summary = new Dictionary<string, string>();
 17   int edits, rejects;
 18   MatchCollection mc;
 19   
 20   summary.Add("en", "Replaced raster image with an image of format SVG.");
 21   summary.Add("de", "Ersetzt das rasterbild mit einem bild des formats SVG.");
 22   summary.Add("pt", "[[:pt:WP:BOT|BOT]]: Substituição de imagem raster por formato SVG.");
 23   summary.Add("uk", "Замінено растрове зображення на зображення в форматі SVG.");
 24   summary.Add("ru", "Заменено растровое изображение на изображение в формате SVG.");
 25   summary.Add("be", "Заменены растравы малюнак на малюнак у фармаце SVG.");
 26   summary.Add("pl", "Zamień grafike rastrową na obraz w formacie SVG.");
 27   summary.Add("sr", "Zamenjena rasterska slika sa slikom u formatu SVG.");
 28   summary.Add("hr", "Zamijenjena rasterska slika slikom u formatu SVG.");
 29   
 30   beginning:
 31   edits = 0;
 32 
 33 
 34   //USER INPUT
 35   Console.WriteLine("Replace: ");
 36   string old_img = args.Length>=3?args[2]:Console.ReadLine();
 37 	if(args.Length>=3) {Console.WriteLine(old_img);}
 38   if(old_img.StartsWith("id="))
 39   {
 40    Site commons_site = new Site("https://commons.wikimedia.org/", username, password);
 41    Page commons_page = new Page(commons_site, Int64.Parse(old_img.Substring(3)));
 42    commons_page.Load();
 43    old_img = commons_page.title.Substring(5);
 44    Console.WriteLine(old_img);
 45  
 46    mc = Regex.Matches(commons_page.text, @"\|((.)+svg)");
 47    new_img = mc[0].Groups[1].Value;
 48    
 49    new_img = new_img.Replace("File:", "");
 50    if(new_img.Contains("|")) {new_img = new_img.Substring(new_img.IndexOf("|")+1);}
 51    if(new_img.Contains("_")) {new_img = new_img.Replace("_", " ");}
 52  
 53    Console.WriteLine("\n"+"with: \n" + new_img);
 54   }
 55   else
 56   {
 57    Console.WriteLine("\n"+"with: ");
 58    new_img = args.Length>=4?args[3]:Console.ReadLine();
 59    	if(args.Length>=4) {Console.WriteLine(new_img);}
 60    if(new_img==old_img)
 61    {Console.WriteLine("\nNew image can not be the same as the old one!\n"); goto beginning;}
 62   }
 63   string old_img_underlined = old_img.Replace(" ", "_");
 64   Console.WriteLine();
 65  
 66 
 67   //WHAT WIKIS TO PROCESS
 68   string htmlCode;
 69   string img_usage_list = "https://" + "commons.wikimedia.org/w/index.php?title=Special:GlobalUsage&limit=500&target=" + 
 70 	old_img.Replace(" ", "+");
 71   bool goto_next_page = true;
 72   sites_list.Clear();
 73 
 74   while(goto_next_page)
 75   {
 76    try {using (WebClient client = new WebClient()) {htmlCode = client.DownloadString(img_usage_list);}}
 77    catch {Console.WriteLine("No page for this image found!"); goto beginning;}
 78   
 79    mc = Regex.Matches(htmlCode, @"\s([-\w]+\.(\w)+\.org)");
 80    if(mc.Count==0) {Console.WriteLine("No inclusions found!"); goto beginning;}
 81    foreach (Match m in mc)
 82    {
 83 	if(!sites_list.Contains(m.Groups[1].Value) && m.Groups[1].Value!="nl.wikipedia.org" && m.Groups[1].Value!="simple.wikipedia.org")
 84 		{sites_list.Add(m.Groups[1].Value);}
 85    }
 86 
 87    goto_next_page = !htmlCode.Contains("| next 500)");
 88    if(goto_next_page)
 89    {
 90 	mc = Regex.Matches(htmlCode, @"\|\s\<a href" + "=\"(/w/index.php" + @"\?title=Special:GlobalUsage&amp;limit=500&amp;from=" + "[^\"]+)\"");
 91     img_usage_list = "https://" + "commons.wikimedia.org" + mc[0].Groups[1].Value.Replace("&amp;", "&");
 92    }
 93   }
 94 
 95 
 96   //PROCESSING
 97   try
 98   {
 99    Site wiki_site; PageList inclusions; int site_counter = 1, page_counter; string lang;
100    foreach (string st_f in sites_list)
101    {
102     string st = st_f;
103     rejects = 0;
104     Console.WriteLine("\n" + site_counter + ". " + st);
105 
106     try_connect_again:
107     try {wiki_site = new Site("https://" + st, username, password);}
108     catch(System.Net.WebException)
109     {
110      Console.WriteLine("No internet connection or wrong sitename!");
111      Console.WriteLine("Check the connection and type sitename again (type 'skip' to skip):");
112      st = Console.ReadLine();
113      if(st=="skip") {continue;}
114      goto try_connect_again;
115     }
116     catch(DotNetWikiBot.WikiBotException)
117     {Console.WriteLine("Failed to login! This site will be skipped."); continue;}
118 
119     inclusions = new PageList(wiki_site);
120     inclusions.FillFromPagesUsingImage(old_img);
121     Console.WriteLine("\t" + inclusions.Count() + " inclusions found" + "\n");
122     lang = GetLang(st);
123   
124     page_counter = 1;
125     foreach (Page wiki_page in inclusions)
126     {
127      Console.WriteLine("\t" + page_counter + ". " + wiki_page.title);
128 	 
129      if(st_f=="www.wikidata.org")
130      {
131       System.Windows.Forms.Clipboard.SetText(new_img);
132       System.Diagnostics.Process.Start("http://" + "www.wikidata.org/wiki/" + wiki_page.title);
133       continue;
134      }
135 
136      Console.Write("\t");
137      wiki_page.Load();
138      if(wiki_page.Exists() && (wiki_page.text.Contains(old_img) || wiki_page.text.Contains(old_img_underlined)))
139      {
140       wiki_page.text = wiki_page.text.Replace(old_img, new_img);
141       wiki_page.text = wiki_page.text.Replace(old_img_underlined, new_img);
142       Console.Write("\t");
143       try {edits++; wiki_page.Save(summary[lang], true); if(st.StartsWith("pt.")) {Thread.Sleep(10000);}}
144       catch (DotNetWikiBot.WikiBotException)
145       {
146        edits--;
147        Console.WriteLine("\t\t" + "Site did not allow this edit");
148        if(++rejects > 3)
149        {Console.WriteLine("\t" + "To many rejects. This site will be skipped"); break;}
150       }
151 	  catch(System.Net.WebException e)
152 	  {
153 	   Console.WriteLine("\t\t" + "Network error: ");
154 	   Console.WriteLine("\t\t" + e.Message);
155 	   Console.WriteLine("\t\t" + "Waiting one minute");
156 	   Thread.Sleep(60000);
157 	  }
158 	  catch(Exception e) {Console.WriteLine("\t\tUnhandled exception: " + e.GetType()); Console.WriteLine("\t\t" + e.Message);}
159      }
160      else {Console.WriteLine("\t\t" + "Image not present");}
161 
162      page_counter++;
163     }
164     site_counter++;
165    }
166   }
167 
168   catch(Exception e)
169   {
170    Console.WriteLine("Unhandled exception: " + e.GetType());
171    Console.WriteLine(e.Message);
172    Console.ReadKey();
173   }
174 
175   //WRITING TO LOG
176   finally
177   {
178    if(edits>=2)
179    {
180     if(old_img.Length>64) {old_img = old_img.Substring(0,60) + "...";}
181     if(new_img.Length>64) {new_img = new_img.Substring(0,60) + "...";}
182 
183     System.IO.StreamWriter outfile = new System.IO.StreamWriter("log.txt", true);
184     outfile.Write("\r\n" + old_img);
185     int tabs = (old_img.Length)/8;
186     tabs = 8 - tabs;
187     while (tabs!=0) {outfile.Write("\t"); tabs--;}
188 
189     outfile.Write(new_img);
190     tabs = (new_img.Length)/8;
191     tabs = 8 - tabs;
192     while (tabs!=0) {outfile.Write("\t"); tabs--;}
193 
194     outfile.Write(DateTime.Now.ToString("dd.MM.yyyy (HH:mm)"));
195     outfile.Write("\t{0,4}", edits);
196     outfile.Close();
197    }
198    Console.WriteLine("DONE! - " + edits + " edits done\n");
199   }
200   if(args.Length>=3) {return;}
201   goto beginning;
202  }
203 
204  
205  //CHOSING LANGUAGE OF EDIT SUMMARY
206  public static string GetLang(string site)
207  {
208   string[] rulangs = {"ru.", "kk.", "hy.", "uz.", "ky.", "tg.", "crh.", "gag.", "tt.", "av.", 
209                          "kbd.", "ab.", "ba.", "bxr.", "os.", "kv.", "krc.", "mrj.", "lbe.", "lez.", 
210                          "mdf.", "ce.", "mhr.", "koi.", "sah.", "cu.", "tyv.", "udm.", "xal.", "cv.", 
211 						 "myv.", "ady"};
212   string[] delangs = {"de.", "lb.", "li.", "als.", "bar.", "ksh."};
213   string[] pllangs = {"pl.", "szl.", "csb.", "hsb.", "dsb."};
214   string[] srlangs = {"sr.", "sh.", "bs.", "mk."};
215 
216   if (site.StartsWith("uk.") || site.StartsWith("rue.")) {return "uk";}
217   else if (site.StartsWith("be.") || site.StartsWith("be-tarask.")) {return "be";}
218   else if (site.StartsWith("hr.") || site.StartsWith("sl.")) {return "hr";}
219   else if (site.StartsWith("pt.")) {return "pt";}
220   else if (Array.IndexOf(srlangs, site.Substring(0,3))>=0) {return "sr";}
221   else if (Array.IndexOf(pllangs, site.Substring(0,3))>=0 || Array.IndexOf(pllangs, site.Substring(0,4))>=0) {return "pl";}
222   else if (Array.IndexOf(delangs, site.Substring(0,3))>=0 || Array.IndexOf(delangs, site.Substring(0,4))>=0) {return "de";}
223   else if (Array.IndexOf(rulangs, site.Substring(0,3))>=0 || Array.IndexOf(rulangs, site.Substring(0,4))>=0) {return "ru";}
224   else {return "en";}
225  }
226 }
"https://bxr.wikipedia.org/wiki/Хэрэглэгшэ:TohaomgBot" холбооһоо абагдаһан