### Rust Result Product Iterator Example Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates how to use the `product` method on an iterator of Results. If any element is an Err, it's returned immediately; otherwise, the product of all Ok values is returned. This is useful for operations where failure at any step invalidates the entire process. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Rust Result `is_ok` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates the `is_ok` method for `Result`, which returns `true` if the result is an `Ok` variant and `false` otherwise. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Read a Wiki Page using mwbot Source: https://docs.rs/mwbot/latest/mwbot/index Demonstrates how to read the HTML content of a MediaWiki page using the mwbot crate. It initializes a Bot instance, fetches a specific page, and extracts text content from the lead section. This example uses Rust. ```rust # async fn demo() -> mwbot::Result<()> { # use parsoid::prelude::*; let bot = mwbot::Bot::from_default_config().await.unwrap(); let page = bot.page("Rust (programming language)")?; let html = page.html().await?.into_mutable(); // The lead section is the second p tag in the first section let lead = html.select("section > p")[1].text_contents(); assert!(lead.starts_with("Rust is a multi-paradigm, general-purpose programming language")); # Ok(()) # } ``` -------------------------------- ### Edit a Wiki Page using mwbot Source: https://docs.rs/mwbot/latest/mwbot/index Shows how to perform an edit on a MediaWiki page using the mwbot crate. It initializes a Bot, selects a target page (e.g., Project:Sandbox), defines the wikitext content, and saves the changes with a summary. This example uses Rust. ```rust let bot = mwbot::Bot::from_default_config().await.unwrap(); let page = bot.page("Project:Sandbox")?; let wikitext = "This is a test edit!"; page.save(wikitext, &mwbot::SaveOptions::summary("test edit!")).await?; ``` -------------------------------- ### Rust Result `transpose` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates the `transpose` method for `Result, E>`, which converts a `Result` of an `Option` into an `Option` of a `Result`. `Ok(None)` becomes `None`, while `Ok(Some(_))` and `Err(_)` are wrapped in `Some`. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Rust Result `is_ok_and` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Shows the `is_ok_and` method for `Result`, which returns `true` if the result is `Ok` and its contained value satisfies a given predicate. It takes a closure `f` as an argument. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Execute FilesInPage Generator - Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/file/struct Implementation of the `generate` method for the FilesInPage struct. This method starts the generator and returns a Receiver to asynchronously retrieve a list of pages. ```Rust fn generate(self, bot: &Bot) -> Receiver ``` -------------------------------- ### Rust Example: Fetching pages in a category using CategoryMembers generator Source: https://docs.rs/mwbot/latest/mwbot/generators/index Demonstrates how to use the `CategoryMembers` generator to fetch a list of pages belonging to a specific category. It initializes a bot, creates a generator instance, and then iterates through the received pages, printing their titles. Note that this generator requires the 'generators' crate feature and handles asynchronous operations. ```Rust use mwbot::generators::{categories::CategoryMembers, Generator}; let bot = Bot::from_default_config().await.unwrap(); let mut generator = CategoryMembers::new("Category:Free software programmed in Rust"); let mut pages = generator.generate(&bot); while let Some(page) = pages.recv().await { let page = page?; println!("{}", page.title()); } ``` -------------------------------- ### UserContribs Builder Methods in Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/user_contribs/struct Provides a set of builder-style methods for configuring the UserContribs generator. These methods allow setting parameters such as start and end times, user lists, namespaces, and filters. ```rust pub fn new() -> Self pub fn start(self, value: impl Into) -> Self pub fn with_start(self, value: impl Into>) -> Self pub fn set_start(&mut self, value: impl Into>) pub fn end(self, value: impl Into) -> Self pub fn with_end(self, value: impl Into>) -> Self pub fn set_end(&mut self, value: impl Into>) pub fn users(self, value: impl Into>) -> Self pub fn with_users(self, value: impl Into>>) -> Self pub fn set_users(&mut self, value: impl Into>>) pub fn user_ids(self, value: impl Into>) -> Self pub fn with_user_ids(self, value: impl Into>>) -> Self pub fn set_user_ids(&mut self, value: impl Into>>) pub fn user_prefix(self, value: impl Into) -> Self pub fn with_user_prefix(self, value: impl Into>) -> Self pub fn set_user_prefix(&mut self, value: impl Into>) pub fn user_ip_range(self, value: impl Into) -> Self pub fn with_user_ip_range(self, value: impl Into>) -> Self pub fn set_user_ip_range(&mut self, value: impl Into>) pub fn dir(self, value: impl Into) -> Self pub fn with_dir(self, value: impl Into>) -> Self pub fn set_dir(&mut self, value: impl Into>) pub fn namespaces(self, value: impl Into>) -> Self pub fn with_namespaces(self, value: impl Into>>) -> Self pub fn set_namespaces(&mut self, value: impl Into>>) pub fn filter(self, value: impl Into>) -> Self pub fn with_filter(self, value: impl Into>>) -> Self pub fn set_filter(&mut self, value: impl Into>>) pub fn tags(self, value: impl Into>) -> Self pub fn with_tags(self, value: impl Into>>) -> Self pub fn set_tags(&mut self, value: impl Into>>) ``` -------------------------------- ### Rust: Get references from Result with as_ref() Source: https://docs.rs/mwbot/latest/mwbot/type Explains how to use the `as_ref()` method to convert a `&Result` into a `Result<&T, &E>`. This allows borrowing the contained values without consuming the original Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### AllPages Generator Trait Implementation - Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/allpages/struct Implements the `Generator` trait for the `AllPages` struct. This includes defining the `Output` type and methods for generating API parameters and starting the generation process asynchronously. ```rust type Output = Result ``` ```rust fn params(&self) -> HashMap<&'static str, String> ``` ```rust fn generate(self, bot: &Bot) -> Receiver ``` -------------------------------- ### AllRedirects Generator Source: https://docs.rs/mwbot/latest/mwbot/generators/allredirects/struct The `AllRedirects` struct provides functionality to retrieve all pages in a given namespace that are redirects. It allows specifying a namespace, a starting page title, an ending page title, a prefix filter, and a sort direction. ```APIDOC ## GET /api/allredirects ### Description Retrieves all pages in a given namespace that are redirects. This can be filtered by starting page, ending page, and prefix. ### Method GET ### Endpoint `/api/allredirects` ### Parameters #### Query Parameters - **namespace** (u32) - Optional - The namespace to enumerate redirects from. - **from** (string) - Optional - The page title to start enumerating from. - **to** (string) - Optional - The page title to stop enumerating at. - **prefix** (string) - Optional - The title prefix for filtering redirects. - **sort** (SortDirection) - Optional - The sort direction for the results (e.g., `ASC`, `DESC`). ### Request Example ```json { "namespace": 0, "from": "PageA", "prefix": "User:", "sort": "ASC" } ``` ### Response #### Success Response (200) - **redirects** (array of objects) - A list of redirects, where each object contains page information. - **title** (string) - The title of the redirect page. - **namespace** (integer) - The namespace of the redirect page. - **pageid** (integer) - The ID of the redirect page. - **redirects_to** (string) - The title of the page the redirect points to. #### Response Example ```json { "redirects": [ { "title": "User:ExampleRedirect", "namespace": 2, "pageid": 12345, "redirects_to": "User:ExamplePage" } ] } ``` ``` -------------------------------- ### Rust Result Sum Iterator Example Source: https://docs.rs/mwbot/latest/mwbot/type Illustrates the usage of the `sum` method on an iterator of Results. Similar to `product`, if an Err is encountered, it's returned; otherwise, the sum of all Ok values is computed. This is suitable for aggregations where a single error should halt the operation. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Rust Result `is_err_and` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates the `is_err_and` method for `Result`, which returns `true` if the result is `Err` and its contained error value satisfies a given predicate. It takes a closure `f` as an argument. ```rust let x: Result = Ok(2); assert_eq!(x.is_err_and(|e| e == "error"), false); let x: Result = Err("error"); assert_eq!(x.is_err_and(|e| e == "error"), true); ``` -------------------------------- ### Configure mwbot Source: https://docs.rs/mwbot/latest/mwbot/index Sets up the mwbot configuration file, typically located at ~/.config/mwbot.toml. It includes options for the wiki URL and authentication details like username and OAuth2 token. File permissions must be restricted for security. ```toml wiki_url = "https://en.wikipedia.org/w/" [auth] username = "Example" oauth2_token = "[...]" ``` -------------------------------- ### Generator Trait Implementation for LonelyPages Source: https://docs.rs/mwbot/latest/mwbot/generators/lonely/struct Implements the Generator trait for LonelyPages, defining the output type as a Result containing a Page or an Error. It includes methods to get API parameters and to start the generation process asynchronously. ```rust type Output = Result fn params(&self) -> HashMap<&'static str, String> fn generate(self, bot: &Bot) -> Receiver ``` -------------------------------- ### Implement Generator Trait for LinksHere in Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/link/struct Details the implementation of the `Generator` trait for the `LinksHere` struct. This includes defining the `Output` type as a `Result`, providing a method to get API parameters, and a `generate` method to start the asynchronous fetching of pages. ```rust type Output = Result ``` ```rust fn params(&self) -> HashMap<&'static str, String> ``` ```rust fn generate(self, bot: &Bot) -> Receiver ``` -------------------------------- ### TitleCodec Initialization Source: https://docs.rs/mwbot/latest/mwbot/struct Methods for creating a new TitleCodec instance. ```APIDOC ## TitleCodec Initialization ### `new()` Construct a new `TitleCodec` using the given fields. In most cases it is easier to do so from one of the siteinfo methods. **Parameters** - `namespace_map` (NamespaceMap) - The map of namespaces. - `interwiki_set` (InterwikiSet) - The set of interwiki definitions. - `local_interwiki_set` (InterwikiSet) - The set of local interwiki definitions. - `main_page` (String) - The name of the main page. - `lang` (String) - The language code of the site. - `legal_title_chars` (String) - A string containing all legal title characters. ### `new_from_iters()` Create a new `TitleCodec` getting namespaces, namespace aliases, and interwikis from iterators. **Parameters** - `namespaces` (N: IntoIterator) - An iterator over namespace information. - `namespace_aliases` (A: IntoIterator) - An iterator over namespace aliases. - `interwikis` (I: IntoIterator) - An iterator over interwiki definitions. - `main_page` (String) - The name of the main page. - `lang` (String) - The language code of the site. - `legal_title_chars` (String) - A string containing all legal title characters. ### `from_site_info()` Create a new `TitleCodec` using the provided `SiteInfo`. The `SiteInfo` must include a non-empty `interwiki_map` field to enable the resulting `TitleCodec` to correctly parse titles with interwikis, but an empty `interwiki_map` is not an error. **Parameters** - `site_info` (SiteInfo) - The site information object. ### `new()` - Example (Conceptual) ```rust // Assuming NamespaceMap, InterwikiSet, etc. are defined and populated // let ns_map = ...; // let iw_set = ...; // let local_iw_set = ...; // let title_codec = TitleCodec::new(ns_map, iw_set, local_iw_set, "Main Page".to_string(), "en".to_string(), "abcdefg...".to_string()); ``` ### `from_site_info()` - Example (Conceptual) ```rust // Assuming SiteInfo is defined and populated // let site_info = ...; // let title_codec = TitleCodec::from_site_info(site_info).unwrap(); ``` ``` -------------------------------- ### Rust Result `is_err` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Illustrates the `is_err` method for `Result`, which returns `true` if the result is an `Err` variant and `false` otherwise. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### LangLinks Constructor and Configuration Methods in Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/langlinks/struct Provides methods to create and configure a LangLinks instance. These methods allow setting initial titles and optionally specifying language, language title, and sort direction. ```rust pub fn new(titles: impl Into>) -> Self pub fn lang(self, value: impl Into) -> Self pub fn with_lang(self, value: impl Into>) -> Self pub fn set_lang(&mut self, value: impl Into>) pub fn lang_title(self, value: impl Into) -> Self pub fn with_lang_title(self, value: impl Into>) -> Self pub fn set_lang_title(&mut self, value: impl Into>) pub fn sort(self, value: impl Into) -> Self pub fn with_sort(self, value: impl Into>) -> Self pub fn set_sort(&mut self, value: impl Into>) pub fn lang_name_locale(self, value: impl Into) -> Self pub fn with_lang_name_locale(self, value: impl Into>) -> Self pub fn set_lang_name_locale(&mut self, value: impl Into>) ``` -------------------------------- ### Rust: UploadRequest Methods for Configuration Source: https://docs.rs/mwbot/latest/mwbot/upload/struct Details the public methods available on the `UploadRequest` struct in Rust for configuring upload parameters. These methods include setting the initial file path, adding comments, specifying tags, providing initial wikitext for new pages, controlling warning handling, and defining the chunk size for uploads. Each method returns `Self`, enabling a fluent builder pattern. ```rust pub fn from_path(path: PathBuf) -> Self pub fn comment(self, comment: String) -> Self pub fn tags(self, tags: Vec) -> Self pub fn text(self, text: String) -> Self pub fn ignore_warnings(self, val: bool) -> Self pub fn chunk_size(self, val: usize) -> Self ``` -------------------------------- ### Rust: Get mutable references from Result with as_mut() Source: https://docs.rs/mwbot/latest/mwbot/type Illustrates the `as_mut()` method, which converts a `&mut Result` into a `Result<&mut T, &mut E>`. This enables modifying the contained values in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Rust mwbot Templates Constructor and Configuration Source: https://docs.rs/mwbot/latest/mwbot/generators/templates/struct Provides methods to construct and configure the `Templates` generator. This includes setting initial page titles, specifying namespaces, and adding template names. These methods return `Self` to allow for fluent chaining of configurations. ```rust pub fn new(titles: impl Into>) -> Self pub fn namespaces(self, value: impl Into>) -> Self pub fn with_namespaces(self, value: impl Into>>) -> Self pub fn set_namespaces(&mut self, value: impl Into>>) pub fn templates(self, value: impl Into>) -> Self pub fn with_templates(self, value: impl Into>>) -> Self pub fn set_templates(&mut self, value: impl Into>>) pub fn sort(self, value: impl Into) -> Self pub fn with_sort(self, value: impl Into>) -> Self pub fn set_sort(&mut self, value: impl Into>) ``` -------------------------------- ### Initialize Logging with mwbot Source: https://docs.rs/mwbot/latest/mwbot/index Initializes the logging system for the mwbot crate. The verbosity of the logs can be controlled by setting the `RUST_LOG` environment variable. This function is essential for observing the bot's operations. ```rust mwbot::init_logging(); ``` -------------------------------- ### UnconnectedPages Constructor and Offset Methods Source: https://docs.rs/mwbot/latest/mwbot/generators/unconnected_pages/struct Provides methods for creating an instance of UnconnectedPages and configuring an offset for fetching pages. The `new` function creates a default instance, while `offset` and `with_offset` allow setting an initial page offset. ```rust pub fn new() -> Self ``` ```rust pub fn offset(self, value: impl Into) -> Self ``` ```rust pub fn with_offset(self, value: impl Into>) -> Self ``` ```rust pub fn set_offset(&mut self, value: impl Into>) ``` -------------------------------- ### Rust Result `flatten` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Shows the `flatten` method for `Result, E>`, which converts a nested `Result` into a single-level `Result`. This operation removes one level of nesting at a time. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); // Flattening only removes one level of nesting at a time: let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Rust: Constructing an Upload Request Source: https://docs.rs/mwbot/latest/mwbot/upload/struct Demonstrates how to build an `UploadRequest` object in Rust. This involves initializing the request with a file path and then optionally setting a comment, tags, initial wikitext, ignoring warnings, and specifying chunk size. This builder pattern allows for a flexible and readable way to configure file uploads. ```rust use mwbot::upload::UploadRequest; use std::path::PathBuf; // Example of creating and configuring an UploadRequest let mut request = UploadRequest::from_path(PathBuf::from("path/to/your/file.jpg")); request = request.comment("Uploading a test image".to_string()); request = request.tags(vec!["test".to_string(), "image".to_string()]); request = request.text("This is a new page with initial text.".to_string()); request = request.ignore_warnings(false); request = request.chunk_size(10_000_000); // 10MB chunk size // The 'request' object is now configured and ready to be used for an upload. ``` -------------------------------- ### Constructor and Configuration: PagesWithProp (Rust) Source: https://docs.rs/mwbot/latest/mwbot/generators/pageswithprop/struct Provides methods for creating and configuring a PagesWithProp instance. The `new` function initializes the struct with a required property name, while `dir` and `with_dir` allow for setting the sort direction. ```rust pub fn new(prop_name: impl Into) -> Self pub fn dir(self, value: impl Into) -> Self pub fn with_dir(self, value: impl Into>) -> Self pub fn set_dir(&mut self, value: impl Into>) ``` -------------------------------- ### AllPages Generator Configuration Methods - Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/allpages/struct Provides methods for configuring the `AllPages` generator. These methods allow setting various parameters like namespace, redirect filtering, size limits, and page ranges. They typically return `Self` for chaining. ```rust pub fn new() -> Self ``` ```rust pub fn namespace(self, value: impl Into) -> Self ``` ```rust pub fn with_namespace(self, value: impl Into>) -> Self ``` ```rust pub fn set_namespace(&mut self, value: impl Into>) ``` ```rust pub fn filter_redirect(self, value: impl Into) -> Self ``` ```rust pub fn with_filter_redirect( self, value: impl Into>, ) -> Self ``` ```rust pub fn set_filter_redirect(&mut self, value: impl Into>) ``` ```rust pub fn min_size(self, value: impl Into) -> Self ``` ```rust pub fn with_min_size(self, value: impl Into>) -> Self ``` ```rust pub fn set_min_size(&mut self, value: impl Into>) ``` ```rust pub fn max_size(self, value: impl Into) -> Self ``` ```rust pub fn with_max_size(self, value: impl Into>) -> Self ``` ```rust pub fn set_max_size(&mut self, value: impl Into>) ``` ```rust pub fn from(self, value: impl Into) -> Self ``` ```rust pub fn with_from(self, value: impl Into>) -> Self ``` ```rust pub fn set_from(&mut self, value: impl Into>) ``` ```rust pub fn to(self, value: impl Into) -> Self ``` ```rust pub fn with_to(self, value: impl Into>) -> Self ``` ```rust pub fn set_to(&mut self, value: impl Into>) ``` ```rust pub fn prefix(self, value: impl Into) -> Self ``` ```rust pub fn with_prefix(self, value: impl Into>) -> Self ``` ```rust pub fn set_prefix(&mut self, value: impl Into>) ``` -------------------------------- ### EmbeddedIn Generator API Source: https://docs.rs/mwbot/latest/mwbot/generators/struct This section details the EmbeddedIn struct, which is used to get pages that transclude a given template. It provides methods to configure namespaces, filter redirects, and set the sort direction. ```APIDOC ## POST /api/generators/embeddedin ### Description Retrieves pages that transclude a specified template. This endpoint allows configuration of namespaces, redirect filtering, and sort direction. ### Method POST ### Endpoint /api/generators/embeddedin ### Parameters #### Query Parameters - **title** (String) - Required - The title of the template to find transclusions for. - **namespace** (Vec) - Optional - A list of namespaces to search within. - **filterredirect** (FilterRedirect) - Optional - Specifies how to handle redirects (e.g., "all", "redirects", "nonredirects"). - **dir** (SortDirection) - Optional - The direction to sort the results (e.g., "ascending", "descending"). ### Request Example ```json { "title": "Template:Example", "namespace": [0, 2, 14], "filterredirect": "nonredirects", "dir": "ascending" } ``` ### Response #### Success Response (200) - **output** (Receiver>) - An asynchronous receiver that yields pages transcluding the template or errors encountered during the fetch. #### Response Example (Note: The actual response is a stream of `Result`, not a static JSON object. This is a conceptual representation.) ```json [ { "page": { "title": "Page 1", "id": 123, "namespace": 0, "content": "..." } }, { "page": { "title": "Page 2", "id": 456, "namespace": 2, "content": "..." } } ] ``` ``` -------------------------------- ### LintErrors Constructor and Configuration Methods Source: https://docs.rs/mwbot/latest/mwbot/generators/lint/struct Provides methods for creating and configuring a LintErrors instance. These methods allow setting categories (visible and invisible), namespaces, page IDs, and a 'from' parameter. Most configuration methods return `Self` for builder-style chaining, while `set_` methods modify the struct in place. ```rust pub fn new() -> Self pub fn categories(self, value: impl Into>) -> Self pub fn with_categories(self, value: impl Into>>) -> Self pub fn set_categories(&mut self, value: impl Into>>) pub fn invisible_categories(self, value: impl Into>) -> Self pub fn with_invisible_categories( self, value: impl Into>>, ) -> Self pub fn set_invisible_categories( &mut self, value: impl Into>>, ) pub fn namespaces(self, value: impl Into>) -> Self pub fn with_namespaces(self, value: impl Into>>) -> Self pub fn set_namespaces(&mut self, value: impl Into>>) pub fn page_id(self, value: impl Into) -> Self pub fn with_page_id(self, value: impl Into>) -> Self pub fn set_page_id(&mut self, value: impl Into>) pub fn from(self, value: impl Into) -> Self pub fn with_from(self, value: impl Into>) -> Self pub fn set_from(&mut self, value: impl Into>) ``` -------------------------------- ### Iterate Over Result Value in Rust Source: https://docs.rs/mwbot/latest/mwbot/type Shows how to obtain an iterator that yields the contained value if the Result is Ok, and is empty if the Result is Err. This is useful for functional-style iteration over optional values. Examples cover both Ok and Err cases. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### RandomPages Constructor and Builder Methods Source: https://docs.rs/mwbot/latest/mwbot/generators/random/struct Provides methods for creating and configuring a RandomPages generator. This includes setting namespaces and redirect filters. ```Rust pub fn new() -> Self pub fn namespaces(self, value: impl Into>) -> Self pub fn with_namespaces(self, value: impl Into>>) -> Self pub fn set_namespaces(&mut self, value: impl Into>>) pub fn filterredir(self, value: impl Into) -> Self pub fn with_filterredir(self, value: impl Into>) -> Self pub fn set_filterredir(&mut self, value: impl Into>) ``` -------------------------------- ### Generator Implementation for UserContribs in Rust Source: https://docs.rs/mwbot/latest/mwbot/generators/user_contribs/struct Implements the Generator trait for the UserContribs struct. This includes defining the output type as a Result containing either UserContribsResponseItem or an Error, and methods to generate API parameters and start the generation process. ```rust type Output = Result fn params(&self) -> HashMap<&'static str, String> fn generate(self, bot: &Bot) -> Receiver ``` -------------------------------- ### mwbot::generators::allpages::AllPages Source: https://docs.rs/mwbot/latest/mwbot/generators/allpages/struct The AllPages struct provides a fluent API for configuring and generating a list of all pages from a MediaWiki instance. It allows setting various filters and parameters to customize the page retrieval process. ```APIDOC ## GET /api/allpages ### Description Retrieves all pages within a specified namespace from a MediaWiki instance. This generator can be configured with various filters such as minimum/maximum page size, namespace, and page title prefix. ### Method GET ### Endpoint /api/allpages ### Parameters #### Query Parameters - **action** (string) - Required - Set to 'query' for API requests. - **list** (string) - Required - Set to 'allpages' to specify the generator. - **apnamespace** (integer) - Optional - The namespace to enumerate pages from. Defaults to 0 (main namespace). - **apfilterredirects** (string) - Optional - How to filter redirects. Possible values: 'normal', 'redirects', 'nonredirects'. - **apminsize** (integer) - Optional - Limit to pages with at least this many bytes. - **apmaxsize** (integer) - Optional - Limit to pages with at most this many bytes. - **apfrom** (string) - Optional - The page title to start enumerating from. - **apto** (string) - Optional - The page title to stop enumerating at. - **apprefix** (string) - Optional - The title prefix for filtering pages. - **format** (string) - Required - The desired output format (e.g., 'json'). ### Request Example ```http GET /w/api.php?action=query&list=allpages&apnamespace=0&apminsize=1000&apprefix=User&format=json ``` ### Response #### Success Response (200) - **query** (object) - Contains the list of pages. - **allpages** (array) - An array of page objects. - **pageid** (integer) - The ID of the page. - **ns** (integer) - The namespace of the page. - **title** (string) - The title of the page. - **length** (integer) - The size of the page in bytes. #### Response Example ```json { "batchcomplete": "", "continue": { "apcontinue": "ExamplePage", "continue": "-||-" }, "query": { "allpages": [ { "pageid": 123, "ns": 0, "title": "ExamplePage", "length": 1500 }, { "pageid": 456, "ns": 0, "title": "AnotherPage", "length": 2000 } ] } } ``` ``` -------------------------------- ### Map Error on Result Type in Rust Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates mapping an error value of a Result using a provided function. This is useful for transforming error types without affecting the success value. The example shows how to convert a u32 error to a String. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Rust - Search Struct Builder Methods Source: https://docs.rs/mwbot/latest/mwbot/generators/search/struct Provides builder-style methods for configuring a Search instance. These methods allow setting various search parameters like namespace, offset, query profile, search content, interwiki preference, and rewrite enablement. Each method returns `Self` to enable chaining. ```rust pub fn new(search: impl Into) -> Self pub fn namespace(self, value: impl Into>) -> Self pub fn with_namespace(self, value: impl Into>>) -> Self pub fn set_namespace(&mut self, value: impl Into>>) pub fn offset(self, value: impl Into) -> Self pub fn with_offset(self, value: impl Into>) -> Self pub fn set_offset(&mut self, value: impl Into>) pub fn qi_profile(self, value: impl Into) -> Self pub fn with_qi_profile(self, value: impl Into>) -> Self pub fn set_qi_profile(&mut self, value: impl Into>) pub fn what(self, value: impl Into) -> Self pub fn with_what(self, value: impl Into>) -> Self pub fn set_what(&mut self, value: impl Into>) pub fn interwiki(self, value: impl Into) -> Self pub fn with_interwiki(self, value: impl Into>) -> Self pub fn set_interwiki(&mut self, value: impl Into>) pub fn enable_rewrites(self, value: impl Into) -> Self pub fn with_enable_rewrites(self, value: impl Into>) -> Self pub fn set_enable_rewrites(&mut self, value: impl Into>) ``` -------------------------------- ### Rust: Initialize and configure CategoryMembers Source: https://docs.rs/mwbot/latest/mwbot/generators/categories/struct Demonstrates how to create and configure a CategoryMembers instance in Rust. Methods like `new`, `namespace`, `dir`, `type_`, `sort`, and `starthexsortkey` can be chained to specify query parameters for fetching category members. The `generators` feature must be enabled. ```rust pub fn new(title: impl Into) -> Self pub fn namespace(self, value: impl Into>) -> Self pub fn dir(self, value: impl Into) -> Self pub fn type_(self, value: impl Into) -> Self pub fn sort(self, value: impl Into) -> Self pub fn starthexsortkey(self, value: impl Into) -> Self ``` -------------------------------- ### LogEvents Constructor and Setters (Rust) Source: https://docs.rs/mwbot/latest/mwbot/generators/log_events/struct Provides methods to create and configure a LogEvents instance. These methods allow setting types, action, start/end timestamps, order, user, title, namespace, and tags for filtering log events. Many methods return `Self` for chaining. ```rust pub fn new() -> Self pub fn types(self, value: impl Into>) -> Self pub fn with_types(self, value: impl Into>>) -> Self pub fn set_types(&mut self, value: impl Into>>) pub fn action(self, value: impl Into) -> Self pub fn with_action(self, value: impl Into>) -> Self pub fn set_action(&mut self, value: impl Into>) pub fn start(self, value: impl Into) -> Self pub fn with_start(self, value: impl Into>) -> Self pub fn set_start(&mut self, value: impl Into>) pub fn end(self, value: impl Into) -> Self pub fn with_end(self, value: impl Into>) -> Self pub fn set_end(&mut self, value: impl Into>) pub fn order(self, value: impl Into) -> Self pub fn with_order(self, value: impl Into>) -> Self pub fn set_order(&mut self, value: impl Into>) pub fn user(self, value: impl Into) -> Self pub fn with_user(self, value: impl Into>) -> Self pub fn set_user(&mut self, value: impl Into>) pub fn title(self, value: impl Into) -> Self pub fn with_title(self, value: impl Into>) -> Self pub fn set_title(&mut self, value: impl Into>) pub fn namespace(self, value: impl Into) -> Self pub fn with_namespace(self, value: impl Into>) -> Self pub fn set_namespace(&mut self, value: impl Into>) pub fn tag(self, value: impl Into) -> Self pub fn with_tag(self, value: impl Into>) -> Self pub fn set_tag(&mut self, value: impl Into>) ``` -------------------------------- ### Inspect Err Value of Result Type in Rust Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates calling a closure with a reference to the contained error value if the Result is Err. This is useful for logging or handling errors without altering the original Result. The example logs an error during file reading. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Conversion: TryFrom and TryInto Trait Implementations (Rust) Source: https://docs.rs/mwbot/latest/mwbot/generators/pageswithprop/struct Illustrates the blanket implementations of `TryFrom` and `TryInto`. These traits provide fallible conversion methods, returning a `Result` to handle potential conversion errors. ```rust type Error = Infallible fn try_from(value: U) -> Result>::Error> type Error = >::Error fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Inspect Ok Value of Result Type in Rust Source: https://docs.rs/mwbot/latest/mwbot/type Shows how to call a closure with a reference to the contained value if the Result is Ok, without modifying the result itself. This is useful for side effects like logging. The example parses a string to a u8 and prints the original value. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Rust Result `cloned` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Illustrates the `cloned` method for `Result<&T, E>` and `Result<&mut T, E>`, which maps a `Result` containing a reference to its contained value into a `Result` containing a cloned value. This requires the contained type `T` to implement the `Clone` trait. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Generic Trait Implementations for QueryPage Source: https://docs.rs/mwbot/latest/mwbot/generators/querypage/struct Showcases various blanket trait implementations for QueryPage, including Auto Traits like Send, Sync, and UnwindSafe, as well as Blanket Implementations for traits like Any, Borrow, and Instrument. ```rust impl Freeze for QueryPage impl RefUnwindSafe for QueryPage impl Send for QueryPage impl Sync for QueryPage impl Unpin for QueryPage impl UnwindSafe for QueryPage impl Any for T where T: 'static + ?Sized impl Borrow for T where T: ?Sized impl BorrowMut for T where T: ?Sized impl From for T impl Instrument for T impl Into where U: From impl PolicyExt for T where T: ?Sized impl TryFrom where U: Into impl TryInto where U: TryFrom impl WithSubscriber for T impl ErasedDestructor for T where T: 'static ``` -------------------------------- ### Rust Result `copied` Implementation Example Source: https://docs.rs/mwbot/latest/mwbot/type Demonstrates the `copied` method for `Result<&T, E>` and `Result<&mut T, E>`, which maps a `Result` containing a reference to its contained value into a `Result` containing a copied value. This requires the contained type `T` to implement the `Copy` trait. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Iterate Mutably Over Result Value in Rust Source: https://docs.rs/mwbot/latest/mwbot/type Provides a mutable iterator that yields a mutable reference to the contained value if the Result is Ok, and is empty if the Result is Err. This allows in-place modification of the Ok value. Examples demonstrate modifying an Ok value and handling an Err. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Create 'And' Policy Source: https://docs.rs/mwbot/latest/mwbot/generators/categories/struct Creates a new Policy that returns Action::Follow only if both self and other Policies return Action::Follow. This is useful for defining combined access control logic where all conditions must be met. ```Rust fn and(self, other: P) -> And where T: Policy, P: Policy, ```