A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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