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.

725 regels
29 KiB

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