Википедија:Создавање на бот

Бот страници: Правила за ботови | Активни ботови | Барање за одобрување на бот | Создавање на бот | Група за одобрување на бот
Барање на ботовски услуги | Bot owners' noticeboard | Bot status page | BAG Admin Tools

Роботи или ботови се автоматски процеси кои дејствуваат во рамките на Википедија на сличен начин како уредувачите. Оваа статија има за цел да објасни како се создава бот.

Зошто би ми требал бот? уреди

Ботовите можат да ги автоматизираат работите, со самото тоа истите се извршуваат многу побрзо отколку истите да се работат рачно. Ако имате некоја едноставна работа која треба да ја повторите многу пати (пример додавање на некоја предлошка во сите статии во одредена категорија која брои преку 1000 статии), тогаш оваа работа подобро е да ја препуштите на некој бот создаден за таа намена отколку тоа да го правите рачно.

Дали можам да создадам бот самиот? уреди

Оваа страница за помош се однесува на оние кои имаат претходно програмерско искуство но не знаат како да го применат своето знаење за создавање на Википедија бот.

Ако немате програмерски вештини и знаење подобро е работата околу создавањето на бот да ја препуштите на некој кој може да го направи тоа. Во тој случај поставете барање на страницата за барање на ботовски услуги. Исто така може да станете оператор на веќе постоечки ботови semi-bots. Ако и понатаму сакате да создадете свој бот, тогаш продолжете со читање на оваа статија.

Ако немате програмерско искуство и знаење, би ве предупредиле дека учењето на програмски јазик не е тривијална работа. Но и не е некоја филозофија да се научи ако имате доволно време и волја.

Чекори за развој на бот уреди

Во суштина кодирањето и пишувањето на бот е само еден дел од процесот на развој на ботот. Во принцип треба да ги следите развојните циклуси опишани подолу. Ако испуштите некој чекор, посебно во делот , тоа може да доведе до грешки во работата на ботот што значи нема да добие дозвола за извршување и ќе биде блокиран на Википедија.

Анализа уреди

  • Првиот чекор во создавање на бот е дефинирање на потребите односно идејата за што ќе служи ботот. Ако немате идеја, за што ќе служи ботот, може да одберете некое од барањата за ботовски услуги.
  • Проверете дали некој од веќе постоечките ботови не ја работи работата која сакате да ја завршите. За да видите за кои работи се создадени ботови, погледнете ја списокот на активни ботови.

Спецификација уреди

  • Спецификацијата треба детално да ја опише задачата која треба да биде извршена. Треба да имате детален список на задачите кои треба да се завршат. Обидете се да ги продискутирате овие задачи со останатите уредувачи на Википедија и извршете дополнителна спецификација откако од нив ќе добиете повратни информации. Дури и најголемите идеи можат да се подобрат ако се инкорпорираат идеите од останатите уредувачи.
  • Во наједноставните случаи, вашата спецификација мора да ги следи следниве услови:
  • Ботот е безопасен (тој не смее да прави измени кои би се сметале за вандализам)
  • Ботот е корисен (ја олеснува работата на уредувачите)
  • Ботот не ги троши премногу опслужувачките ресурси
  • Проверете дали ги задоволувате критериумите на Wikipedia bot policy

Софтверска архитектура уреди

  • Размислувајте за тоа како може да го создадете ботот и кои програмски јазици и алатки ќе користите.

Имплементација уреди

Имплементацијата (или кодирањето) значи она што сте го дизајнирале да го преточите во програмски код. Ова е видливиот дел од софтверското инженерство, но не и најзначајниот. Во фазата на имплеметација, потребно е да:

  • Создадете корисничка станица за вашиот бот. Уредувањата на вашиот бот нема да се извршуваат со вашата корисничка сметка. Вашиот бот ќе треба да има своја корисничка сметка со сопствено корисничко име и лозинка.
  • Истите поединости поставете ги на корисничката страница на вашиот бот. Треба исто така да поставите врска до страницата за одобрување (дали има одобрување или нема) за секоја функција. Луѓето ќе имаат прилика да даваат коментари на вашата објава, да одобруваат или не прифаќаат.
  • Кодирајте го вашиот бот во програмскиот јазик кој сте го избрале.

Тестирање: уреди

Ако вашиот предлог за бот е прифатен, најверојатно доделен му е пробен период во кој може да започне со работа за да се провери и да се исчисти од грешки. Треба добро да го проверите вашиот бот за да бидете сигурни дека функционира исправно. После истекот на периодот за проверка, надевајте се дека истиот ќе биде одобрен за употреба.

Документација: уреди

Важна (но често занемарена) задача е да се документира интерниот дизајн на ботот со цел во иднина истиот да се поправи или подобри. Ова е посебно важно ако имате намера да допуштите клонирање на вашиот бот. Во идеален случај, би требало да го постирате изворниот код на вашиот бот на неговата корисничка страница ако сакате другите да го стартуваат и клонираат. Овој код треба да биде добро документиран и лесен за користење.

Обука за користење на ботот и поддршка уреди

Треба да бидете подготвени да дадете одговори на поставени прашања од корисници или приговори во врска со вашиот бот на вашата корисничка страница за разговор.

Одржување: уреди

Одржувањето и подбрувањето на вашиот бот со цел да се надминат проблемите кои со тек на времето ќе се појавуваат може да ви одземе многу повеќе време отколку времето потребно за првичниот развој на ботот.

Што треба да имате во предвид уреди

  • Дали ќе функционира целосно автоматски или ќе има потреба од мануелна интервенција?
  • Дали ќе биде потребно логирање?
  • Дали ќе се генерираат соодветни извештаи?

Како википедија ботовите работат? уреди

Преглед на операциите уреди

 

Слично како и човекот - уредувач, википедија ботот може да ја прочита содржината на википедија-статијата, да изврши одредени манипулации врз истата врз основа на логиката врз која е програмиран и истите да ги запише. Се разбира, во некои работи ботот може да биде подобар од човекот а во некои полош.

Слично како човекот-уредувач, типичниот бот ќе оперира поставувајќи еден или повеќе GET барања до википедија преку HTTP протоколот (исто како што човекот-уредувач тоа го прави преку неговиот веб-прелистувач), прави одредени пресметки врз податоците кои ги прима од опслужувачот, потоа прави други упити/барања до опслужувачот врз основа на направените пресметки во претходниот чекор.

Пример, ако некој бот сака да ја вчита списокот на страници кои се поврзани со одредена страница, тој ќе му каже на опслужувачот "Ја сакам :Whatlinkshere".. Опслужувачот ќе одговори на тој начин што ќе му прати соодветни HTML податоци. Потоа ботот ќе делува во зависност од тоа што се содржи во овие податоци.

API-ја за ботови уреди

API доаѓа од англиски: Application Programming Interface. Опишува како ботот комуницира со википедија.

Најчесто користен API најверојатно е Screen scraping. Овој API во себе вклучува барање за википедија страница, а потоа прегледување на HTML податоците (исто како кога во вашиот веб-прелистувач ќе ја активирате командата view source), па екстракција на одредени вредности од овие HTML податоци. Ова и не е толку препорачливо, бидејќи како прво, интерфејсот може да се смени во секој момент а како второ, тоа значи значително оптоварување на опслужувачот. Но во овој момент тоа е единствениот начин да се преземат HTML форматирани вики-страници. Исто така уредувањето на страницата а потоа правење на http пост на податоците е единствениот начин да направите уредување на статиите.

Други API-ја кои можат да бидат од корист:

  • MediaWiki API extension - this is the next generation API that may one day be expanded to include data posting, as well as various data requests. Currently a number of features have already been implemented, such as revision+content, log events, watchlist, and many other. Data is available in many different formats (JSON,XML,YAML,...). See it live. Features are being ported from the older Query API interface.
    Status: Partially complete engine feature, available on all Wikimedia projects.
  • Query API -- a multi-format API to query data directly from the Wiki-servers (Live)
    Status: Production. This is an extension enabled on all WikiMedia servers.
  • Special:Export feature (bulk export of xml formatted data); see Parameters_to_Special:Export for arguments;
    Status: Production. Built-in engine feature, available on all WikiMedia servers.
  • Raw page: passing action=raw or action=raw&templates=expand to index.php allows for a direct access to the source of pages

Common hurdles уреди

Logging in as your bot when making edits уреди

It will be necessary for an approved bot to be logged in under its user account before making edits. A bot is free to make read requests without logging in, but ideally it should log in for all activites. One can login by passing a login string via HTTP such as http://en.wikipedia.org/w/index.php?title=Special:Userlogin&action=submitlogin&type=login through the query string. Data that should be POSTed to log in is wpName=BOTUSERNAME&wpPassword=BOTPASSWORD&wpRemember=1&wpLoginattempt=Log+in

Once logged in, the bot will need to save Wikipedia cookies and make sure it passes these back when making edit requests.

Edit tokens уреди

Wikipedia uses a system of edit tokens for making edits to wikipedia pages.

What this means is that it is not possible for your bot to pass a single POST request via HTTP to make a page edit. Just like a human editor, it is necessary for the bot to go through a number of stages:

  • Request the page using a string such as http://en.wikipedia.org/w/index.php?title=Wikipedia:Creating_a_bot&action=edit
  • The bot is returned an edit page with a text field. It is also returned (and this is important) an edit token as a hidden input form field in the html form tag. The edit token is of the approximate form b66655fjr7fd5drr3411ss23456s65eg\. Note that this edit token is unique to each edit request, may not be transferred for use on other pages, will only work for a single edit, and has a time limit after which it will not work.
  • The bot must then make a "write my edit to the page" request passing back the edit token it has been issued.

Why am I being returned an empty or near-empty edit token? уреди

Your bot may be returned an empty edit token or the edit token "\". This indicates that the bot's login has failed and that its authentication has not been approved by the server. This may be due to it failing to store and return the correct cookies.

Уредувачки конфликти уреди

A high possibility is that your bot will get caught in an edit conflict, in which another user will have made an edit between your requesting an edit (and getting your edit token) and actually making the edit.

One reason for this is that it might not have the correct wpStarttime and wpEdittime variables in the data sent to the server.

To check for edit conflicts, sadly you will have to do it the deprecated way, checking for some kind of indication it was a conflict in the html.

General guidelines for running a bot уреди

In addition to the official bot policy, which covers the main points to consider when developing your bot, there are a number of more general advisory points to consider when developing your bot.

Bot best practice уреди

  • Try not to make more than 10 requests (read and write added together) per minute.
  • Try to run the bot only at low server load times, or throttle the read/write request rate down at busy server times.
  • Edit/write requests are more expensive in server time than read requests. Be edit-light.
  • Do not make multi-threaded requests. Wait for one server request to complete before beginning another
  • Back off on receiving errors from the server. Errors are an indication often of heavy server load. Try to respond by backing off and not repeatedly hammering the server with replacement requests.
  • Try to consolidate edits. One single large edit is better than 10 smaller ones. Try and write your code with this in mind.

Common bot features you should consider implementing уреди

Timers уреди

You don't want your bot to edit too fast. Timers are ways for bots to control how fast they edit. A common way to do this is to send your bot to "sleep" for a certain time after performing an action before doing anything else. In Perl, this is accomplished by the simple command sleep(10); where 10 is the number of seconds to sleep for.

Manual assistance уреди

If your bot is doing anything that requires judgement or evaluation of context (e.g., correcting spelling) then you should consider making your bot manually-assisted. That is, not making edits without human confirmation.

Disabling the bot уреди

It is good bot policy to have a feature to disable the bot's operation if it is requested. You should probably have the bot refuse to run if a message has been left on its talk page, on the assumption that the message may be a complaint against its activities. This can be checked by looking for the "You have new messages..." banner in the HTML for the edit form. Remember that if your bot goes bad, it is your responsibility to clean up after it!

Signature уреди

Just like a human, if your bot makes edits to a talk page on wikipedia, it should sign its post with four tildes (~~~~). It should not sign any edits to text in the main namespace.

What technique and language should I use? уреди

Semi-Bots or auxiliary software уреди

In addition to true bots, there are a number of semi-bots known as auxiliary software available to anyone. Most of these take the form of enchanced web browsers with Wikipedia-specific functionality. The most popular one of these is AWB (Click here for a full list of these and other editing tools).

Bot clones уреди

There are already a number of bots running on wikipedia. Many of these bots publish their source code and allow you to subscribe to them, download and operate a copy (clone) of them in order to perform useful tasks whilst browsing wikipedia.

Developing a new bot уреди

Bots are essentially small computer applications or applets written in one or more programming languages. There are generally two types of bots: client-side and server-side. Client-side bots run on your local machine, and can only be run by you. Server-side bots are hosted online by your own machine or on a remote webserver, and (if you chose) can be initiated by others.

An overview is given below of various languages that can be used for writing a wikipedia bot. For each, a list is given of external articles advising how to get started programming in that language, as well as a list of existing libraries (sub-programs) you can use with your bot to prevent having to "reinvent the wheel" for basic functions.

Perl уреди

Perl has a run-time compiler. This means that it is not necessary to compile builds of your code yourself as it is with other programming languages. Instead, you simply create your program using a text editor such as gvim. You then run the code by passing it to an interpreter. This can be located either on your own computer or on a remote computer (webserver). If located on a webserver, you can start your program running and interface with your program while it is running via the Common Gateway Interface from your browser. Perl is available for most operating systems, including Microsoft Windows (which most human editors use) and UNIX (which many webservers use). If your internet service provider provides you with webspace, the chances are good that you have access to a perl build on the webserver from which you can run your Perl programs.

 

An example of some Perl code:

open (INPUT, "< $filepageid") || &file_open_error("$filepageid");

while ($page_id=<INPUT>){
    chomp($page_id);
    push @page_ids, $page_id;

    $hits_upto_sth->execute($page_id, $start_date);
    $hits{upto}{$page_id} = $hits_upto_sth->fetchrow_array();

    $hits_daily_sth->execute($page_id, $today);
    $hits{today}{$page_id} = $hits_daily_sth->fetchrow_array();

    $hits_daily_sth->execute($page_id, $yesterday);
    $hits{yesterday}{$page_id} = $hits_daily_sth->fetchrow_array();

    $hits_range_sth->execute($page_id, $start_of_30_days,
                                       $end_of_30_days,);
    $hits{monthly}{$page_id} = $hits_range_sth->fetchrow_array();
}

Guides to getting started with Perl programming:

Libraries:

  • Anura -- Perl interface to MediaWiki using libwww-perl. Not recommended, as the current version does not check for edit conflicts.
  • WWW::Mediawiki::Client -- perl module and command line client
  • WWW::Wikipedia -- perl module for interfacing wikipedia
  • Perl Wikipedia ToolKit -- perl modules, parsing wikitext and extracting data
  • perlwikipedia � A fairly-complete Wikipedia bot framework written in Perl.

PHP уреди

If you create a bot in the PHP programming language, you would probably want to merge it with a interactive web app.

You could also run it through a Command Line Interface, like the way you would do with perl

When you put it on a server, you will not need to run it as a CGI script, but just a regular old php page.

For example, to have someone sign up for a newsletter on Wikipedia, but don't force them to edit the page directly, you could make an interface on the web that goes and edits "User:Me/spam" and adds the user's name (this is not a good idea, just an example)

Example PHP code:

<?php
if(!isset($_POST['username'])) {
	echo "<form method=\"post\" action=\"{$_SERVER['PHP_SELF']}\">\n".
	     "Please enter your username here: <input type=\"text\" name=\"username\" />\n".
	     "<input type=\"submit\" value=\"submit\" />\n".
	     "</form>\n";
} else {
	echo "Welcome {$_POST['username']}!";
}
?>

Python уреди

Introduction to use

An example of some Python code:

def addt5(x):
    return x+5

def dotwrite(ast):
    nodename = getNodeName()
    label=symbol.sym_name.get(int(ast[0]),ast[0])
    print ' %s [label="%s' % (nodename, label) ,
    if isinstance(ast[1], str):
        if ast[1].strip():
            print '= %s "];' % ast[1]
        else:
            print '"]'
    else:
        print '"]'
        children = []
        for n, child in eunmerate(ast[1:]):
            children.append(dotwrite(child))
        print ' %s -> {' % nodename,
        for name in children:
            print '%s' % name,

Getting started with Python:

Libraries:

Microsoft .NET уреди

Generally developed in Microsoft Visual Studio development environment, languages include C++/CLI, J#, JScript .NET, Microsoft Visual C#, Visual Basic .NET, IronPython, and Windows PowerShell

Example of code (based on DotNetWikiBot Framework):

using System;
using DotNetWikiBot;
 
class MyBot : Bot
{						            
     public static void Main()
     {  
         Site enWP = new Site("http://en.wikipedia.org", "myLogin", 
                              "myPassword");
         Page p = new Page(enWP, "Art");
         p.Load();
         p.AddToCategory("Visual arts");
         p.Save("comment: category link added", true);
 		
         PageList pl = new PageList(enWP);
         pl.FillFromPageHistory("Science", 30);
         pl.LoadEx();
         pl.SaveXMLDumpToFile("Dumps\\ScienceArticleHistory.xml");
     }
}

Getting started:

  • Add links here!

Libraries:

Java уреди

Generally developed with Eclipse

Example of code:

public static void main(String [] args) throws Exception {
     MediaWikiBot bot = new MediaWikiBot("http://yourWiki.tld");
     bot.login("user", "pw");
     SimpleArticle a = bot.readContent("Main Page");
     modifyContent(a);
     bot.writeContent(a);
}

Getting started:

  • Add links here!

Libraries:

AppleScript уреди

Introduction to use

Example of code:

if testPrime is in {2, -2} then
        set testPrime to testPrime as string
        display dialog testPrime & " is a prime number." ¬
                buttons {"OK"} default button "OK"

else if testPrime is in {1, 0, -1} then
        set testPrime to testPrime as string
        display dialog testPrime & " is not a prime number." ¬
                buttons {"OK"} default button "OK"
end if 

Getting started with AppleScript

Библиотека: