Википедија:Креирање на бот

Од Википедија, слободна енциклопедија

Бот страници: Бот политика | Активни ботови | Барање за одобрување на бот | Креирање на бот | Група за одобрување на бот
Requests for work to be done by a bot | Bot owners' noticeboard | Bot status page | BAG Admin Tools

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

Содржина

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

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

[уреди] Дали можам да креирам самиот бот?

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

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

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

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

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

[уреди] Анализа:

  • Првиот чекор во креирање на бот е дефинирање на потребите односно идејата за што ќе служи ботот. Ако немате идеја, за што ќе служи ботот, може да одберете некоја од requests for work to be done by a bot.
  • Проверете дали некој од веќе постоечките ботови не ја работи работата која сакате да ја завршите. За да видите кои за работи се креирани ботови, погледнете на the list of currently operating bots.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Слично како човекот уредувач, типичниот бот ќе оперира поставувајчи еден или повеќе 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.

[уреди] Edit conflicts

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:

 // Managed extensions for C++
 #using <mscorlib.dll>
 using namespace System::Collections;
 __gc class referencetype
 {
 protected:
     String* stringVar;
     int intArr __gc[];
     ArrayList* doubleList;
 public:
     referencetype(String* str, int* pointer, int number) // Which one is managed?
     {
         doubleList = new ArrayList();
         System::Console::WriteLine(str->Trim() + number.ToString());
     }
 };

Getting started:

  • Add links here!

Libraries:

  • DotNetWikiBot Framework (based on .NET Framework 2.0, written in C#)
    • WikiFunctions .NET library -- Bundled with AWB, is a library of stuff useful for bots, such as generating lists, loading/editing articles, connecting to the recent changes IRC channel and more.


[уреди] 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

Библиотека: