A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

739 lines
30 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from hashlib import md5
  23. from logging import getLogger, NullHandler
  24. import re
  25. from time import gmtime, strftime
  26. from urllib.parse import quote
  27. import mwparserfromhell
  28. from earwigbot import exceptions
  29. from earwigbot.wiki.copyvios import CopyvioMixIn
  30. __all__ = ["Page"]
  31. class Page(CopyvioMixIn):
  32. """
  33. **EarwigBot: Wiki Toolset: Page**
  34. Represents a page on a given :py:class:`~earwigbot.wiki.site.Site`. Has
  35. methods for getting information about the page, getting page content, and
  36. so on. :py:class:`~earwigbot.wiki.category.Category` is a subclass of
  37. :py:class:`Page` with additional methods.
  38. *Attributes:*
  39. - :py:attr:`site`: the page's corresponding Site object
  40. - :py:attr:`title`: the page's title, or pagename
  41. - :py:attr:`exists`: whether or not the page exists
  42. - :py:attr:`pageid`: an integer ID representing the page
  43. - :py:attr:`url`: the page's URL
  44. - :py:attr:`namespace`: the page's namespace as an integer
  45. - :py:attr:`lastrevid`: the ID of the page's most recent revision
  46. - :py:attr:`protection`: the page's current protection status
  47. - :py:attr:`is_talkpage`: ``True`` if this is a talkpage, else ``False``
  48. - :py:attr:`is_redirect`: ``True`` if this is a redirect, else ``False``
  49. *Public methods:*
  50. - :py:meth:`reload`: forcibly reloads the page's attributes
  51. - :py:meth:`toggle_talk`: returns a content page's talk page, or vice versa
  52. - :py:meth:`get`: returns the page's content
  53. - :py:meth:`get_redirect_target`: returns the page's destination if it is a
  54. redirect
  55. - :py:meth:`get_creator`: returns a User object representing the first
  56. person to edit the page
  57. - :py:meth:`parse`: parses the page content for templates, links, etc
  58. - :py:meth:`edit`: replaces the page's content or creates a new page
  59. - :py:meth:`add_section`: adds a new section at the bottom of the page
  60. - :py:meth:`check_exclusion`: checks whether or not we are allowed to edit
  61. the page, per ``{{bots}}``/``{{nobots}}``
  62. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_check`:
  63. checks the page for copyright violations
  64. - :py:meth:`~earwigbot.wiki.copyvios.CopyrightMixIn.copyvio_compare`:
  65. checks the page like :py:meth:`copyvio_check`, but against a specific URL
  66. """
  67. PAGE_UNKNOWN = 0
  68. PAGE_INVALID = 1
  69. PAGE_MISSING = 2
  70. PAGE_EXISTS = 3
  71. def __init__(self, site, title, follow_redirects=False, pageid=None,
  72. logger=None):
  73. """Constructor for new Page instances.
  74. Takes four arguments: a Site object, the Page's title (or pagename),
  75. whether or not to follow redirects (optional, defaults to False), and
  76. a page ID to supplement the title (optional, defaults to None - i.e.,
  77. we will have to query the API to get it).
  78. As with User, site.get_page() is preferred.
  79. __init__() will not do any API queries, but it will use basic namespace
  80. logic to determine our namespace ID and if we are a talkpage.
  81. """
  82. super().__init__(site)
  83. self._site = site
  84. self._title = title.strip()
  85. self._follow_redirects = self._keep_following = follow_redirects
  86. self._pageid = pageid
  87. # Set up our internal logger:
  88. if logger:
  89. self._logger = logger
  90. else: # Just set up a null logger to eat up our messages:
  91. self._logger = getLogger("earwigbot.wiki")
  92. self._logger.addHandler(NullHandler())
  93. # Attributes to be loaded through the API:
  94. self._exists = self.PAGE_UNKNOWN
  95. self._is_redirect = None
  96. self._lastrevid = None
  97. self._protection = None
  98. self._fullurl = None
  99. self._content = None
  100. self._creator = None
  101. # Attributes used for editing/deleting/protecting/etc:
  102. self._basetimestamp = None
  103. self._starttimestamp = None
  104. # Try to determine the page's namespace using our site's namespace
  105. # converter:
  106. prefix = self._title.split(":", 1)[0]
  107. if prefix != title: # ignore a page that's titled "Category" or "User"
  108. try:
  109. self._namespace = self.site.namespace_name_to_id(prefix)
  110. except exceptions.NamespaceNotFoundError:
  111. self._namespace = 0
  112. else:
  113. self._namespace = 0
  114. # Is this a talkpage? Talkpages have odd IDs, while content pages have
  115. # even IDs, excluding the "special" namespaces:
  116. if self._namespace < 0:
  117. self._is_talkpage = False
  118. else:
  119. self._is_talkpage = self._namespace % 2 == 1
  120. def __repr__(self):
  121. """Return the canonical string representation of the Page."""
  122. res = "Page(title={0!r}, follow_redirects={1!r}, site={2!r})"
  123. return res.format(self._title, self._follow_redirects, self._site)
  124. def __str__(self):
  125. """Return a nice string representation of the Page."""
  126. return '<Page "{0}" of {1}>'.format(self.title, str(self.site))
  127. def _assert_validity(self):
  128. """Used to ensure that our page's title is valid.
  129. If this method is called when our page is not valid (and after
  130. _load_attributes() has been called), InvalidPageError will be raised.
  131. Note that validity != existence. If a page's title is invalid (e.g, it
  132. contains "[") it will always be invalid, and cannot be edited.
  133. """
  134. if self._exists == self.PAGE_INVALID:
  135. e = "Page '{0}' is invalid.".format(self._title)
  136. raise exceptions.InvalidPageError(e)
  137. def _assert_existence(self):
  138. """Used to ensure that our page exists.
  139. If this method is called when our page doesn't exist (and after
  140. _load_attributes() has been called), PageNotFoundError will be raised.
  141. It will also call _assert_validity() beforehand.
  142. """
  143. self._assert_validity()
  144. if self._exists == self.PAGE_MISSING:
  145. e = "Page '{0}' does not exist.".format(self._title)
  146. raise exceptions.PageNotFoundError(e)
  147. def _load(self):
  148. """Call _load_attributes() and follows redirects if we're supposed to.
  149. This method will only follow redirects if follow_redirects=True was
  150. passed to __init__() (perhaps indirectly passed by site.get_page()).
  151. It avoids the API's &redirects param in favor of manual following,
  152. so we can act more realistically (we don't follow double redirects, and
  153. circular redirects don't break us).
  154. This will raise RedirectError if we have a problem following, but that
  155. is a bug and should NOT happen.
  156. If we're following a redirect, this will make a grand total of three
  157. API queries. It's a lot, but each one is quite small.
  158. """
  159. self._load_attributes()
  160. if self._keep_following and self._is_redirect:
  161. self._title = self.get_redirect_target()
  162. self._keep_following = False # don't follow double redirects
  163. self._content = None # reset the content we just loaded
  164. self._load_attributes()
  165. def _load_attributes(self, result=None):
  166. """Load various data from the API in a single query.
  167. Loads self._title, ._exists, ._is_redirect, ._pageid, ._fullurl,
  168. ._protection, ._namespace, ._is_talkpage, ._creator, ._lastrevid, and
  169. ._starttimestamp using the API. It will do a query of its own unless
  170. *result* is provided, in which case we'll pretend *result* is what the
  171. query returned.
  172. Assuming the API is sound, this should not raise any exceptions.
  173. """
  174. if not result:
  175. query = self.site.api_query
  176. result = query(action="query", prop="info|revisions",
  177. inprop="protection|url", rvprop="user", rvlimit=1,
  178. rvdir="newer", titles=self._title)
  179. if "interwiki" in result["query"]:
  180. self._title = result["query"]["interwiki"][0]["title"]
  181. self._exists = self.PAGE_INVALID
  182. return
  183. res = list(result["query"]["pages"].values())[0]
  184. self._title = res["title"] # Normalize our pagename/title
  185. self._is_redirect = "redirect" in res
  186. self._pageid = int(list(result["query"]["pages"].keys())[0])
  187. if self._pageid < 0:
  188. if "missing" in res:
  189. # If it has a negative ID and it's missing; we can still get
  190. # data like the namespace, protection, and URL:
  191. self._exists = self.PAGE_MISSING
  192. else:
  193. # If it has a negative ID and it's invalid, then break here,
  194. # because there's no other data for us to get:
  195. self._exists = self.PAGE_INVALID
  196. return
  197. else:
  198. self._exists = self.PAGE_EXISTS
  199. self._fullurl = res["fullurl"]
  200. self._protection = res["protection"]
  201. self._starttimestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
  202. # We've determined the namespace and talkpage status in __init__()
  203. # based on the title, but now we can be sure:
  204. self._namespace = res["ns"]
  205. self._is_talkpage = self._namespace % 2 == 1 # talkpages have odd IDs
  206. # These last two fields will only be specified if the page exists:
  207. self._lastrevid = res.get("lastrevid")
  208. try:
  209. self._creator = res['revisions'][0]['user']
  210. except KeyError:
  211. pass
  212. def _load_content(self, result=None):
  213. """Load current page content from the API.
  214. If *result* is provided, we'll pretend that is the result of an API
  215. query and try to get content from that. Otherwise, we'll do an API
  216. query on our own.
  217. Don't call this directly, ever; use reload() followed by get() if you
  218. want to force content reloading.
  219. """
  220. if not result:
  221. query = self.site.api_query
  222. result = query(action="query", prop="revisions", rvlimit=1,
  223. rvprop="content|timestamp", rvslots="main",
  224. titles=self._title)
  225. res = list(result["query"]["pages"].values())[0]
  226. try:
  227. revision = res["revisions"][0]
  228. self._content = revision["slots"]["main"]["*"]
  229. self._basetimestamp = revision["timestamp"]
  230. except (KeyError, IndexError):
  231. # This can only happen if the page was deleted since we last called
  232. # self._load_attributes(). In that case, some of our attributes are
  233. # outdated, so force another self._load_attributes():
  234. self._load_attributes()
  235. self._assert_existence()
  236. def _edit(self, params=None, text=None, summary=None, minor=None, bot=None,
  237. force=None, section=None, captcha_id=None, captcha_word=None):
  238. """Edit the page!
  239. If *params* is given, we'll use it as our API query parameters.
  240. Otherwise, we'll build params using the given kwargs via
  241. _build_edit_params().
  242. We'll then try to do the API query, and catch any errors the API raises
  243. in _handle_edit_errors(). We'll then throw these back as subclasses of
  244. EditError.
  245. """
  246. # Weed out invalid pages before we get too far:
  247. self._assert_validity()
  248. # Build our API query string:
  249. if not params:
  250. params = self._build_edit_params(text, summary, minor, bot, force,
  251. section, captcha_id, captcha_word)
  252. else: # Make sure we have the right token:
  253. params["token"] = self.site.get_token()
  254. # Try the API query, catching most errors with our handler:
  255. try:
  256. result = self.site.api_query(**params)
  257. except exceptions.APIError as error:
  258. if not hasattr(error, "code"):
  259. raise # We can only handle errors with a code attribute
  260. result = self._handle_edit_errors(error, params)
  261. # If everything was successful, reset invalidated attributes:
  262. if result["edit"]["result"] == "Success":
  263. self._content = None
  264. self._basetimestamp = None
  265. self._exists = self.PAGE_UNKNOWN
  266. return
  267. # Otherwise, there was some kind of problem. Throw an exception:
  268. raise exceptions.EditError(result["edit"])
  269. def _build_edit_params(self, text, summary, minor, bot, force, section,
  270. captcha_id, captcha_word):
  271. """Given some keyword arguments, build an API edit query string."""
  272. unitxt = text.encode("utf8") if isinstance(text, str) else text
  273. hashed = md5(unitxt).hexdigest() # Checksum to ensure text is correct
  274. params = {
  275. "action": "edit", "title": self._title, "text": text,
  276. "token": self.site.get_token(), "summary": summary, "md5": hashed}
  277. if section:
  278. params["section"] = section
  279. if captcha_id and captcha_word:
  280. params["captchaid"] = captcha_id
  281. params["captchaword"] = captcha_word
  282. if minor:
  283. params["minor"] = "true"
  284. else:
  285. params["notminor"] = "true"
  286. if bot:
  287. params["bot"] = "true"
  288. if not force:
  289. if self._starttimestamp:
  290. params["starttimestamp"] = self._starttimestamp
  291. if self._basetimestamp:
  292. params["basetimestamp"] = self._basetimestamp
  293. if self._exists == self.PAGE_MISSING:
  294. # Page does not exist; don't edit if it already exists:
  295. params["createonly"] = "true"
  296. else:
  297. params["recreate"] = "true"
  298. return params
  299. def _handle_edit_errors(self, error, params, retry=True):
  300. """If our edit fails due to some error, try to handle it.
  301. We'll either raise an appropriate exception (for example, if the page
  302. is protected), or we'll try to fix it (for example, if the token is
  303. invalid, we'll try to get a new one).
  304. """
  305. perms = ["noedit", "noedit-anon", "cantcreate", "cantcreate-anon",
  306. "protectedtitle", "noimageredirect", "noimageredirect-anon",
  307. "blocked"]
  308. if error.code in perms:
  309. raise exceptions.PermissionsError(error.info)
  310. elif error.code in ["editconflict", "pagedeleted", "articleexists"]:
  311. # These attributes are now invalidated:
  312. self._content = None
  313. self._basetimestamp = None
  314. self._exists = self.PAGE_UNKNOWN
  315. raise exceptions.EditConflictError(error.info)
  316. elif error.code == "badtoken" and retry:
  317. params["token"] = self.site.get_token(force=True)
  318. try:
  319. return self.site.api_query(**params)
  320. except exceptions.APIError as err:
  321. if not hasattr(err, "code"):
  322. raise # We can only handle errors with a code attribute
  323. return self._handle_edit_errors(err, params, retry=False)
  324. elif error.code in ["emptypage", "emptynewsection"]:
  325. raise exceptions.NoContentError(error.info)
  326. elif error.code == "contenttoobig":
  327. raise exceptions.ContentTooBigError(error.info)
  328. elif error.code == "spamdetected":
  329. raise exceptions.SpamDetectedError(error.info)
  330. elif error.code == "filtered":
  331. raise exceptions.FilteredError(error.info)
  332. raise exceptions.EditError(": ".join((error.code, error.info)))
  333. @property
  334. def site(self):
  335. """The page's corresponding Site object."""
  336. return self._site
  337. @property
  338. def title(self):
  339. """The page's title, or "pagename".
  340. This won't do any API queries on its own. Any other attributes or
  341. methods that do API queries will reload the title, however, like
  342. :py:attr:`exists` and :py:meth:`get`, potentially "normalizing" it or
  343. following redirects if :py:attr:`self._follow_redirects` is ``True``.
  344. """
  345. return self._title
  346. @property
  347. def exists(self):
  348. """Whether or not the page exists.
  349. This will be a number; its value does not matter, but it will equal
  350. one of :py:attr:`self.PAGE_INVALID <PAGE_INVALID>`,
  351. :py:attr:`self.PAGE_MISSING <PAGE_MISSING>`, or
  352. :py:attr:`self.PAGE_EXISTS <PAGE_EXISTS>`.
  353. Makes an API query only if we haven't already made one.
  354. """
  355. if self._exists == self.PAGE_UNKNOWN:
  356. self._load()
  357. return self._exists
  358. @property
  359. def pageid(self):
  360. """An integer ID representing the page.
  361. Makes an API query only if we haven't already made one and the *pageid*
  362. parameter to :py:meth:`__init__` was left as ``None``, which should be
  363. true for all cases except when pages are returned by an SQL generator
  364. (like :py:meth:`category.get_members()
  365. <earwigbot.wiki.category.Category.get_members>`).
  366. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  367. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  368. invalid or the page does not exist, respectively.
  369. """
  370. if self._pageid:
  371. return self._pageid
  372. if self._exists == self.PAGE_UNKNOWN:
  373. self._load()
  374. self._assert_existence() # Missing pages do not have IDs
  375. return self._pageid
  376. @property
  377. def url(self):
  378. """The page's URL.
  379. Like :py:meth:`title`, this won't do any API queries on its own. If the
  380. API was never queried for this page, we will attempt to determine the
  381. URL ourselves based on the title.
  382. """
  383. if self._fullurl:
  384. return self._fullurl
  385. else:
  386. encoded = self._title.encode("utf8").replace(" ", "_")
  387. slug = quote(encoded, safe="/:").decode("utf8")
  388. path = self.site._article_path.replace("$1", slug)
  389. return "".join((self.site.url, path))
  390. @property
  391. def namespace(self):
  392. """The page's namespace ID (an integer).
  393. Like :py:meth:`title`, this won't do any API queries on its own. If the
  394. API was never queried for this page, we will attempt to determine the
  395. namespace ourselves based on the title.
  396. """
  397. return self._namespace
  398. @property
  399. def lastrevid(self):
  400. """The ID of the page's most recent revision.
  401. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  402. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  403. invalid or the page does not exist, respectively.
  404. """
  405. if self._exists == self.PAGE_UNKNOWN:
  406. self._load()
  407. self._assert_existence() # Missing pages don't have revisions
  408. return self._lastrevid
  409. @property
  410. def protection(self):
  411. """The page's current protection status.
  412. Makes an API query only if we haven't already made one.
  413. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` if the page
  414. name is invalid. Won't raise an error if the page is missing because
  415. those can still be create-protected.
  416. """
  417. if self._exists == self.PAGE_UNKNOWN:
  418. self._load()
  419. self._assert_validity() # Invalid pages cannot be protected
  420. return self._protection
  421. @property
  422. def is_talkpage(self):
  423. """``True`` if the page is a talkpage, otherwise ``False``.
  424. Like :py:meth:`title`, this won't do any API queries on its own. If the
  425. API was never queried for this page, we will attempt to determine
  426. whether it is a talkpage ourselves based on its namespace.
  427. """
  428. return self._is_talkpage
  429. @property
  430. def is_redirect(self):
  431. """``True`` if the page is a redirect, otherwise ``False``.
  432. Makes an API query only if we haven't already made one.
  433. We will return ``False`` even if the page does not exist or is invalid.
  434. """
  435. if self._exists == self.PAGE_UNKNOWN:
  436. self._load()
  437. return self._is_redirect
  438. def reload(self):
  439. """Forcibly reload the page's attributes.
  440. Emphasis on *reload*: this is only necessary if there is reason to
  441. believe they have changed.
  442. """
  443. self._load()
  444. if self._content is not None:
  445. # Only reload content if it has already been loaded:
  446. self._load_content()
  447. def toggle_talk(self, follow_redirects=None):
  448. """Return a content page's talk page, or vice versa.
  449. The title of the new page is determined by namespace logic, not API
  450. queries. We won't make any API queries on our own.
  451. If *follow_redirects* is anything other than ``None`` (the default), it
  452. will be passed to the new :py:class:`~earwigbot.wiki.page.Page`
  453. object's :py:meth:`__init__`. Otherwise, we'll use the value passed to
  454. our own :py:meth:`__init__`.
  455. Will raise :py:exc:`~earwigbot.exceptions.InvalidPageError` if we try
  456. to get the talk page of a special page (in the ``Special:`` or
  457. ``Media:`` namespaces), but we won't raise an exception if our page is
  458. otherwise missing or invalid.
  459. """
  460. if self._namespace < 0:
  461. ns = self.site.namespace_id_to_name(self._namespace)
  462. e = "Pages in the {0} namespace can't have talk pages.".format(ns)
  463. raise exceptions.InvalidPageError(e)
  464. if self._is_talkpage:
  465. new_ns = self._namespace - 1
  466. else:
  467. new_ns = self._namespace + 1
  468. if self._namespace != 0:
  469. body = self._title.split(":", 1)[1]
  470. else:
  471. body = self._title
  472. new_prefix = self.site.namespace_id_to_name(new_ns)
  473. # If the new page is in namespace 0, don't do ":Title" (it's correct,
  474. # but unnecessary), just do "Title":
  475. if new_prefix:
  476. new_title = ":".join((new_prefix, body))
  477. else:
  478. new_title = body
  479. if follow_redirects is None:
  480. follow_redirects = self._follow_redirects
  481. return Page(self.site, new_title, follow_redirects)
  482. def get(self):
  483. """Return page content, which is cached if you try to call get again.
  484. Raises InvalidPageError or PageNotFoundError if the page name is
  485. invalid or the page does not exist, respectively.
  486. """
  487. if self._exists == self.PAGE_UNKNOWN:
  488. # Kill two birds with one stone by doing an API query for both our
  489. # attributes and our page content:
  490. query = self.site.api_query
  491. result = query(action="query", rvlimit=1, titles=self._title,
  492. prop="info|revisions", inprop="protection|url",
  493. rvprop="content|timestamp", rvslots="main")
  494. self._load_attributes(result=result)
  495. self._assert_existence()
  496. self._load_content(result=result)
  497. # Follow redirects if we're told to:
  498. if self._keep_following and self._is_redirect:
  499. self._title = self.get_redirect_target()
  500. self._keep_following = False # Don't follow double redirects
  501. self._exists = self.PAGE_UNKNOWN # Force another API query
  502. self.get()
  503. return self._content
  504. # Make sure we're dealing with a real page here. This may be outdated
  505. # if the page was deleted since we last called self._load_attributes(),
  506. # but self._load_content() can handle that:
  507. self._assert_existence()
  508. if self._content is None:
  509. self._load_content()
  510. return self._content
  511. def get_redirect_target(self):
  512. """If the page is a redirect, return its destination.
  513. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  514. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  515. invalid or the page does not exist, respectively. Raises
  516. :py:exc:`~earwigbot.exceptions.RedirectError` if the page is not a
  517. redirect.
  518. """
  519. re_redirect = r"^\s*\#\s*redirect\s*\[\[(.*?)\]\]"
  520. content = self.get()
  521. try:
  522. return re.findall(re_redirect, content, flags=re.I)[0]
  523. except IndexError:
  524. e = "The page does not appear to have a redirect target."
  525. raise exceptions.RedirectError(e)
  526. def get_creator(self):
  527. """Return the User object for the first person to edit the page.
  528. Makes an API query only if we haven't already made one. Normally, we
  529. can get the creator along with everything else (except content) in
  530. :py:meth:`_load_attributes`. However, due to a limitation in the API
  531. (can't get the editor of one revision and the content of another at
  532. both ends of the history), if our other attributes were only loaded
  533. through :py:meth:`get`, we'll have to do another API query.
  534. Raises :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  535. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  536. invalid or the page does not exist, respectively.
  537. """
  538. if self._exists == self.PAGE_UNKNOWN:
  539. self._load()
  540. self._assert_existence()
  541. if not self._creator:
  542. self._load()
  543. self._assert_existence()
  544. return self.site.get_user(self._creator)
  545. def parse(self):
  546. """Parse the page content for templates, links, etc.
  547. Actual parsing is handled by :py:mod:`mwparserfromhell`. Raises
  548. :py:exc:`~earwigbot.exceptions.InvalidPageError` or
  549. :py:exc:`~earwigbot.exceptions.PageNotFoundError` if the page name is
  550. invalid or the page does not exist, respectively.
  551. """
  552. return mwparserfromhell.parse(self.get())
  553. def edit(self, text, summary, minor=False, bot=True, force=False):
  554. """Replace the page's content or creates a new page.
  555. *text* is the new page content, with *summary* as the edit summary.
  556. If *minor* is ``True``, the edit will be marked as minor. If *bot* is
  557. ``True``, the edit will be marked as a bot edit, but only if we
  558. actually have a bot flag.
  559. Use *force* to push the new content even if there's an edit conflict or
  560. the page was deleted/recreated between getting our edit token and
  561. editing our page. Be careful with this!
  562. """
  563. self._edit(text=text, summary=summary, minor=minor, bot=bot,
  564. force=force)
  565. def add_section(self, text, title, minor=False, bot=True, force=False):
  566. """Add a new section to the bottom of the page.
  567. The arguments for this are the same as those for :py:meth:`edit`, but
  568. instead of providing a summary, you provide a section title. Likewise,
  569. raised exceptions are the same as :py:meth:`edit`'s.
  570. This should create the page if it does not already exist, with just the
  571. new section as content.
  572. """
  573. self._edit(text=text, summary=title, minor=minor, bot=bot, force=force,
  574. section="new")
  575. def check_exclusion(self, username=None, optouts=None):
  576. """Check whether or not we are allowed to edit the page.
  577. Return ``True`` if we *are* allowed to edit this page, and ``False`` if
  578. we aren't.
  579. *username* is used to determine whether we are part of a specific list
  580. of allowed or disallowed bots (e.g. ``{{bots|allow=EarwigBot}}`` or
  581. ``{{bots|deny=FooBot,EarwigBot}}``). It's ``None`` by default, which
  582. will swipe our username from :py:meth:`site.get_user()
  583. <earwigbot.wiki.site.Site.get_user>`.\
  584. :py:attr:`~earwigbot.wiki.user.User.name`.
  585. *optouts* is a list of messages to consider this check as part of for
  586. the purpose of opt-out; it defaults to ``None``, which ignores the
  587. parameter completely. For example, if *optouts* is ``["nolicense"]``,
  588. we'll return ``False`` on ``{{bots|optout=nolicense}}`` or
  589. ``{{bots|optout=all}}``, but `True` on
  590. ``{{bots|optout=orfud,norationale,replaceable}}``.
  591. """
  592. def parse_param(template, param):
  593. value = template.get(param).value
  594. return [item.strip().lower() for item in value.split(",")]
  595. if not username:
  596. username = self.site.get_user().name
  597. # Lowercase everything:
  598. username = username.lower()
  599. optouts = [optout.lower() for optout in optouts] if optouts else []
  600. r_bots = r"\{\{\s*(no)?bots\s*(\||\}\})"
  601. filter = self.parse().ifilter_templates(recursive=True, matches=r_bots)
  602. for template in filter:
  603. if template.has_param("deny"):
  604. denies = parse_param(template, "deny")
  605. if "all" in denies or username in denies:
  606. return False
  607. if template.has_param("allow"):
  608. allows = parse_param(template, "allow")
  609. if "all" in allows or username in allows:
  610. continue
  611. if optouts and template.has_param("optout"):
  612. tasks = parse_param(template, "optout")
  613. matches = [optout in tasks for optout in optouts]
  614. if "all" in tasks or any(matches):
  615. return False
  616. if template.name.strip().lower() == "nobots":
  617. return False
  618. return True