A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

265 satır
10 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 time import gmtime, strptime
  23. from earwigbot.wiki.constants import *
  24. from earwigbot.wiki.exceptions import UserNotFoundError
  25. from earwigbot.wiki.page import Page
  26. __all__ = ["User"]
  27. class User(object):
  28. """
  29. EarwigBot's Wiki Toolset: User Class
  30. Represents a User on a given Site. Has methods for getting a bunch of
  31. information about the user, such as editcount and user rights, methods for
  32. returning the user's userpage and talkpage, etc.
  33. Public methods:
  34. name -- returns the user's username
  35. exists -- returns True if the user exists, False if they do not
  36. userid -- returns an integer ID representing the user
  37. blockinfo -- returns information about a current block on the user
  38. groups -- returns a list of the user's groups
  39. rights -- returns a list of the user's rights
  40. editcount -- returns the number of edits made by the user
  41. registration -- returns the time the user registered as a time.struct_time
  42. emailable -- returns True if you can email the user, False if you cannot
  43. gender -- returns the user's gender ("male", "female", or "unknown")
  44. get_userpage -- returns a Page object representing the user's userpage
  45. get_talkpage -- returns a Page object representing the user's talkpage
  46. """
  47. def __init__(self, site, name):
  48. """Constructor for new User instances.
  49. Takes two arguments, a Site object (necessary for doing API queries),
  50. and the name of the user, preferably without "User:" in front, although
  51. this prefix will be automatically removed by the API if given.
  52. You can also use site.get_user() instead, which returns a User object,
  53. and is preferred.
  54. We won't do any API queries yet for basic information about the user -
  55. save that for when the information is requested.
  56. """
  57. self._site = site
  58. self._name = name
  59. def __repr__(self):
  60. """Returns the canonical string representation of the User."""
  61. return "User(name={0!r}, site={1!r})".format(self._name, self._site)
  62. def __str__(self):
  63. """Returns a nice string representation of the User."""
  64. return '<User "{0}" of {1}>'.format(self.name(), str(self._site))
  65. def _get_attribute(self, attr, force):
  66. """Internally used to get an attribute by name.
  67. We'll call _load_attributes() to get this (and all other attributes)
  68. from the API if it is not already defined. If `force` is True, we'll
  69. re-load them even if they've already been loaded.
  70. Raises UserNotFoundError if a nonexistant user prevents us from
  71. returning a certain attribute.
  72. """
  73. if not hasattr(self, attr) or force:
  74. self._load_attributes()
  75. if self._exists is False:
  76. e = "User '{0}' does not exist.".format(self._name)
  77. raise UserNotFoundError(e)
  78. return getattr(self, attr)
  79. def _load_attributes(self):
  80. """Internally used to load all attributes from the API.
  81. Normally, this is called by _get_attribute() when a requested attribute
  82. is not defined. This defines it.
  83. """
  84. params = {"action": "query", "list": "users", "ususers": self._name,
  85. "usprop": "blockinfo|groups|rights|editcount|registration|emailable|gender"}
  86. result = self._site._api_query(params)
  87. res = result["query"]["users"][0]
  88. # normalize our username in case it was entered oddly
  89. self._name = res["name"]
  90. try:
  91. self._userid = res["userid"]
  92. except KeyError: # userid is missing, so user does not exist
  93. self._exists = False
  94. return
  95. self._exists = True
  96. try:
  97. self._blockinfo = {
  98. "by": res["blockedby"],
  99. "reason": res["blockreason"],
  100. "expiry": res["blockexpiry"]
  101. }
  102. except KeyError:
  103. self._blockinfo = False
  104. self._groups = res["groups"]
  105. try:
  106. self._rights = res["rights"].values()
  107. except AttributeError:
  108. self._rights = res["rights"]
  109. self._editcount = res["editcount"]
  110. reg = res["registration"]
  111. try:
  112. self._registration = strptime(reg, "%Y-%m-%dT%H:%M:%SZ")
  113. except TypeError:
  114. # Sometimes the API doesn't give a date; the user's probably really
  115. # old. There's nothing else we can do!
  116. self._registration = gmtime(0)
  117. try:
  118. res["emailable"]
  119. except KeyError:
  120. self._emailable = False
  121. else:
  122. self._emailable = True
  123. self._gender = res["gender"]
  124. def name(self, force=False):
  125. """Returns the user's name.
  126. If `force` is True, we will load the name from the API and return that.
  127. This could potentially return a "normalized" version of the name - for
  128. example, without a "User:" prefix or without underscores. Unlike other
  129. attribute getters, this will never make an API query without `force`.
  130. Note that if another attribute getter, like exists(), has already been
  131. called, then the username has already been normalized.
  132. """
  133. if force:
  134. self._load_attributes()
  135. return self._name
  136. def exists(self, force=False):
  137. """Returns True if the user exists, or False if they do not.
  138. Makes an API query if `force` is True or if we haven't made one
  139. already.
  140. """
  141. if not hasattr(self, "_exists") or force:
  142. self._load_attributes()
  143. return self._exists
  144. def userid(self, force=False):
  145. """Returns an integer ID used by MediaWiki to represent the user.
  146. Raises UserNotFoundError if the user does not exist. Makes an API query
  147. if `force` is True or if we haven't made one already.
  148. """
  149. return self._get_attribute("_userid", force)
  150. def blockinfo(self, force=False):
  151. """Returns information about a current block on the user.
  152. If the user is not blocked, returns False. If they are, returns a dict
  153. with three keys: "by" is the blocker's username, "reason" is the reason
  154. why they were blocked, and "expiry" is when the block expires.
  155. Raises UserNotFoundError if the user does not exist. Makes an API query
  156. if `force` is True or if we haven't made one already.
  157. """
  158. return self._get_attribute("_blockinfo", force)
  159. def groups(self, force=False):
  160. """Returns a list of groups this user is in, including "*".
  161. Raises UserNotFoundError if the user does not exist. Makes an API query
  162. if `force` is True or if we haven't made one already.
  163. """
  164. return self._get_attribute("_groups", force)
  165. def rights(self, force=False):
  166. """Returns a list of this user's rights.
  167. Raises UserNotFoundError if the user does not exist. Makes an API query
  168. if `force` is True or if we haven't made one already.
  169. """
  170. return self._get_attribute("_rights", force)
  171. def editcount(self, force=False):
  172. """Returns the number of edits made by the user.
  173. Raises UserNotFoundError if the user does not exist. Makes an API query
  174. if `force` is True or if we haven't made one already.
  175. """
  176. return self._get_attribute("_editcount", force)
  177. def registration(self, force=False):
  178. """Returns the time the user registered as a time.struct_time object.
  179. Raises UserNotFoundError if the user does not exist. Makes an API query
  180. if `force` is True or if we haven't made one already.
  181. """
  182. return self._get_attribute("_registration", force)
  183. def emailable(self, force=False):
  184. """Returns True if the user can be emailed, or False if they cannot.
  185. Raises UserNotFoundError if the user does not exist. Makes an API query
  186. if `force` is True or if we haven't made one already.
  187. """
  188. return self._get_attribute("_emailable", force)
  189. def gender(self, force=False):
  190. """Returns the user's gender.
  191. Can return either "male", "female", or "unknown", if they did not
  192. specify it.
  193. Raises UserNotFoundError if the user does not exist. Makes an API query
  194. if `force` is True or if we haven't made one already.
  195. """
  196. return self._get_attribute("_gender", force)
  197. def get_userpage(self):
  198. """Returns a Page object representing the user's userpage.
  199. No checks are made to see if it exists or not. Proper site namespace
  200. conventions are followed.
  201. """
  202. prefix = self._site.namespace_id_to_name(NS_USER)
  203. pagename = ':'.join((prefix, self._name))
  204. return Page(self._site, pagename)
  205. def get_talkpage(self):
  206. """Returns a Page object representing the user's talkpage.
  207. No checks are made to see if it exists or not. Proper site namespace
  208. conventions are followed.
  209. """
  210. prefix = self._site.namespace_id_to_name(NS_USER_TALK)
  211. pagename = ':'.join((prefix, self._name))
  212. return Page(self._site, pagename)